Skip to content
This repository was archived by the owner on Jun 30, 2022. It is now read-only.

Commit 30af51a

Browse files
charlesccychenaaltay
authored andcommitted
Introduce OperationCouters.should_sample
This change implements sampling for size estimation, so we don't calculate the size of every element. Size estimation itself is not yet implemented. Cython is used to improve performance. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=124303848
1 parent c731121 commit 30af51a

4 files changed

Lines changed: 148 additions & 11 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Copyright 2016 Google Inc. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the 'License');
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an 'AS IS' BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
cimport cython
16+
cimport libc.stdint
17+
18+
cdef class OperationCounters(object):
19+
cdef public _counter_factory
20+
cdef public element_counter
21+
cdef public mean_byte_counter
22+
cdef public coder
23+
cdef public _active_accumulators
24+
cdef public libc.stdint.int64_t _sample_counter
25+
cdef public libc.stdint.int64_t _next_sample
26+
27+
cpdef update_from(self, windowed_value, coder=*)
28+
cpdef update_collect(self)
29+
30+
cdef libc.stdint.int64_t _compute_next_sample(self, libc.stdint.int64_t i)
31+
cdef bint should_sample(self)

google/cloud/dataflow/worker/opcounters.py

Lines changed: 83 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,43 +12,115 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
# cython: profile=True
16+
1517
"""Counters collect the progress of the Worker for reporting to the service."""
1618

1719
from __future__ import absolute_import
20+
import math
21+
import random
1822

23+
from google.cloud.dataflow.coders import WindowedValueCoder
24+
from google.cloud.dataflow.transforms.window import WindowedValue
1925
from google.cloud.dataflow.utils.counters import Counter
2026

2127

2228
class OperationCounters(object):
2329
"""The set of basic counters to attach to an Operation."""
2430

2531
def __init__(self, counter_factory, step_name, coder, output_index):
32+
self._counter_factory = counter_factory
2633
self.element_counter = counter_factory.get_counter(
2734
'%s-out%d-ElementCount' % (step_name, output_index), Counter.SUM)
2835
self.mean_byte_counter = counter_factory.get_counter(
2936
'%s-out%d-MeanByteCount' % (step_name, output_index), Counter.MEAN)
3037
self.coder = coder
38+
self._active_accumulators = []
39+
self._sample_counter = 0
40+
self._next_sample = 0
3141

32-
def update_from(self, windowed_value, coder=None): # pylint: disable=unused-argument
42+
def update_from(self, windowed_value, coder=None):
3343
"""Add one value to this counter."""
3444
self.element_counter.update(1)
35-
# TODO(silviuc): Implement estimated size sampling.
36-
# TODO(gildea):
37-
# Actually compute the encoded size of this value.
38-
# In spirit, something like this:
39-
# if coder is None:
40-
# coder = self.coder
41-
# coder.store_estimated_size(windowed_value, byte_size_accumulator)
42-
# but will need to do sampling.
45+
if self.should_sample():
46+
byte_size_accumulator = self._counter_factory.get_counter(
47+
'%s-temp%d' % (self.mean_byte_counter.name, self._sample_counter),
48+
Counter.SUM)
49+
self._active_accumulators.append(byte_size_accumulator)
50+
# Shuffle operations may pass in their own coder
51+
if coder is None:
52+
coder = self.coder
53+
# Some Readers and Writers return windowed values even
54+
# though their output encoding does not claim to be windowed.
55+
# TODO(ccy): fix output encodings to be consistent here.
56+
if (isinstance(windowed_value, WindowedValue)
57+
and not isinstance(coder, WindowedValueCoder)):
58+
coder = WindowedValueCoder(coder)
59+
# TODO(gildea):
60+
# Actually compute the encoded size of this value:
61+
# coder.store_estimated_size(windowed_value, byte_size_accumulator)
4362

