You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cover.c 33KB

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