Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
* (Go) Added pass-through registration for fixed and variable length string and bytes logical types ([#39684](https://github.com/apache/beam/issues/39684)).
* (Java) Added `LogElements.stdout()`, which prints elements with `System.out.println` instead of logging them through SLF4J, so they still show up when no SLF4J provider is on the classpath ([#41573](https://github.com/apache/beam/pull/41573)).
* (Python) `OnnxModelHandlerNumpy` and the XGBoost model handlers now support model updates through `model_metadata_pcoll`, for example with `WatchFilePattern`. ONNX predictions now also set `model_id` ([#41384](https://github.com/apache/beam/issues/41384)).
* (Python) The DirectRunner's bundle-based runner now honors `ProfilingOptions` (`--profile_cpu`, `--profile_memory`, `--profile_location`, `--profile_sample_rate`), writing profiles for the work executed on its worker thread ([#18011](https://github.com/apache/beam/issues/18011)).

### Performance

Expand Down
6 changes: 5 additions & 1 deletion sdks/python/apache_beam/runners/direct/direct_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from apache_beam import typehints
from apache_beam.internal.util import ArgumentPlaceholder
from apache_beam.options.pipeline_options import DirectOptions
from apache_beam.options.pipeline_options import ProfilingOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.options.value_provider import RuntimeValueProvider
from apache_beam.pvalue import PCollection
Expand All @@ -52,6 +53,7 @@
from apache_beam.transforms.timeutil import TimeDomain
from apache_beam.typehints import trivial_inference
from apache_beam.utils.interactive_utils import is_in_ipython
from apache_beam.utils.profiler import Profile

__all__ = ['BundleBasedDirectRunner', 'DirectRunner', 'SwitchingDirectRunner']

Expand Down Expand Up @@ -610,7 +612,9 @@ def visit_transform(self, applied_ptransform):
executor = Executor(
self.consumer_tracking_visitor.value_to_consumers,
TransformEvaluatorRegistry(evaluation_context),
evaluation_context)
evaluation_context,
profiler_factory=Profile.factory_from_options(
options.view_as(ProfilingOptions)))
# DirectRunner does not support injecting
# PipelineOptions values at runtime
RuntimeValueProvider.set_runtime_options({})
Expand Down
35 changes: 35 additions & 0 deletions sdks/python/apache_beam/runners/direct/direct_runner_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@

# pytype: skip-file

import os
import pstats
import tempfile
import threading
import unittest
from collections import defaultdict
Expand All @@ -31,10 +34,12 @@
from apache_beam.metrics.metric import Metrics
from apache_beam.metrics.metric import MetricsFilter
from apache_beam.metrics.metricbase import MetricName
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.pipeline import Pipeline
from apache_beam.runners import DirectRunner
from apache_beam.runners import TestDirectRunner
from apache_beam.runners import create_runner
from apache_beam.runners.direct.direct_runner import BundleBasedDirectRunner
from apache_beam.runners.direct.evaluation_context import _ExecutionContext
from apache_beam.runners.direct.transform_evaluator import _GroupByKeyOnlyEvaluator
from apache_beam.runners.direct.transform_evaluator import _TransformEvaluator
Expand Down Expand Up @@ -154,6 +159,36 @@ def test_create_runner(self):
isinstance(create_runner('TestDirectRunner'), TestDirectRunner))


class BundleBasedDirectRunnerProfilingTest(unittest.TestCase):
def _run_pipeline(self, options):
with beam.Pipeline(runner=BundleBasedDirectRunner(),
options=options) as pipeline:
_ = pipeline | beam.Create([1, 2, 3]) | beam.Map(lambda x: x + 1)

def test_writes_profile_when_profiling_enabled(self):
with tempfile.TemporaryDirectory() as profile_location:
options = PipelineOptions(
['--profile_cpu', '--profile_location=%s' % profile_location])
self._run_pipeline(options)

profile_files = [
os.path.join(root, name)
for root, _, names in os.walk(profile_location) for name in names
]
cpu_profiles = [path for path in profile_files if 'cpu_profile' in path]
self.assertTrue(
cpu_profiles,
'Expected a CPU profile to be written, got: %s' % profile_files)
self.assertGreater(len(pstats.Stats(cpu_profiles[0]).stats), 0)

def test_writes_no_profile_when_profiling_disabled(self):
with tempfile.TemporaryDirectory() as profile_location:
options = PipelineOptions(['--profile_location=%s' % profile_location])
self._run_pipeline(options)

self.assertEqual([], os.listdir(profile_location))


class BundleBasedRunnerTest(unittest.TestCase):
def test_type_hints(self):
with test_pipeline.TestPipeline(runner='BundleBasedDirectRunner') as p:
Expand Down
31 changes: 26 additions & 5 deletions sdks/python/apache_beam/runners/direct/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@
# pytype: skip-file

import collections
import contextlib
import itertools
import logging
import queue
import threading
import traceback
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable
from typing import Optional
from weakref import WeakValueDictionary

Expand All @@ -40,6 +42,7 @@
from apache_beam.runners.direct.bundle_factory import _Bundle
from apache_beam.runners.direct.evaluation_context import EvaluationContext
from apache_beam.runners.direct.transform_evaluator import TransformEvaluatorRegistry
from apache_beam.utils.profiler import Profile

_LOGGER = logging.getLogger(__name__)

Expand All @@ -61,10 +64,14 @@ class _ExecutorServiceWorker(threading.Thread):
TIMEOUT = 5

def __init__(
self, queue: 'queue.Queue[_ExecutorService.CallableTask]', index):
self,
queue: 'queue.Queue[_ExecutorService.CallableTask]',
index,
profiler_factory: Optional[Callable[..., 'Profile']] = None):
super().__init__()
self.queue = queue
self._index = index
self._profiler_factory = profiler_factory
self._default_name = 'ExecutorServiceWorker-' + str(index)
self._update_name()
self.shutdown_requested = False
Expand All @@ -91,6 +98,14 @@ def _get_task_or_none(self) -> Optional['_ExecutorService.CallableTask']:
return None

def run(self):
profiler = None
if self._profiler_factory:
profiler = self._profiler_factory(
'direct-worker-%d' % self._index, time_prefix='')
with profiler if profiler else contextlib.nullcontext():
self._run_tasks()

def _run_tasks(self):
state_sampler = statesampler.StateSampler('', counters.CounterFactory())
statesampler.set_current_tracker(state_sampler)
while not self.shutdown_requested:
Expand All @@ -107,10 +122,14 @@ def run(self):
def shutdown(self):
self.shutdown_requested = True

def __init__(self, num_workers):
def __init__(
self,
num_workers,
profiler_factory: Optional[Callable[..., 'Profile']] = None):
self.queue: queue.Queue[_ExecutorService.CallableTask] = queue.Queue()
self.workers = [
_ExecutorService._ExecutorServiceWorker(self.queue, i)
_ExecutorService._ExecutorServiceWorker(
self.queue, i, profiler_factory=profiler_factory)
for i in range(num_workers)
]
self.shutdown_requested = False
Expand Down Expand Up @@ -427,9 +446,11 @@ def __init__(
self,
value_to_consumers,
transform_evaluator_registry,
evaluation_context: 'EvaluationContext'):
evaluation_context: 'EvaluationContext',
profiler_factory: Optional[Callable[..., 'Profile']] = None):
self.executor_service = _ExecutorService(
_ExecutorServiceParallelExecutor.NUM_WORKERS)
_ExecutorServiceParallelExecutor.NUM_WORKERS,
profiler_factory=profiler_factory)
self.transform_executor_services = _TransformExecutorServices(
self.executor_service)
self.value_to_consumers = value_to_consumers
Expand Down
Loading