cover.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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 occurence 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 (%u MB), maximum size is %u MB\n",
  507. (U32)(totalSamplesSize>>20), (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,
  618. const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
  619. ZDICT_cover_params_t parameters)
  620. {
  621. BYTE* const dict = (BYTE*)dictBuffer;
  622. COVER_ctx_t ctx;
  623. COVER_map_t activeDmers;
  624. /* Initialize global data */
  625. g_displayLevel = parameters.zParams.notificationLevel;
  626. /* Checks */
  627. if (!COVER_checkParameters(parameters, dictBufferCapacity)) {
  628. DISPLAYLEVEL(1, "Cover parameters incorrect\n");
  629. return ERROR(GENERIC);
  630. }
  631. if (nbSamples == 0) {
  632. DISPLAYLEVEL(1, "Cover must have at least one input file\n");
  633. return ERROR(GENERIC);
  634. }
  635. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  636. DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
  637. ZDICT_DICTSIZE_MIN);
  638. return ERROR(dstSize_tooSmall);
  639. }
  640. /* Initialize context and activeDmers */
  641. if (!COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
  642. parameters.d)) {
  643. return ERROR(GENERIC);
  644. }
  645. if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
  646. DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
  647. COVER_ctx_destroy(&ctx);
  648. return ERROR(GENERIC);
  649. }
  650. DISPLAYLEVEL(2, "Building dictionary\n");
  651. {
  652. const size_t tail =
  653. COVER_buildDictionary(&ctx, ctx.freqs, &activeDmers, dictBuffer,
  654. dictBufferCapacity, parameters);
  655. const size_t dictionarySize = ZDICT_finalizeDictionary(
  656. dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
  657. samplesBuffer, samplesSizes, nbSamples, parameters.zParams);
  658. if (!ZSTD_isError(dictionarySize)) {
  659. DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
  660. (U32)dictionarySize);
  661. }
  662. COVER_ctx_destroy(&ctx);
  663. COVER_map_destroy(&activeDmers);
  664. return dictionarySize;
  665. }
  666. }
  667. /**
  668. * COVER_best_t is used for two purposes:
  669. * 1. Synchronizing threads.
  670. * 2. Saving the best parameters and dictionary.
  671. *
  672. * All of the methods except COVER_best_init() are thread safe if zstd is
  673. * compiled with multithreaded support.
  674. */
  675. typedef struct COVER_best_s {
  676. ZSTD_pthread_mutex_t mutex;
  677. ZSTD_pthread_cond_t cond;
  678. size_t liveJobs;
  679. void *dict;
  680. size_t dictSize;
  681. ZDICT_cover_params_t parameters;
  682. size_t compressedSize;
  683. } COVER_best_t;
  684. /**
  685. * Initialize the `COVER_best_t`.
  686. */
  687. static void COVER_best_init(COVER_best_t *best) {
  688. if (best==NULL) return; /* compatible with init on NULL */
  689. (void)ZSTD_pthread_mutex_init(&best->mutex, NULL);
  690. (void)ZSTD_pthread_cond_init(&best->cond, NULL);
  691. best->liveJobs = 0;
  692. best->dict = NULL;
  693. best->dictSize = 0;
  694. best->compressedSize = (size_t)-1;
  695. memset(&best->parameters, 0, sizeof(best->parameters));
  696. }
  697. /**
  698. * Wait until liveJobs == 0.
  699. */
  700. static void COVER_best_wait(COVER_best_t *best) {
  701. if (!best) {
  702. return;
  703. }
  704. ZSTD_pthread_mutex_lock(&best->mutex);
  705. while (best->liveJobs != 0) {
  706. ZSTD_pthread_cond_wait(&best->cond, &best->mutex);
  707. }
  708. ZSTD_pthread_mutex_unlock(&best->mutex);
  709. }
  710. /**
  711. * Call COVER_best_wait() and then destroy the COVER_best_t.
  712. */
  713. static void COVER_best_destroy(COVER_best_t *best) {
  714. if (!best) {
  715. return;
  716. }
  717. COVER_best_wait(best);
  718. if (best->dict) {
  719. free(best->dict);
  720. }
  721. ZSTD_pthread_mutex_destroy(&best->mutex);
  722. ZSTD_pthread_cond_destroy(&best->cond);
  723. }
  724. /**
  725. * Called when a thread is about to be launched.
  726. * Increments liveJobs.
  727. */
  728. static void COVER_best_start(COVER_best_t *best) {
  729. if (!best) {
  730. return;
  731. }
  732. ZSTD_pthread_mutex_lock(&best->mutex);
  733. ++best->liveJobs;
  734. ZSTD_pthread_mutex_unlock(&best->mutex);
  735. }
  736. /**
  737. * Called when a thread finishes executing, both on error or success.
  738. * Decrements liveJobs and signals any waiting threads if liveJobs == 0.
  739. * If this dictionary is the best so far save it and its parameters.
  740. */
  741. static void COVER_best_finish(COVER_best_t *best, size_t compressedSize,
  742. ZDICT_cover_params_t parameters, void *dict,
  743. size_t dictSize) {
  744. if (!best) {
  745. return;
  746. }
  747. {
  748. size_t liveJobs;
  749. ZSTD_pthread_mutex_lock(&best->mutex);
  750. --best->liveJobs;
  751. liveJobs = best->liveJobs;
  752. /* If the new dictionary is better */
  753. if (compressedSize < best->compressedSize) {
  754. /* Allocate space if necessary */
  755. if (!best->dict || best->dictSize < dictSize) {
  756. if (best->dict) {
  757. free(best->dict);
  758. }
  759. best->dict = malloc(dictSize);
  760. if (!best->dict) {
  761. best->compressedSize = ERROR(GENERIC);
  762. best->dictSize = 0;
  763. return;
  764. }
  765. }
  766. /* Save the dictionary, parameters, and size */
  767. memcpy(best->dict, dict, dictSize);
  768. best->dictSize = dictSize;
  769. best->parameters = parameters;
  770. best->compressedSize = compressedSize;
  771. }
  772. ZSTD_pthread_mutex_unlock(&best->mutex);
  773. if (liveJobs == 0) {
  774. ZSTD_pthread_cond_broadcast(&best->cond);
  775. }
  776. }
  777. }
  778. /**
  779. * Parameters for COVER_tryParameters().
  780. */
  781. typedef struct COVER_tryParameters_data_s {
  782. const COVER_ctx_t *ctx;
  783. COVER_best_t *best;
  784. size_t dictBufferCapacity;
  785. ZDICT_cover_params_t parameters;
  786. } COVER_tryParameters_data_t;
  787. /**
  788. * Tries a set of parameters and upates the COVER_best_t with the results.
  789. * This function is thread safe if zstd is compiled with multithreaded support.
  790. * It takes its parameters as an *OWNING* opaque pointer to support threading.
  791. */
  792. static void COVER_tryParameters(void *opaque) {
  793. /* Save parameters as local variables */
  794. COVER_tryParameters_data_t *const data = (COVER_tryParameters_data_t *)opaque;
  795. const COVER_ctx_t *const ctx = data->ctx;
  796. const ZDICT_cover_params_t parameters = data->parameters;
  797. size_t dictBufferCapacity = data->dictBufferCapacity;
  798. size_t totalCompressedSize = ERROR(GENERIC);
  799. /* Allocate space for hash table, dict, and freqs */
  800. COVER_map_t activeDmers;
  801. BYTE *const dict = (BYTE * const)malloc(dictBufferCapacity);
  802. U32 *freqs = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
  803. if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
  804. DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
  805. goto _cleanup;
  806. }
  807. if (!dict || !freqs) {
  808. DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
  809. goto _cleanup;
  810. }
  811. /* Copy the frequencies because we need to modify them */
  812. memcpy(freqs, ctx->freqs, ctx->suffixSize * sizeof(U32));
  813. /* Build the dictionary */
  814. {
  815. const size_t tail = COVER_buildDictionary(ctx, freqs, &activeDmers, dict,
  816. dictBufferCapacity, parameters);
  817. dictBufferCapacity = ZDICT_finalizeDictionary(
  818. dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
  819. ctx->samples, ctx->samplesSizes, (unsigned)ctx->nbSamples,
  820. parameters.zParams);
  821. if (ZDICT_isError(dictBufferCapacity)) {
  822. DISPLAYLEVEL(1, "Failed to finalize dictionary\n");
  823. goto _cleanup;
  824. }
  825. }
  826. /* Check total compressed size */
  827. {
  828. /* Pointers */
  829. ZSTD_CCtx *cctx;
  830. ZSTD_CDict *cdict;
  831. void *dst;
  832. /* Local variables */
  833. size_t dstCapacity;
  834. size_t i;
  835. /* Allocate dst with enough space to compress the maximum sized sample */
  836. {
  837. size_t maxSampleSize = 0;
  838. for (i = 0; i < ctx->nbSamples; ++i) {
  839. maxSampleSize = MAX(ctx->samplesSizes[i], maxSampleSize);
  840. }
  841. dstCapacity = ZSTD_compressBound(maxSampleSize);
  842. dst = malloc(dstCapacity);
  843. }
  844. /* Create the cctx and cdict */
  845. cctx = ZSTD_createCCtx();
  846. cdict = ZSTD_createCDict(dict, dictBufferCapacity,
  847. parameters.zParams.compressionLevel);
  848. if (!dst || !cctx || !cdict) {
  849. goto _compressCleanup;
  850. }
  851. /* Compress each sample and sum their sizes (or error) */
  852. totalCompressedSize = dictBufferCapacity;
  853. for (i = 0; i < ctx->nbSamples; ++i) {
  854. const size_t size = ZSTD_compress_usingCDict(
  855. cctx, dst, dstCapacity, ctx->samples + ctx->offsets[i],
  856. ctx->samplesSizes[i], cdict);
  857. if (ZSTD_isError(size)) {
  858. totalCompressedSize = ERROR(GENERIC);
  859. goto _compressCleanup;
  860. }
  861. totalCompressedSize += size;
  862. }
  863. _compressCleanup:
  864. ZSTD_freeCCtx(cctx);
  865. ZSTD_freeCDict(cdict);
  866. if (dst) {
  867. free(dst);
  868. }
  869. }
  870. _cleanup:
  871. COVER_best_finish(data->best, totalCompressedSize, parameters, dict,
  872. dictBufferCapacity);
  873. free(data);
  874. COVER_map_destroy(&activeDmers);
  875. if (dict) {
  876. free(dict);
  877. }
  878. if (freqs) {
  879. free(freqs);
  880. }
  881. }
  882. ZDICTLIB_API size_t ZDICT_optimizeTrainFromBuffer_cover(
  883. void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer,
  884. const size_t *samplesSizes, unsigned nbSamples,
  885. ZDICT_cover_params_t *parameters) {
  886. /* constants */
  887. const unsigned nbThreads = parameters->nbThreads;
  888. const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
  889. const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
  890. const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
  891. const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
  892. const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
  893. const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
  894. const unsigned kIterations =
  895. (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
  896. /* Local variables */
  897. const int displayLevel = parameters->zParams.notificationLevel;
  898. unsigned iteration = 1;
  899. unsigned d;
  900. unsigned k;
  901. COVER_best_t best;
  902. POOL_ctx *pool = NULL;
  903. /* Checks */
  904. if (kMinK < kMaxD || kMaxK < kMinK) {
  905. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
  906. return ERROR(GENERIC);
  907. }
  908. if (nbSamples == 0) {
  909. DISPLAYLEVEL(1, "Cover must have at least one input file\n");
  910. return ERROR(GENERIC);
  911. }
  912. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  913. DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
  914. ZDICT_DICTSIZE_MIN);
  915. return ERROR(dstSize_tooSmall);
  916. }
  917. if (nbThreads > 1) {
  918. pool = POOL_create(nbThreads, 1);
  919. if (!pool) {
  920. return ERROR(memory_allocation);
  921. }
  922. }
  923. /* Initialization */
  924. COVER_best_init(&best);
  925. /* Turn down global display level to clean up display at level 2 and below */
  926. g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1;
  927. /* Loop through d first because each new value needs a new context */
  928. LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n",
  929. kIterations);
  930. for (d = kMinD; d <= kMaxD; d += 2) {
  931. /* Initialize the context for this value of d */
  932. COVER_ctx_t ctx;
  933. LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d);
  934. if (!COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d)) {
  935. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n");
  936. COVER_best_destroy(&best);
  937. POOL_free(pool);
  938. return ERROR(GENERIC);
  939. }
  940. /* Loop through k reusing the same context */
  941. for (k = kMinK; k <= kMaxK; k += kStepSize) {
  942. /* Prepare the arguments */
  943. COVER_tryParameters_data_t *data = (COVER_tryParameters_data_t *)malloc(
  944. sizeof(COVER_tryParameters_data_t));
  945. LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k);
  946. if (!data) {
  947. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n");
  948. COVER_best_destroy(&best);
  949. COVER_ctx_destroy(&ctx);
  950. POOL_free(pool);
  951. return ERROR(GENERIC);
  952. }
  953. data->ctx = &ctx;
  954. data->best = &best;
  955. data->dictBufferCapacity = dictBufferCapacity;
  956. data->parameters = *parameters;
  957. data->parameters.k = k;
  958. data->parameters.d = d;
  959. data->parameters.steps = kSteps;
  960. data->parameters.zParams.notificationLevel = g_displayLevel;
  961. /* Check the parameters */
  962. if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) {
  963. DISPLAYLEVEL(1, "Cover parameters incorrect\n");
  964. free(data);
  965. continue;
  966. }
  967. /* Call the function and pass ownership of data to it */
  968. COVER_best_start(&best);
  969. if (pool) {
  970. POOL_add(pool, &COVER_tryParameters, data);
  971. } else {
  972. COVER_tryParameters(data);
  973. }
  974. /* Print status */
  975. LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ",
  976. (U32)((iteration * 100) / kIterations));
  977. ++iteration;
  978. }
  979. COVER_best_wait(&best);
  980. COVER_ctx_destroy(&ctx);
  981. }
  982. LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", "");
  983. /* Fill the output buffer and parameters with output of the best parameters */
  984. {
  985. const size_t dictSize = best.dictSize;
  986. if (ZSTD_isError(best.compressedSize)) {
  987. const size_t compressedSize = best.compressedSize;
  988. COVER_best_destroy(&best);
  989. POOL_free(pool);
  990. return compressedSize;
  991. }
  992. *parameters = best.parameters;
  993. memcpy(dictBuffer, best.dict, dictSize);
  994. COVER_best_destroy(&best);
  995. POOL_free(pool);
  996. return dictSize;
  997. }
  998. }