4463
def update_collect(self):
4564
"""Collects the accumulated size estimates.
4665
4766
Now that the element has been processed, we ask our accumulator
4867
for the total and store the result in a counter.
4968
"""
50-
# TODO(silviuc): Implement estimated size sampling.
51-
pass
69+
for pending in self._active_accumulators:
70+
self.mean_byte_counter.update(pending.value())
71+
self._active_accumulators = []
72+
73+
def _compute_next_sample(self, i):
74+
# https://en.wikipedia.org/wiki/Reservoir_sampling#Fast_Approximation
75+
gap = math.log(1.0 - random.random()) / math.log(1.0 - 10.0/i)
76+
return i + math.floor(gap)
77+
78+
def should_sample(self):
79+
"""Determines whether to sample the next element.
80+
81+
Size calculation can be expensive, so we don't do it for each element.
82+
Because we need only an estimate of average size, we sample.
83+
84+
We always sample the first 10 elements, then the sampling rate
85+
is approximately 10/N. After reading N elements, of the next N,
86+
we will sample approximately 10*ln(2) (about 7) elements.
87+
88+
This algorithm samples at the same rate as Reservoir Sampling, but
89+
it never throws away early results. (Because we keep only a
90+
running accumulation, storage is not a problem, so there is no
91+
need to discard earlier calculations.)
92+
93+
Because we accumulate and do not replace, our statistics are
94+
biased toward early data. If the data are distributed uniformly,
95+
this is not a problem. If the data change over time (i.e., the
96+
element size tends to grow or shrink over time), our estimate will
97+
show the bias. We could correct this by giving weight N to each
98+
sample, since each sample is a stand-in for the N/(10*ln(2))
99+
samples around it, which is proportional to N. Since we do not
100+
expect biased data, for efficiency we omit the extra multiplication.
101+
We could reduce the early-data bias by putting a lower bound on
102+
the sampling rate.
103+
104+
Computing random.randint(1, self._sample_counter) for each element
105+
is too slow, so when the sample size is big enough (we estimate 30
106+
is big enough), we estimate the size of the gap after each sample.
107+
This estimation allows us to call random much less often.
108+
109+
Returns:
110+
True if it is time to compute another element's size.
111+
"""
112+
113+
self._sample_counter += 1
114+
if self._next_sample == 0:
115+
if random.randint(1, self._sample_counter) <= 10:
116+
if self._sample_counter > 30:
117+
self._next_sample = self._compute_next_sample(self._sample_counter)
118+
return True
119+
return False
120+
elif self._sample_counter >= self._next_sample:
121+
self._next_sample = self._compute_next_sample(self._sample_counter)
122+
return True
123+
return False
52124

53125
def __str__(self):
54126
return '<%s [%s]>' % (self.__class__.__name__,

google/cloud/dataflow/worker/opcounters_test.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"""Tests for worker counters."""
1616

1717
import logging
18+
import random
1819
import unittest
1920

2021
from google.cloud.dataflow import coders
@@ -91,6 +92,38 @@ def test_update_multiple(self):
9192
opcounts.update_collect()
9293
self.verify_counters(opcounts, 3)
9394

95+
def test_should_sample(self):
96+
# Order of magnitude more buckets than highest constant in code under test.
97+
buckets = [0] * 300
98+
# The seed is arbitrary and exists just to ensure this test is robust.
99+
# If you don't like this seed, try your own; the test should still pass.
100+
random.seed(1717)
101+
# Do enough runs that the expected hits even in the last buckets
102+
# is big enough to expect some statistical smoothing.
103+
total_runs = 10 * len(buckets)
104+
105+
# Fill the buckets.
106+
for _ in xrange(total_runs):
107+
opcounts = OperationCounters(CounterFactory(), 'some-name',
108+
coders.PickleCoder(), 0)
109+
for i in xrange(len(buckets)):
110+
if opcounts.should_sample():
111+
buckets[i] += 1
112+
113+
# Look at the buckets to see if they are likely.
114+
for i in xrange(10):
115+
self.assertEqual(total_runs, buckets[i])
116+
for i in xrange(10, len(buckets)):
117+
self.assertTrue(buckets[i] > 7 * total_runs / i,
118+
'i=%d, buckets[i]=%d, expected=%d, ratio=%f' % (
119+
i, buckets[i],
120+
10 * total_runs / i,
121+
buckets[i] / (10.0 * total_runs / i)))
122+
self.assertTrue(buckets[i] < 14 * total_runs / i,
123+
'i=%d, buckets[i]=%d, expected=%d, ratio=%f' % (
124+
i, buckets[i],
125+
10 * total_runs / i,
126+
buckets[i] / (10.0 * total_runs / i)))
94127

95128
if __name__ == '__main__':
96129
logging.getLogger().setLevel(logging.INFO)

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ def get_download_url():
114114
'google/cloud/dataflow/coders/coder_impl.py',
115115
'google/cloud/dataflow/runners/common.py',
116116
'google/cloud/dataflow/worker/executor.py',
117+
'google/cloud/dataflow/worker/opcounters.py',
117118
'google/cloud/dataflow/utils/counters.py',
118119
]),
119120
setup_requires=['nose>=1.0'],

0 commit comments

Comments
 (0)