Coverage Report

Created: 2024-09-08 06:25

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