cover.c 35 KB

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