cover.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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" /* POOL_ctx */
  31. #include "../common/threading.h" /* ZSTD_pthread_mutex_t */
  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 = (size_t)(last - first);
  282. assert(last >= first);
  283. while (count != 0) {
  284. size_t step = count / 2;
  285. const size_t *ptr = first;
  286. ptr += step;
  287. if (*ptr < value) {
  288. first = ++ptr;
  289. count -= step + 1;
  290. } else {
  291. count = step;
  292. }
  293. }
  294. return first;
  295. }
  296. /**
  297. * Generic groupBy function.
  298. * Groups an array sorted by cmp into groups with equivalent values.
  299. * Calls grp for each group.
  300. */
  301. static void
  302. COVER_groupBy(const void *data, size_t count, size_t size, COVER_ctx_t *ctx,
  303. int (*cmp)(COVER_ctx_t *, const void *, const void *),
  304. void (*grp)(COVER_ctx_t *, const void *, const void *)) {
  305. const BYTE *ptr = (const BYTE *)data;
  306. size_t num = 0;
  307. while (num < count) {
  308. const BYTE *grpEnd = ptr + size;
  309. ++num;
  310. while (num < count && cmp(ctx, ptr, grpEnd) == 0) {
  311. grpEnd += size;
  312. ++num;
  313. }
  314. grp(ctx, ptr, grpEnd);
  315. ptr = grpEnd;
  316. }
  317. }
  318. /*-*************************************
  319. * Cover functions
  320. ***************************************/
  321. /**
  322. * Called on each group of positions with the same dmer.
  323. * Counts the frequency of each dmer and saves it in the suffix array.
  324. * Fills `ctx->dmerAt`.
  325. */
  326. static void COVER_group(COVER_ctx_t *ctx, const void *group,
  327. const void *groupEnd) {
  328. /* The group consists of all the positions with the same first d bytes. */
  329. const U32 *grpPtr = (const U32 *)group;
  330. const U32 *grpEnd = (const U32 *)groupEnd;
  331. /* The dmerId is how we will reference this dmer.
  332. * This allows us to map the whole dmer space to a much smaller space, the
  333. * size of the suffix array.
  334. */
  335. const U32 dmerId = (U32)(grpPtr - ctx->suffix);
  336. /* Count the number of samples this dmer shows up in */
  337. U32 freq = 0;
  338. /* Details */
  339. const size_t *curOffsetPtr = ctx->offsets;
  340. const size_t *offsetsEnd = ctx->offsets + ctx->nbSamples;
  341. /* Once *grpPtr >= curSampleEnd this occurrence of the dmer is in a
  342. * different sample than the last.
  343. */
  344. size_t curSampleEnd = ctx->offsets[0];
  345. for (; grpPtr != grpEnd; ++grpPtr) {
  346. /* Save the dmerId for this position so we can get back to it. */
  347. ctx->dmerAt[*grpPtr] = dmerId;
  348. /* Dictionaries only help for the first reference to the dmer.
  349. * After that zstd can reference the match from the previous reference.
  350. * So only count each dmer once for each sample it is in.
  351. */
  352. if (*grpPtr < curSampleEnd) {
  353. continue;
  354. }
  355. freq += 1;
  356. /* Binary search to find the end of the sample *grpPtr is in.
  357. * In the common case that grpPtr + 1 == grpEnd we can skip the binary
  358. * search because the loop is over.
  359. */
  360. if (grpPtr + 1 != grpEnd) {
  361. const size_t *sampleEndPtr =
  362. COVER_lower_bound(curOffsetPtr, offsetsEnd, *grpPtr);
  363. curSampleEnd = *sampleEndPtr;
  364. curOffsetPtr = sampleEndPtr + 1;
  365. }
  366. }
  367. /* At this point we are never going to look at this segment of the suffix
  368. * array again. We take advantage of this fact to save memory.
  369. * We store the frequency of the dmer in the first position of the group,
  370. * which is dmerId.
  371. */
  372. ctx->suffix[dmerId] = freq;
  373. }
  374. /**
  375. * Selects the best segment in an epoch.
  376. * Segments of are scored according to the function:
  377. *
  378. * Let F(d) be the frequency of dmer d.
  379. * Let S_i be the dmer at position i of segment S which has length k.
  380. *
  381. * Score(S) = F(S_1) + F(S_2) + ... + F(S_{k-d+1})
  382. *
  383. * Once the dmer d is in the dictionary we set F(d) = 0.
  384. */
  385. static COVER_segment_t COVER_selectSegment(const COVER_ctx_t *ctx, U32 *freqs,
  386. COVER_map_t *activeDmers, U32 begin,
  387. U32 end,
  388. ZDICT_cover_params_t parameters) {
  389. /* Constants */
  390. const U32 k = parameters.k;
  391. const U32 d = parameters.d;
  392. const U32 dmersInK = k - d + 1;
  393. /* Try each segment (activeSegment) and save the best (bestSegment) */
  394. COVER_segment_t bestSegment = {0, 0, 0};
  395. COVER_segment_t activeSegment;
  396. /* Reset the activeDmers in the segment */
  397. COVER_map_clear(activeDmers);
  398. /* The activeSegment starts at the beginning of the epoch. */
  399. activeSegment.begin = begin;
  400. activeSegment.end = begin;
  401. activeSegment.score = 0;
  402. /* Slide the activeSegment through the whole epoch.
  403. * Save the best segment in bestSegment.
  404. */
  405. while (activeSegment.end < end) {
  406. /* The dmerId for the dmer at the next position */
  407. U32 newDmer = ctx->dmerAt[activeSegment.end];
  408. /* The entry in activeDmers for this dmerId */
  409. U32 *newDmerOcc = COVER_map_at(activeDmers, newDmer);
  410. /* If the dmer isn't already present in the segment add its score. */
  411. if (*newDmerOcc == 0) {
  412. /* The paper suggest using the L-0.5 norm, but experiments show that it
  413. * doesn't help.
  414. */
  415. activeSegment.score += freqs[newDmer];
  416. }
  417. /* Add the dmer to the segment */
  418. activeSegment.end += 1;
  419. *newDmerOcc += 1;
  420. /* If the window is now too large, drop the first position */
  421. if (activeSegment.end - activeSegment.begin == dmersInK + 1) {
  422. U32 delDmer = ctx->dmerAt[activeSegment.begin];
  423. U32 *delDmerOcc = COVER_map_at(activeDmers, delDmer);
  424. activeSegment.begin += 1;
  425. *delDmerOcc -= 1;
  426. /* If this is the last occurrence of the dmer, subtract its score */
  427. if (*delDmerOcc == 0) {
  428. COVER_map_remove(activeDmers, delDmer);
  429. activeSegment.score -= freqs[delDmer];
  430. }
  431. }
  432. /* If this segment is the best so far save it */
  433. if (activeSegment.score > bestSegment.score) {
  434. bestSegment = activeSegment;
  435. }
  436. }
  437. {
  438. /* Trim off the zero frequency head and tail from the segment. */
  439. U32 newBegin = bestSegment.end;
  440. U32 newEnd = bestSegment.begin;
  441. U32 pos;
  442. for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
  443. U32 freq = freqs[ctx->dmerAt[pos]];
  444. if (freq != 0) {
  445. newBegin = MIN(newBegin, pos);
  446. newEnd = pos + 1;
  447. }
  448. }
  449. bestSegment.begin = newBegin;
  450. bestSegment.end = newEnd;
  451. }
  452. {
  453. /* Zero out the frequency of each dmer covered by the chosen segment. */
  454. U32 pos;
  455. for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
  456. freqs[ctx->dmerAt[pos]] = 0;
  457. }
  458. }
  459. return bestSegment;
  460. }
  461. /**
  462. * Check the validity of the parameters.
  463. * Returns non-zero if the parameters are valid and 0 otherwise.
  464. */
  465. static int COVER_checkParameters(ZDICT_cover_params_t parameters,
  466. size_t maxDictSize) {
  467. /* k and d are required parameters */
  468. if (parameters.d == 0 || parameters.k == 0) {
  469. return 0;
  470. }
  471. /* k <= maxDictSize */
  472. if (parameters.k > maxDictSize) {
  473. return 0;
  474. }
  475. /* d <= k */
  476. if (parameters.d > parameters.k) {
  477. return 0;
  478. }
  479. /* 0 < splitPoint <= 1 */
  480. if (parameters.splitPoint <= 0 || parameters.splitPoint > 1){
  481. return 0;
  482. }
  483. return 1;
  484. }
  485. /**
  486. * Clean up a context initialized with `COVER_ctx_init()`.
  487. */
  488. static void COVER_ctx_destroy(COVER_ctx_t *ctx) {
  489. if (!ctx) {
  490. return;
  491. }
  492. if (ctx->suffix) {
  493. free(ctx->suffix);
  494. ctx->suffix = NULL;
  495. }
  496. if (ctx->freqs) {
  497. free(ctx->freqs);
  498. ctx->freqs = NULL;
  499. }
  500. if (ctx->dmerAt) {
  501. free(ctx->dmerAt);
  502. ctx->dmerAt = NULL;
  503. }
  504. if (ctx->offsets) {
  505. free(ctx->offsets);
  506. ctx->offsets = NULL;
  507. }
  508. }
  509. /**
  510. * Prepare a context for dictionary building.
  511. * The context is only dependent on the parameter `d` and can be used multiple
  512. * times.
  513. * Returns 0 on success or error code on error.
  514. * The context must be destroyed with `COVER_ctx_destroy()`.
  515. */
  516. static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer,
  517. const size_t *samplesSizes, unsigned nbSamples,
  518. unsigned d, double splitPoint)
  519. {
  520. const BYTE *const samples = (const BYTE *)samplesBuffer;
  521. const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
  522. /* Split samples into testing and training sets */
  523. const unsigned nbTrainSamples = splitPoint < 1.0 ? (unsigned)((double)nbSamples * splitPoint) : nbSamples;
  524. const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples;
  525. const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize;
  526. const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize;
  527. /* Checks */
  528. if (totalSamplesSize < MAX(d, sizeof(U64)) ||
  529. totalSamplesSize >= (size_t)COVER_MAX_SAMPLES_SIZE) {
  530. DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n",
  531. (unsigned)(totalSamplesSize>>20), (COVER_MAX_SAMPLES_SIZE >> 20));
  532. return ERROR(srcSize_wrong);
  533. }
  534. /* Check if there are at least 5 training samples */
  535. if (nbTrainSamples < 5) {
  536. DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid.", nbTrainSamples);
  537. return ERROR(srcSize_wrong);
  538. }
  539. /* Check if there's testing sample */
  540. if (nbTestSamples < 1) {
  541. DISPLAYLEVEL(1, "Total number of testing samples is %u and is invalid.", nbTestSamples);
  542. return ERROR(srcSize_wrong);
  543. }
  544. /* Zero the context */
  545. memset(ctx, 0, sizeof(*ctx));
  546. DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples,
  547. (unsigned)trainingSamplesSize);
  548. DISPLAYLEVEL(2, "Testing on %u samples of total size %u\n", nbTestSamples,
  549. (unsigned)testSamplesSize);
  550. ctx->samples = samples;
  551. ctx->samplesSizes = samplesSizes;
  552. ctx->nbSamples = nbSamples;
  553. ctx->nbTrainSamples = nbTrainSamples;
  554. ctx->nbTestSamples = nbTestSamples;
  555. /* Partial suffix array */
  556. ctx->suffixSize = trainingSamplesSize - MAX(d, sizeof(U64)) + 1;
  557. ctx->suffix = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
  558. /* Maps index to the dmerID */
  559. ctx->dmerAt = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
  560. /* The offsets of each file */
  561. ctx->offsets = (size_t *)malloc((nbSamples + 1) * sizeof(size_t));
  562. if (!ctx->suffix || !ctx->dmerAt || !ctx->offsets) {
  563. DISPLAYLEVEL(1, "Failed to allocate scratch buffers\n");
  564. COVER_ctx_destroy(ctx);
  565. return ERROR(memory_allocation);
  566. }
  567. ctx->freqs = NULL;
  568. ctx->d = d;
  569. /* Fill offsets from the samplesSizes */
  570. {
  571. U32 i;
  572. ctx->offsets[0] = 0;
  573. for (i = 1; i <= nbSamples; ++i) {
  574. ctx->offsets[i] = ctx->offsets[i - 1] + samplesSizes[i - 1];
  575. }
  576. }
  577. DISPLAYLEVEL(2, "Constructing partial suffix array\n");
  578. {
  579. /* suffix is a partial suffix array.
  580. * It only sorts suffixes by their first parameters.d bytes.
  581. * The sort is stable, so each dmer group is sorted by position in input.
  582. */
  583. U32 i;
  584. for (i = 0; i < ctx->suffixSize; ++i) {
  585. ctx->suffix[i] = i;
  586. }
  587. /* qsort doesn't take an opaque pointer, so pass as a global.
  588. * On OpenBSD qsort() is not guaranteed to be stable, their mergesort() is.
  589. */
  590. g_coverCtx = ctx;
  591. #if defined(__OpenBSD__)
  592. mergesort(ctx->suffix, ctx->suffixSize, sizeof(U32),
  593. (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
  594. #else
  595. qsort(ctx->suffix, ctx->suffixSize, sizeof(U32),
  596. (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
  597. #endif
  598. }
  599. DISPLAYLEVEL(2, "Computing frequencies\n");
  600. /* For each dmer group (group of positions with the same first d bytes):
  601. * 1. For each position we set dmerAt[position] = dmerID. The dmerID is
  602. * (groupBeginPtr - suffix). This allows us to go from position to
  603. * dmerID so we can look up values in freq.
  604. * 2. We calculate how many samples the dmer occurs in and save it in
  605. * freqs[dmerId].
  606. */
  607. COVER_groupBy(ctx->suffix, ctx->suffixSize, sizeof(U32), ctx,
  608. (ctx->d <= 8 ? &COVER_cmp8 : &COVER_cmp), &COVER_group);
  609. ctx->freqs = ctx->suffix;
  610. ctx->suffix = NULL;
  611. return 0;
  612. }
  613. void COVER_warnOnSmallCorpus(size_t maxDictSize, size_t nbDmers, int displayLevel)
  614. {
  615. const double ratio = (double)nbDmers / (double)maxDictSize;
  616. if (ratio >= 10) {
  617. return;
  618. }
  619. LOCALDISPLAYLEVEL(displayLevel, 1,
  620. "WARNING: The maximum dictionary size %u is too large "
  621. "compared to the source size %u! "
  622. "size(source)/size(dictionary) = %f, but it should be >= "
  623. "10! This may lead to a subpar dictionary! We recommend "
  624. "training on sources at least 10x, and preferably 100x "
  625. "the size of the dictionary! \n", (U32)maxDictSize,
  626. (U32)nbDmers, ratio);
  627. }
  628. COVER_epoch_info_t COVER_computeEpochs(U32 maxDictSize,
  629. U32 nbDmers, U32 k, U32 passes)
  630. {
  631. const U32 minEpochSize = k * 10;
  632. COVER_epoch_info_t epochs;
  633. epochs.num = MAX(1, maxDictSize / k / passes);
  634. epochs.size = nbDmers / epochs.num;
  635. if (epochs.size >= minEpochSize) {
  636. assert(epochs.size * epochs.num <= nbDmers);
  637. return epochs;
  638. }
  639. epochs.size = MIN(minEpochSize, nbDmers);
  640. epochs.num = nbDmers / epochs.size;
  641. assert(epochs.size * epochs.num <= nbDmers);
  642. return epochs;
  643. }
  644. /**
  645. * Given the prepared context build the dictionary.
  646. */
  647. static size_t COVER_buildDictionary(const COVER_ctx_t *ctx, U32 *freqs,
  648. COVER_map_t *activeDmers, void *dictBuffer,
  649. size_t dictBufferCapacity,
  650. ZDICT_cover_params_t parameters) {
  651. BYTE *const dict = (BYTE *)dictBuffer;
  652. size_t tail = dictBufferCapacity;
  653. /* Divide the data into epochs. We will select one segment from each epoch. */
  654. const COVER_epoch_info_t epochs = COVER_computeEpochs(
  655. (U32)dictBufferCapacity, (U32)ctx->suffixSize, parameters.k, 4);
  656. const size_t maxZeroScoreRun = MAX(10, MIN(100, epochs.num >> 3));
  657. size_t zeroScoreRun = 0;
  658. size_t epoch;
  659. DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n",
  660. (U32)epochs.num, (U32)epochs.size);
  661. /* Loop through the epochs until there are no more segments or the dictionary
  662. * is full.
  663. */
  664. for (epoch = 0; tail > 0; epoch = (epoch + 1) % epochs.num) {
  665. const U32 epochBegin = (U32)(epoch * epochs.size);
  666. const U32 epochEnd = epochBegin + epochs.size;
  667. size_t segmentSize;
  668. /* Select a segment */
  669. COVER_segment_t segment = COVER_selectSegment(
  670. ctx, freqs, activeDmers, epochBegin, epochEnd, parameters);
  671. /* If the segment covers no dmers, then we are out of content.
  672. * There may be new content in other epochs, for continue for some time.
  673. */
  674. if (segment.score == 0) {
  675. if (++zeroScoreRun >= maxZeroScoreRun) {
  676. break;
  677. }
  678. continue;
  679. }
  680. zeroScoreRun = 0;
  681. /* Trim the segment if necessary and if it is too small then we are done */
  682. segmentSize = MIN(segment.end - segment.begin + parameters.d - 1, tail);
  683. if (segmentSize < parameters.d) {
  684. break;
  685. }
  686. /* We fill the dictionary from the back to allow the best segments to be
  687. * referenced with the smallest offsets.
  688. */
  689. tail -= segmentSize;
  690. memcpy(dict + tail, ctx->samples + segment.begin, segmentSize);
  691. DISPLAYUPDATE(
  692. 2, "\r%u%% ",
  693. (unsigned)(((dictBufferCapacity - tail) * 100) / dictBufferCapacity));
  694. }
  695. DISPLAYLEVEL(2, "\r%79s\r", "");
  696. return tail;
  697. }
  698. ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_cover(
  699. void *dictBuffer, size_t dictBufferCapacity,
  700. const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
  701. ZDICT_cover_params_t parameters)
  702. {
  703. BYTE* const dict = (BYTE*)dictBuffer;
  704. COVER_ctx_t ctx;
  705. COVER_map_t activeDmers;
  706. parameters.splitPoint = 1.0;
  707. /* Initialize global data */
  708. g_displayLevel = (int)parameters.zParams.notificationLevel;
  709. /* Checks */
  710. if (!COVER_checkParameters(parameters, dictBufferCapacity)) {
  711. DISPLAYLEVEL(1, "Cover parameters incorrect\n");
  712. return ERROR(parameter_outOfBound);
  713. }
  714. if (nbSamples == 0) {
  715. DISPLAYLEVEL(1, "Cover must have at least one input file\n");
  716. return ERROR(srcSize_wrong);
  717. }
  718. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  719. DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
  720. ZDICT_DICTSIZE_MIN);
  721. return ERROR(dstSize_tooSmall);
  722. }
  723. /* Initialize context and activeDmers */
  724. {
  725. size_t const initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
  726. parameters.d, parameters.splitPoint);
  727. if (ZSTD_isError(initVal)) {
  728. return initVal;
  729. }
  730. }
  731. COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, g_displayLevel);
  732. if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
  733. DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
  734. COVER_ctx_destroy(&ctx);
  735. return ERROR(memory_allocation);
  736. }
  737. DISPLAYLEVEL(2, "Building dictionary\n");
  738. {
  739. const size_t tail =
  740. COVER_buildDictionary(&ctx, ctx.freqs, &activeDmers, dictBuffer,
  741. dictBufferCapacity, parameters);
  742. const size_t dictionarySize = ZDICT_finalizeDictionary(
  743. dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
  744. samplesBuffer, samplesSizes, nbSamples, parameters.zParams);
  745. if (!ZSTD_isError(dictionarySize)) {
  746. DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
  747. (unsigned)dictionarySize);
  748. }
  749. COVER_ctx_destroy(&ctx);
  750. COVER_map_destroy(&activeDmers);
  751. return dictionarySize;
  752. }
  753. }
  754. size_t COVER_checkTotalCompressedSize(const ZDICT_cover_params_t parameters,
  755. const size_t *samplesSizes, const BYTE *samples,
  756. size_t *offsets,
  757. size_t nbTrainSamples, size_t nbSamples,
  758. BYTE *const dict, size_t dictBufferCapacity) {
  759. size_t totalCompressedSize = ERROR(GENERIC);
  760. /* Pointers */
  761. ZSTD_CCtx *cctx;
  762. ZSTD_CDict *cdict;
  763. void *dst;
  764. /* Local variables */
  765. size_t dstCapacity;
  766. size_t i;
  767. /* Allocate dst with enough space to compress the maximum sized sample */
  768. {
  769. size_t maxSampleSize = 0;
  770. i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
  771. for (; i < nbSamples; ++i) {
  772. maxSampleSize = MAX(samplesSizes[i], maxSampleSize);
  773. }
  774. dstCapacity = ZSTD_compressBound(maxSampleSize);
  775. dst = malloc(dstCapacity);
  776. }
  777. /* Create the cctx and cdict */
  778. cctx = ZSTD_createCCtx();
  779. cdict = ZSTD_createCDict(dict, dictBufferCapacity,
  780. parameters.zParams.compressionLevel);
  781. if (!dst || !cctx || !cdict) {
  782. goto _compressCleanup;
  783. }
  784. /* Compress each sample and sum their sizes (or error) */
  785. totalCompressedSize = dictBufferCapacity;
  786. i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
  787. for (; i < nbSamples; ++i) {
  788. const size_t size = ZSTD_compress_usingCDict(
  789. cctx, dst, dstCapacity, samples + offsets[i],
  790. samplesSizes[i], cdict);
  791. if (ZSTD_isError(size)) {
  792. totalCompressedSize = size;
  793. goto _compressCleanup;
  794. }
  795. totalCompressedSize += size;
  796. }
  797. _compressCleanup:
  798. ZSTD_freeCCtx(cctx);
  799. ZSTD_freeCDict(cdict);
  800. if (dst) {
  801. free(dst);
  802. }
  803. return totalCompressedSize;
  804. }
  805. /**
  806. * Initialize the `COVER_best_t`.
  807. */
  808. void COVER_best_init(COVER_best_t *best) {
  809. if (best==NULL) return; /* compatible with init on NULL */
  810. (void)ZSTD_pthread_mutex_init(&best->mutex, NULL);
  811. (void)ZSTD_pthread_cond_init(&best->cond, NULL);
  812. best->liveJobs = 0;
  813. best->dict = NULL;
  814. best->dictSize = 0;
  815. best->compressedSize = (size_t)-1;
  816. memset(&best->parameters, 0, sizeof(best->parameters));
  817. }
  818. /**
  819. * Wait until liveJobs == 0.
  820. */
  821. void COVER_best_wait(COVER_best_t *best) {
  822. if (!best) {
  823. return;
  824. }
  825. ZSTD_pthread_mutex_lock(&best->mutex);
  826. while (best->liveJobs != 0) {
  827. ZSTD_pthread_cond_wait(&best->cond, &best->mutex);
  828. }
  829. ZSTD_pthread_mutex_unlock(&best->mutex);
  830. }
  831. /**
  832. * Call COVER_best_wait() and then destroy the COVER_best_t.
  833. */
  834. void COVER_best_destroy(COVER_best_t *best) {
  835. if (!best) {
  836. return;
  837. }
  838. COVER_best_wait(best);
  839. if (best->dict) {
  840. free(best->dict);
  841. }
  842. ZSTD_pthread_mutex_destroy(&best->mutex);
  843. ZSTD_pthread_cond_destroy(&best->cond);
  844. }
  845. /**
  846. * Called when a thread is about to be launched.
  847. * Increments liveJobs.
  848. */
  849. void COVER_best_start(COVER_best_t *best) {
  850. if (!best) {
  851. return;
  852. }
  853. ZSTD_pthread_mutex_lock(&best->mutex);
  854. ++best->liveJobs;
  855. ZSTD_pthread_mutex_unlock(&best->mutex);
  856. }
  857. /**
  858. * Called when a thread finishes executing, both on error or success.
  859. * Decrements liveJobs and signals any waiting threads if liveJobs == 0.
  860. * If this dictionary is the best so far save it and its parameters.
  861. */
  862. void COVER_best_finish(COVER_best_t* best,
  863. ZDICT_cover_params_t parameters,
  864. COVER_dictSelection_t selection)
  865. {
  866. void* dict = selection.dictContent;
  867. size_t compressedSize = selection.totalCompressedSize;
  868. size_t dictSize = selection.dictSize;
  869. if (!best) {
  870. return;
  871. }
  872. {
  873. size_t liveJobs;
  874. ZSTD_pthread_mutex_lock(&best->mutex);
  875. --best->liveJobs;
  876. liveJobs = best->liveJobs;
  877. /* If the new dictionary is better */
  878. if (compressedSize < best->compressedSize) {
  879. /* Allocate space if necessary */
  880. if (!best->dict || best->dictSize < dictSize) {
  881. if (best->dict) {
  882. free(best->dict);
  883. }
  884. best->dict = malloc(dictSize);
  885. if (!best->dict) {
  886. best->compressedSize = ERROR(GENERIC);
  887. best->dictSize = 0;
  888. ZSTD_pthread_cond_signal(&best->cond);
  889. ZSTD_pthread_mutex_unlock(&best->mutex);
  890. return;
  891. }
  892. }
  893. /* Save the dictionary, parameters, and size */
  894. if (dict) {
  895. memcpy(best->dict, dict, dictSize);
  896. best->dictSize = dictSize;
  897. best->parameters = parameters;
  898. best->compressedSize = compressedSize;
  899. }
  900. }
  901. if (liveJobs == 0) {
  902. ZSTD_pthread_cond_broadcast(&best->cond);
  903. }
  904. ZSTD_pthread_mutex_unlock(&best->mutex);
  905. }
  906. }
  907. static COVER_dictSelection_t setDictSelection(BYTE* buf, size_t s, size_t csz)
  908. {
  909. COVER_dictSelection_t ds;
  910. ds.dictContent = buf;
  911. ds.dictSize = s;
  912. ds.totalCompressedSize = csz;
  913. return ds;
  914. }
  915. COVER_dictSelection_t COVER_dictSelectionError(size_t error) {
  916. return setDictSelection(NULL, 0, error);
  917. }
  918. unsigned COVER_dictSelectionIsError(COVER_dictSelection_t selection) {
  919. return (ZSTD_isError(selection.totalCompressedSize) || !selection.dictContent);
  920. }
  921. void COVER_dictSelectionFree(COVER_dictSelection_t selection){
  922. free(selection.dictContent);
  923. }
  924. COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent, size_t dictBufferCapacity,
  925. size_t dictContentSize, const BYTE* samplesBuffer, const size_t* samplesSizes, unsigned nbFinalizeSamples,
  926. size_t nbCheckSamples, size_t nbSamples, ZDICT_cover_params_t params, size_t* offsets, size_t totalCompressedSize) {
  927. size_t largestDict = 0;
  928. size_t largestCompressed = 0;
  929. BYTE* customDictContentEnd = customDictContent + dictContentSize;
  930. BYTE* largestDictbuffer = (BYTE*)malloc(dictBufferCapacity);
  931. BYTE* candidateDictBuffer = (BYTE*)malloc(dictBufferCapacity);
  932. double regressionTolerance = ((double)params.shrinkDictMaxRegression / 100.0) + 1.00;
  933. if (!largestDictbuffer || !candidateDictBuffer) {
  934. free(largestDictbuffer);
  935. free(candidateDictBuffer);
  936. return COVER_dictSelectionError(dictContentSize);
  937. }
  938. /* Initial dictionary size and compressed size */
  939. memcpy(largestDictbuffer, customDictContent, dictContentSize);
  940. dictContentSize = ZDICT_finalizeDictionary(
  941. largestDictbuffer, dictBufferCapacity, customDictContent, dictContentSize,
  942. samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
  943. if (ZDICT_isError(dictContentSize)) {
  944. free(largestDictbuffer);
  945. free(candidateDictBuffer);
  946. return COVER_dictSelectionError(dictContentSize);
  947. }
  948. totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
  949. samplesBuffer, offsets,
  950. nbCheckSamples, nbSamples,
  951. largestDictbuffer, dictContentSize);
  952. if (ZSTD_isError(totalCompressedSize)) {
  953. free(largestDictbuffer);
  954. free(candidateDictBuffer);
  955. return COVER_dictSelectionError(totalCompressedSize);
  956. }
  957. if (params.shrinkDict == 0) {
  958. free(candidateDictBuffer);
  959. return setDictSelection(largestDictbuffer, dictContentSize, totalCompressedSize);
  960. }
  961. largestDict = dictContentSize;
  962. largestCompressed = totalCompressedSize;
  963. dictContentSize = ZDICT_DICTSIZE_MIN;
  964. /* Largest dict is initially at least ZDICT_DICTSIZE_MIN */
  965. while (dictContentSize < largestDict) {
  966. memcpy(candidateDictBuffer, largestDictbuffer, largestDict);
  967. dictContentSize = ZDICT_finalizeDictionary(
  968. candidateDictBuffer, dictBufferCapacity, customDictContentEnd - dictContentSize, dictContentSize,
  969. samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
  970. if (ZDICT_isError(dictContentSize)) {
  971. free(largestDictbuffer);
  972. free(candidateDictBuffer);
  973. return COVER_dictSelectionError(dictContentSize);
  974. }
  975. totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
  976. samplesBuffer, offsets,
  977. nbCheckSamples, nbSamples,
  978. candidateDictBuffer, dictContentSize);
  979. if (ZSTD_isError(totalCompressedSize)) {
  980. free(largestDictbuffer);
  981. free(candidateDictBuffer);
  982. return COVER_dictSelectionError(totalCompressedSize);
  983. }
  984. if ((double)totalCompressedSize <= (double)largestCompressed * regressionTolerance) {
  985. free(largestDictbuffer);
  986. return setDictSelection( candidateDictBuffer, dictContentSize, totalCompressedSize );
  987. }
  988. dictContentSize *= 2;
  989. }
  990. dictContentSize = largestDict;
  991. totalCompressedSize = largestCompressed;
  992. free(candidateDictBuffer);
  993. return setDictSelection( largestDictbuffer, dictContentSize, totalCompressedSize );
  994. }
  995. /**
  996. * Parameters for COVER_tryParameters().
  997. */
  998. typedef struct COVER_tryParameters_data_s {
  999. const COVER_ctx_t *ctx;
  1000. COVER_best_t *best;
  1001. size_t dictBufferCapacity;
  1002. ZDICT_cover_params_t parameters;
  1003. } COVER_tryParameters_data_t;
  1004. /**
  1005. * Tries a set of parameters and updates the COVER_best_t with the results.
  1006. * This function is thread safe if zstd is compiled with multithreaded support.
  1007. * It takes its parameters as an *OWNING* opaque pointer to support threading.
  1008. */
  1009. static void COVER_tryParameters(void *opaque)
  1010. {
  1011. /* Save parameters as local variables */
  1012. COVER_tryParameters_data_t *const data = (COVER_tryParameters_data_t*)opaque;
  1013. const COVER_ctx_t *const ctx = data->ctx;
  1014. const ZDICT_cover_params_t parameters = data->parameters;
  1015. size_t dictBufferCapacity = data->dictBufferCapacity;
  1016. size_t totalCompressedSize = ERROR(GENERIC);
  1017. /* Allocate space for hash table, dict, and freqs */
  1018. COVER_map_t activeDmers;
  1019. BYTE* const dict = (BYTE*)malloc(dictBufferCapacity);
  1020. COVER_dictSelection_t selection = COVER_dictSelectionError(ERROR(GENERIC));
  1021. U32* const freqs = (U32*)malloc(ctx->suffixSize * sizeof(U32));
  1022. if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
  1023. DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
  1024. goto _cleanup;
  1025. }
  1026. if (!dict || !freqs) {
  1027. DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
  1028. goto _cleanup;
  1029. }
  1030. /* Copy the frequencies because we need to modify them */
  1031. memcpy(freqs, ctx->freqs, ctx->suffixSize * sizeof(U32));
  1032. /* Build the dictionary */
  1033. {
  1034. const size_t tail = COVER_buildDictionary(ctx, freqs, &activeDmers, dict,
  1035. dictBufferCapacity, parameters);
  1036. selection = COVER_selectDict(dict + tail, dictBufferCapacity, dictBufferCapacity - tail,
  1037. ctx->samples, ctx->samplesSizes, (unsigned)ctx->nbTrainSamples, ctx->nbTrainSamples, ctx->nbSamples, parameters, ctx->offsets,
  1038. totalCompressedSize);
  1039. if (COVER_dictSelectionIsError(selection)) {
  1040. DISPLAYLEVEL(1, "Failed to select dictionary\n");
  1041. goto _cleanup;
  1042. }
  1043. }
  1044. _cleanup:
  1045. free(dict);
  1046. COVER_best_finish(data->best, parameters, selection);
  1047. free(data);
  1048. COVER_map_destroy(&activeDmers);
  1049. COVER_dictSelectionFree(selection);
  1050. free(freqs);
  1051. }
  1052. ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover(
  1053. void* dictBuffer, size_t dictBufferCapacity, const void* samplesBuffer,
  1054. const size_t* samplesSizes, unsigned nbSamples,
  1055. ZDICT_cover_params_t* parameters)
  1056. {
  1057. /* constants */
  1058. const unsigned nbThreads = parameters->nbThreads;
  1059. const double splitPoint =
  1060. parameters->splitPoint <= 0.0 ? COVER_DEFAULT_SPLITPOINT : parameters->splitPoint;
  1061. const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
  1062. const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
  1063. const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
  1064. const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
  1065. const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
  1066. const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
  1067. const unsigned kIterations =
  1068. (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
  1069. const unsigned shrinkDict = 0;
  1070. /* Local variables */
  1071. const int displayLevel = parameters->zParams.notificationLevel;
  1072. unsigned iteration = 1;
  1073. unsigned d;
  1074. unsigned k;
  1075. COVER_best_t best;
  1076. POOL_ctx *pool = NULL;
  1077. int warned = 0;
  1078. /* Checks */
  1079. if (splitPoint <= 0 || splitPoint > 1) {
  1080. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
  1081. return ERROR(parameter_outOfBound);
  1082. }
  1083. if (kMinK < kMaxD || kMaxK < kMinK) {
  1084. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
  1085. return ERROR(parameter_outOfBound);
  1086. }
  1087. if (nbSamples == 0) {
  1088. DISPLAYLEVEL(1, "Cover must have at least one input file\n");
  1089. return ERROR(srcSize_wrong);
  1090. }
  1091. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  1092. DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
  1093. ZDICT_DICTSIZE_MIN);
  1094. return ERROR(dstSize_tooSmall);
  1095. }
  1096. if (nbThreads > 1) {
  1097. pool = POOL_create(nbThreads, 1);
  1098. if (!pool) {
  1099. return ERROR(memory_allocation);
  1100. }
  1101. }
  1102. /* Initialization */
  1103. COVER_best_init(&best);
  1104. /* Turn down global display level to clean up display at level 2 and below */
  1105. g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1;
  1106. /* Loop through d first because each new value needs a new context */
  1107. LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n",
  1108. kIterations);
  1109. for (d = kMinD; d <= kMaxD; d += 2) {
  1110. /* Initialize the context for this value of d */
  1111. COVER_ctx_t ctx;
  1112. LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d);
  1113. {
  1114. const size_t initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint);
  1115. if (ZSTD_isError(initVal)) {
  1116. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n");
  1117. COVER_best_destroy(&best);
  1118. POOL_free(pool);
  1119. return initVal;
  1120. }
  1121. }
  1122. if (!warned) {
  1123. COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, displayLevel);
  1124. warned = 1;
  1125. }
  1126. /* Loop through k reusing the same context */
  1127. for (k = kMinK; k <= kMaxK; k += kStepSize) {
  1128. /* Prepare the arguments */
  1129. COVER_tryParameters_data_t *data = (COVER_tryParameters_data_t *)malloc(
  1130. sizeof(COVER_tryParameters_data_t));
  1131. LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k);
  1132. if (!data) {
  1133. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n");
  1134. COVER_best_destroy(&best);
  1135. COVER_ctx_destroy(&ctx);
  1136. POOL_free(pool);
  1137. return ERROR(memory_allocation);
  1138. }
  1139. data->ctx = &ctx;
  1140. data->best = &best;
  1141. data->dictBufferCapacity = dictBufferCapacity;
  1142. data->parameters = *parameters;
  1143. data->parameters.k = k;
  1144. data->parameters.d = d;
  1145. data->parameters.splitPoint = splitPoint;
  1146. data->parameters.steps = kSteps;
  1147. data->parameters.shrinkDict = shrinkDict;
  1148. data->parameters.zParams.notificationLevel = g_displayLevel;
  1149. /* Check the parameters */
  1150. if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) {
  1151. DISPLAYLEVEL(1, "Cover parameters incorrect\n");
  1152. free(data);
  1153. continue;
  1154. }
  1155. /* Call the function and pass ownership of data to it */
  1156. COVER_best_start(&best);
  1157. if (pool) {
  1158. POOL_add(pool, &COVER_tryParameters, data);
  1159. } else {
  1160. COVER_tryParameters(data);
  1161. }
  1162. /* Print status */
  1163. LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ",
  1164. (unsigned)((iteration * 100) / kIterations));
  1165. ++iteration;
  1166. }
  1167. COVER_best_wait(&best);
  1168. COVER_ctx_destroy(&ctx);
  1169. }
  1170. LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", "");
  1171. /* Fill the output buffer and parameters with output of the best parameters */
  1172. {
  1173. const size_t dictSize = best.dictSize;
  1174. if (ZSTD_isError(best.compressedSize)) {
  1175. const size_t compressedSize = best.compressedSize;
  1176. COVER_best_destroy(&best);
  1177. POOL_free(pool);
  1178. return compressedSize;
  1179. }
  1180. *parameters = best.parameters;
  1181. memcpy(dictBuffer, best.dict, dictSize);
  1182. COVER_best_destroy(&best);
  1183. POOL_free(pool);
  1184. return dictSize;
  1185. }
  1186. }