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