Skip to content

Commit 4dd90fa

Browse files
authored
[ML] Store calendar periodicity historical error statistics in compressed format (#127)
Also, extend the window of historical error statistics, which means we can improve the test accuracy (this was previously being limited to keep memory usage down) and simplify the implementation, which was previously bit packing the count statistics to reduce memory usage.
1 parent 601f344 commit 4dd90fa

18 files changed

+1129
-771
lines changed

docs/CHANGELOG.asciidoc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ new processes being created and macOS uses the sandbox functionality ({pull}98[#
4848
Fix a bug causing us to under estimate the memory used by shared pointers and reduce the memory consumed
4949
by unnecessary reference counting ({pull}108[#108])
5050

51+
Reduce model memory by storing state for testing for predictive calendar features in a compressed format
52+
({pull}127[#127])
53+
5154
=== Bug Fixes
5255

5356
Age seasonal components in proportion to the fraction of values with which they're updated ({pull}88[#88])

include/maths/CCalendarCyclicTest.h

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
#ifndef INCLUDED_ml_maths_CCalendarCyclicTest_h
8+
#define INCLUDED_ml_maths_CCalendarCyclicTest_h
9+
10+
#include <core/CMemoryUsage.h>
11+
#include <core/CoreTypes.h>
12+
13+
#include <maths/CCalendarFeature.h>
14+
#include <maths/CQuantileSketch.h>
15+
#include <maths/ImportExport.h>
16+
#include <maths/MathsTypes.h>
17+
18+
#include <boost/optional.hpp>
19+
20+
#include <cstdint>
21+
#include <vector>
22+
23+
namespace ml {
24+
namespace core {
25+
class CStatePersistInserter;
26+
class CStateRestoreTraverser;
27+
}
28+
namespace maths {
29+
30+
//! \brief The basic idea of this test is to see if there is stronger
31+
//! than expected temporal correlation between large prediction errors
32+
//! and calendar features.
33+
//!
34+
//! DESCRIPTION:\n
35+
//! This maintains prediction error statistics for a collection of
36+
//! calendar features. These are things like "day of month",
37+
//! ("day of week", "week month") pairs and so on. The test checks to
38+
//! see if the number of large prediction errors is statistically high,
39+
//! i.e. are there many more errors exceeding a specified percentile
40+
//! than one would expect given that this is expected to be binomial.
41+
//! Amongst features with statistically significant frequencies of large
42+
//! errors it returns the feature with the highest mean prediction error.
43+
class MATHS_EXPORT CCalendarCyclicTest {
44+
public:
45+
using TOptionalFeature = boost::optional<CCalendarFeature>;
46+
47+
public:
48+
explicit CCalendarCyclicTest(double decayRate = 0.0);
49+
50+
//! Initialize by reading state from \p traverser.
51+
bool acceptRestoreTraverser(core::CStateRestoreTraverser& traverser);
52+
53+
//! Persist state by passing information to \p inserter.
54+
void acceptPersistInserter(core::CStatePersistInserter& inserter) const;
55+
56+
//! Age the bucket values to account for \p time elapsed time.
57+
void propagateForwardsByTime(double time);
58+
59+
//! Add \p error at \p time.
60+
void add(core_t::TTime time, double error, double weight = 1.0);
61+
62+
//! Check if there are calendar components.
63+
TOptionalFeature test() const;
64+
65+
//! Get a checksum for this object.
66+
std::uint64_t checksum(std::uint64_t seed = 0) const;
67+
68+
//! Debug the memory used by this object.
69+
void debugMemoryUsage(core::CMemoryUsage::TMemoryUsagePtr mem) const;
70+
71+
//! Get the memory used by this object.
72+
std::size_t memoryUsage() const;
73+
74+
private:
75+
using TTimeVec = std::vector<core_t::TTime>;
76+
using TByte = unsigned char;
77+
using TByteVec = std::vector<TByte>;
78+
79+
//! \brief Records the daily error statistics.
80+
struct MATHS_EXPORT SErrorStats {
81+
//! Get a checksum for this object.
82+
std::uint64_t checksum() const;
83+
//! Convert to a delimited string.
84+
std::string toDelimited() const;
85+
//! Initialize from a delimited string.
86+
bool fromDelimited(const std::string& str);
87+
88+
std::uint32_t s_Count = 0;
89+
std::uint32_t s_LargeErrorCount = 0;
90+
CFloatStorage s_LargeErrorSum = 0.0;
91+
};
92+
using TErrorStatsVec = std::vector<SErrorStats>;
93+
94+
private:
95+
//! Winsorise \p error.
96+
double winsorise(double error) const;
97+
98+
//! Get the significance of \p x large errors given \p n samples.
99+
double significance(double n, double x) const;
100+
101+
//! Convert to a compressed representation.
102+
void deflate(const TErrorStatsVec& stats);
103+
104+
//! Extract from the compressed representation.
105+
TErrorStatsVec inflate() const;
106+
107+
private:
108+
//! The rate at which the error counts are aged.
109+
double m_DecayRate;
110+
111+
//! Used to estimate large error thresholds.
112+
CQuantileSketch m_ErrorQuantiles;
113+
114+
//! The start time of the bucket to which the last error
115+
//! was added.
116+
core_t::TTime m_CurrentBucketTime;
117+
118+
//! The start time of the earliest bucket for which we have
119+
//! error statistics.
120+
core_t::TTime m_CurrentBucketIndex;
121+
122+
//! The bucket statistics currently being updated.
123+
SErrorStats m_CurrentBucketErrorStats;
124+
125+
//! The compressed error statistics.
126+
//!
127+
//! \note We always persist the errors in uncompressed format.
128+
TByteVec m_CompressedBucketErrorStats;
129+
};
130+
}
131+
}
132+
133+
#endif // INCLUDED_ml_maths_CCalendarCyclicTest_h

include/maths/CTrendTests.h renamed to include/maths/CRandomizedPeriodicityTest.h

Lines changed: 11 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -4,35 +4,31 @@
44
* you may not use this file except in compliance with the Elastic License.
55
*/
66

7-
#ifndef INCLUDED_ml_maths_CTrendTests_h
8-
#define INCLUDED_ml_maths_CTrendTests_h
7+
#ifndef INCLUDED_ml_maths_CRandomizedPeriodicityTest_h
8+
#define INCLUDED_ml_maths_CRandomizedPeriodicityTest_h
99

1010
#include <core/CMutex.h>
11-
#include <core/CVectorRange.h>
1211
#include <core/CoreTypes.h>
1312

1413
#include <maths/CBasicStatistics.h>
15-
#include <maths/CCalendarFeature.h>
1614
#include <maths/CLinearAlgebra.h>
1715
#include <maths/CPRNG.h>
18-
#include <maths/CQuantileSketch.h>
19-
#include <maths/CRegression.h>
2016
#include <maths/ImportExport.h>
21-
#include <maths/MathsTypes.h>
2217

23-
#include <boost/circular_buffer.hpp>
24-
#include <boost/container/flat_map.hpp>
2518
#include <boost/random/mersenne_twister.hpp>
2619

2720
#include <atomic>
2821
#include <cstddef>
22+
#include <cstdint>
2923
#include <vector>
3024

31-
#include <stdint.h>
32-
33-
class CTrendTestsTest;
25+
class CRandomizedPeriodicityTestTest;
3426

3527
namespace ml {
28+
namespace core {
29+
class CStatePersistInserter;
30+
class CStateRestoreTraverser;
31+
}
3632
namespace maths {
3733
class CSeasonalTime;
3834

@@ -93,7 +89,7 @@ class MATHS_EXPORT CRandomizedPeriodicityTest {
9389
static void reset();
9490

9591
//! Get a checksum for this object.
96-
uint64_t checksum(uint64_t seed = 0) const;
92+
std::uint64_t checksum(std::uint64_t seed = 0) const;
9793

9894
private:
9995
using TDoubleVec = std::vector<double>;
@@ -155,97 +151,9 @@ class MATHS_EXPORT CRandomizedPeriodicityTest {
155151
//! The last time the day projections were updated.
156152
core_t::TTime m_WeekRefreshedProjections;
157153

158-
friend class ::CTrendTestsTest;
159-
};
160-
161-
//! \brief The basic idea of this test is to see if there is stronger
162-
//! than expected temporal correlation between large prediction errors
163-
//! and calendar features.
164-
//!
165-
//! DESCRIPTION:\n
166-
//! This maintains prediction error statistics for a collection of
167-
//! calendar features. These are things like "day of month",
168-
//! ("day of week", "week month") pairs and so on. The test checks to
169-
//! see if the number of large prediction errors is statistically high,
170-
//! i.e. are there many more errors exceeding a specified percentile
171-
//! than one would expect given that this is expected to be binomial.
172-
//! Amongst features with statistically significant frequencies of large
173-
//! errors it returns the feature with the highest mean prediction error.
174-
class MATHS_EXPORT CCalendarCyclicTest {
175-
public:
176-
using TOptionalFeature = boost::optional<CCalendarFeature>;
177-
178-
public:
179-
explicit CCalendarCyclicTest(double decayRate = 0.0);
180-
181-
//! Initialize by reading state from \p traverser.
182-
bool acceptRestoreTraverser(core::CStateRestoreTraverser& traverser);
183-
184-
//! Persist state by passing information to \p inserter.
185-
void acceptPersistInserter(core::CStatePersistInserter& inserter) const;
186-
187-
//! Age the bucket values to account for \p time elapsed time.
188-
void propagateForwardsByTime(double time);
189-
190-
//! Add \p error at \p time.
191-
void add(core_t::TTime time, double error, double weight = 1.0);
192-
193-
//! Check if there are calendar components.
194-
TOptionalFeature test() const;
195-
196-
//! Get a checksum for this object.
197-
uint64_t checksum(uint64_t seed = 0) const;
198-
199-
//! Debug the memory used by this object.
200-
void debugMemoryUsage(core::CMemoryUsage::TMemoryUsagePtr mem) const;
201-
202-
//! Get the memory used by this object.
203-
std::size_t memoryUsage() const;
204-
205-
private:
206-
using TTimeVec = std::vector<core_t::TTime>;
207-
using TUInt32CBuf = boost::circular_buffer<uint32_t>;
208-
using TTimeFloatPr = std::pair<core_t::TTime, CFloatStorage>;
209-
using TTimeFloatFMap = boost::container::flat_map<core_t::TTime, CFloatStorage>;
210-
211-
private:
212-
//! Winsorise \p error.
213-
double winsorise(double error) const;
214-
215-
//! Get the significance of \p x large errors given \p n samples.
216-
double significance(double n, double x) const;
217-
218-
private:
219-
//! The error bucketing interval.
220-
static const core_t::TTime BUCKET;
221-
//! The window length in buckets.
222-
static const core_t::TTime WINDOW;
223-
//! The percentile of a large error.
224-
static const double LARGE_ERROR_PERCENTILE;
225-
//! The minimum number of repeats for a testable feature.
226-
static const unsigned int MINIMUM_REPEATS;
227-
//! The bits used to count added values.
228-
static const uint32_t COUNT_BITS;
229-
//! The offsets that are used for different timezone offsets.
230-
static const TTimeVec TIMEZONE_OFFSETS;
231-
232-
private:
233-
//! The rate at which the error counts are aged.
234-
double m_DecayRate;
235-
236-
//! The time of the last error added.
237-
core_t::TTime m_Bucket;
238-
239-
//! Used to estimate large error thresholds.
240-
CQuantileSketch m_ErrorQuantiles;
241-
242-
//! The counts of errors and large errors in a sliding window.
243-
TUInt32CBuf m_ErrorCounts;
244-
245-
//! The bucket large error sums.
246-
TTimeFloatFMap m_ErrorSums;
154+
friend class ::CRandomizedPeriodicityTestTest;
247155
};
248156
}
249157
}
250158

251-
#endif // INCLUDED_ml_maths_CTrendTests_h
159+
#endif // INCLUDED_ml_maths_CRandomizedPeriodicityTest_h

include/maths/CTimeSeriesDecompositionDetail.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@
1212
#include <core/CoreTypes.h>
1313

1414
#include <maths/CCalendarComponent.h>
15+
#include <maths/CCalendarCyclicTest.h>
1516
#include <maths/CExpandingWindow.h>
1617
#include <maths/CPeriodicityHypothesisTests.h>
1718
#include <maths/CSeasonalComponent.h>
1819
#include <maths/CSeasonalTime.h>
1920
#include <maths/CTimeSeriesDecompositionInterface.h>
2021
#include <maths/CTrendComponent.h>
21-
#include <maths/CTrendTests.h>
2222
#include <maths/ImportExport.h>
2323

2424
#include <boost/ref.hpp>

lib/api/unittest/CAnomalyJobLimitTest.cc

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ void CAnomalyJobLimitTest::testModelledEntityCountForFixedMemoryLimit() {
374374
LOG_DEBUG(<< "Processed " << std::floor(100.0 * progress) << "%");
375375
reportProgress += 0.1;
376376
}
377-
for (std::size_t i = 0; i < 1000; ++i) {
377+
for (std::size_t i = 0; i < 900; ++i) {
378378
rng.generateUniformSamples(0, generators.size(), 1, generator);
379379
TOptionalDouble value{generators[generator[0]](time)};
380380
if (value) {
@@ -392,10 +392,10 @@ void CAnomalyJobLimitTest::testModelledEntityCountForFixedMemoryLimit() {
392392
LOG_DEBUG(<< "Memory status = " << used.s_MemoryStatus);
393393
LOG_DEBUG(<< "Memory usage bytes = " << used.s_Usage);
394394
LOG_DEBUG(<< "Memory limit bytes = " << memoryLimit * 1024 * 1024);
395-
CPPUNIT_ASSERT(used.s_ByFields > 600 && used.s_ByFields < 800);
395+
CPPUNIT_ASSERT(used.s_ByFields > 650 && used.s_ByFields < 850);
396396
CPPUNIT_ASSERT_EQUAL(std::size_t(2), used.s_PartitionFields);
397397
CPPUNIT_ASSERT_DOUBLES_EQUAL(memoryLimit * 1024 * 1024 / 2, used.s_Usage,
398-
memoryLimit * 1024 * 1024 / 40); // Within 5%.
398+
memoryLimit * 1024 * 1024 / 33); // Within 6%.
399399
}
400400

401401
LOG_DEBUG(<< "**** Test partition ****");
@@ -421,7 +421,7 @@ void CAnomalyJobLimitTest::testModelledEntityCountForFixedMemoryLimit() {
421421
LOG_DEBUG(<< "Processed " << std::floor(100.0 * progress) << "%");
422422
reportProgress += 0.1;
423423
}
424-
for (std::size_t i = 0; i < 600; ++i) {
424+
for (std::size_t i = 0; i < 500; ++i) {
425425
rng.generateUniformSamples(0, generators.size(), 1, generator);
426426
TOptionalDouble value{generators[generator[0]](time)};
427427
if (value) {
@@ -438,7 +438,7 @@ void CAnomalyJobLimitTest::testModelledEntityCountForFixedMemoryLimit() {
438438
LOG_DEBUG(<< "# partition = " << used.s_PartitionFields);
439439
LOG_DEBUG(<< "Memory status = " << used.s_MemoryStatus);
440440
LOG_DEBUG(<< "Memory usage = " << used.s_Usage);
441-
CPPUNIT_ASSERT(used.s_PartitionFields > 350 && used.s_PartitionFields < 450);
441+
CPPUNIT_ASSERT(used.s_PartitionFields > 370 && used.s_PartitionFields < 470);
442442
CPPUNIT_ASSERT(static_cast<double>(used.s_ByFields) >
443443
0.97 * static_cast<double>(used.s_PartitionFields));
444444
CPPUNIT_ASSERT_DOUBLES_EQUAL(memoryLimit * 1024 * 1024 / 2, used.s_Usage,
@@ -468,7 +468,7 @@ void CAnomalyJobLimitTest::testModelledEntityCountForFixedMemoryLimit() {
468468
LOG_DEBUG(<< "Processed " << std::floor(100.0 * progress) << "%");
469469
reportProgress += 0.1;
470470
}
471-
for (std::size_t i = 0; i < 12000; ++i) {
471+
for (std::size_t i = 0; i < 9000; ++i) {
472472
TOptionalDouble value{sparse(time)};
473473
if (value) {
474474
dataRows["time"] = core::CStringUtils::typeToString(time);

0 commit comments

Comments
 (0)