-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.py
More file actions
1528 lines (1354 loc) · 55.3 KB
/
executor.py
File metadata and controls
1528 lines (1354 loc) · 55.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function, division
import concurrent.futures
from functools import partial
from itertools import repeat
import time
import pickle
import sys
import math
import json
import cloudpickle
import uproot
import uuid
import warnings
import shutil
from tqdm.auto import tqdm
from collections import defaultdict
from cachetools import LRUCache
import lz4.frame as lz4f
from .processor import ProcessorABC
from .accumulator import accumulate, set_accumulator, Accumulatable
from .dataframe import LazyDataFrame
from ..nanoevents import NanoEventsFactory, schemas
from ..util import _hash
from collections.abc import Mapping, MutableMapping
from dataclasses import dataclass, field, asdict
from typing import Iterable, Callable, Optional, List, Generator, Dict, Union
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
try:
from functools import cached_property
except ImportError:
cached_property = property
_PICKLE_PROTOCOL = pickle.HIGHEST_PROTOCOL
DEFAULT_METADATA_CACHE: MutableMapping = LRUCache(100000)
_PROTECTED_NAMES = {
"dataset",
"filename",
"treename",
"metadata",
"entrystart",
"entrystop",
"fileuuid",
"numentries",
"uuid",
"clusters",
}
class FileMeta(object):
__slots__ = ["dataset", "filename", "treename", "metadata"]
def __init__(self, dataset, filename, treename, metadata=None):
self.dataset = dataset
self.filename = filename
self.treename = treename
self.metadata = metadata
def __hash__(self):
# As used to lookup metadata, no need for dataset
return _hash((self.filename, self.treename))
def __eq__(self, other):
# In case of hash collisions
return self.filename == other.filename and self.treename == other.treename
def maybe_populate(self, cache):
if cache and self in cache:
self.metadata = cache[self]
def populated(self, clusters=False):
"""Return true if metadata is populated
By default, only require bare minimum metadata (numentries, uuid)
If clusters is True, then require cluster metadata to be populated
"""
if self.metadata is None:
return False
elif "numentries" not in self.metadata or "uuid" not in self.metadata:
return False
elif clusters and "clusters" not in self.metadata:
return False
return True
def chunks(self, target_chunksize, align_clusters, dynamic_chunksize):
if align_clusters and dynamic_chunksize:
raise RuntimeError(
"align_clusters cannot be used with a dynamic chunksize."
)
if not self.populated(clusters=align_clusters):
raise RuntimeError
user_keys = set(self.metadata.keys()) - _PROTECTED_NAMES
user_meta = {k: self.metadata[k] for k in user_keys}
if align_clusters:
chunks = [0]
for c in self.metadata["clusters"]:
if c >= chunks[-1] + target_chunksize:
chunks.append(c)
if self.metadata["clusters"][-1] != chunks[-1]:
chunks.append(self.metadata["clusters"][-1])
for start, stop in zip(chunks[:-1], chunks[1:]):
yield WorkItem(
self.dataset,
self.filename,
self.treename,
start,
stop,
self.metadata["uuid"],
user_meta,
)
return target_chunksize
else:
n = max(round(self.metadata["numentries"] / target_chunksize), 1)
actual_chunksize = math.ceil(self.metadata["numentries"] / n)
start = 0
while start < self.metadata["numentries"]:
stop = min(self.metadata["numentries"], start + actual_chunksize)
next_chunksize = yield WorkItem(
self.dataset,
self.filename,
self.treename,
start,
stop,
self.metadata["uuid"],
user_meta,
)
start = stop
if dynamic_chunksize and next_chunksize:
n = max(
math.ceil(
(self.metadata["numentries"] - start) / next_chunksize
),
1,
)
actual_chunksize = math.ceil(
(self.metadata["numentries"] - start) / n
)
if dynamic_chunksize and next_chunksize:
return next_chunksize
else:
return target_chunksize
@dataclass(unsafe_hash=True)
class WorkItem:
dataset: str
filename: str
treename: str
entrystart: int
entrystop: int
fileuuid: str
usermeta: Optional[Dict] = field(default=None, compare=False)
def __len__(self) -> int:
return self.entrystop - self.entrystart
def _compress(item, compression):
return lz4f.compress(
pickle.dumps(item, protocol=_PICKLE_PROTOCOL), compression_level=compression
)
def _decompress(item):
return pickle.loads(lz4f.decompress(item))
class _compression_wrapper(object):
def __init__(self, level, function, name=None):
self.level = level
self.function = function
self.name = name
def __str__(self):
if self.name is not None:
return self.name
try:
name = self.function.__name__
if name == "<lambda>":
return "lambda"
return name
except AttributeError:
return str(self.function)
# no @wraps due to pickle
def __call__(self, *args, **kwargs):
out = self.function(*args, **kwargs)
return _compress(out, self.level)
class _reduce:
def __init__(self, compression):
self.compression = compression
def __str__(self):
return "reduce"
def __call__(self, items):
items = list(items)
if len(items) == 0:
raise ValueError("Empty list provided to reduction")
if self.compression is not None:
out = _decompress(items.pop())
out = accumulate(map(_decompress, items), out)
return _compress(out, self.compression)
return accumulate(items)
def _cancel(job):
try:
# this is not implemented with parsl AppFutures
job.cancel()
except NotImplementedError:
pass
def _futures_handler(futures, timeout):
"""Essentially the same as concurrent.futures.as_completed
but makes sure not to hold references to futures any longer than strictly necessary,
which is important if the future holds a large result.
"""
futures = set(futures)
try:
while futures:
try:
done, futures = concurrent.futures.wait(
futures,
timeout=timeout,
return_when=concurrent.futures.FIRST_COMPLETED,
)
if len(done) == 0:
warnings.warn(
f"No finished jobs after {timeout}s, stopping remaining {len(futures)} jobs early"
)
break
while done:
try:
yield done.pop().result()
except concurrent.futures.CancelledError:
pass
except KeyboardInterrupt:
for job in futures:
_cancel(job)
running = sum(job.running() for job in futures)
warnings.warn(
f"Early stop: cancelled {len(futures) - running} jobs, will wait for {running} running jobs to complete"
)
finally:
running = sum(job.running() for job in futures)
if running:
warnings.warn(
f"Cancelling {running} running jobs (likely due to an exception)"
)
while futures:
_cancel(futures.pop())
@dataclass
class ExecutorBase:
# shared by all executors
status: bool = True
unit: str = "items"
desc: str = "Processing"
compression: Optional[int] = 1
function_name: Optional[str] = None
def __call__(
self,
items: Iterable,
function: Callable,
accumulator: Accumulatable,
):
raise NotImplementedError(
"This class serves as a base class for executors, do not instantiate it!"
)
def copy(self, **kwargs):
tmp = self.__dict__.copy()
tmp.update(kwargs)
return type(self)(**tmp)
@dataclass
class WorkQueueExecutor(ExecutorBase):
"""Execute using Work Queue
For more information, see :ref:`intro-coffea-wq`
Parameters
----------
items : list or generator
Sequence of input arguments
function : callable
A function to be called on each input, which returns an accumulator instance
accumulator : Accumulatable
An accumulator to collect the output of the function
status : bool
If true (default), enable progress bar
unit : str
Label of progress bar unit
desc : str
Label of progress bar description
compression : int, optional
Compress accumulator outputs in flight with LZ4, at level specified (default 9)
Set to ``None`` for no compression.
# work queue specific options:
cores : int
Number of cores for work queue task. If unset, use a whole worker.
memory : int
Amount of memory (in MB) for work queue task. If unset, use a whole worker.
disk : int
Amount of disk space (in MB) for work queue task. If unset, use a whole worker.
gpus : int
Number of GPUs to allocate to each task. If unset, use zero.
resource_monitor : str
If given, one of 'off', 'measure', or 'watchdog'. Default is 'off'.
- 'off': turns off resource monitoring. Overriden if resources_mode
is not set to 'fixed'.
- 'measure': turns on resource monitoring for Work Queue. The
resources used per task are measured.
- 'watchdog': in addition to measuring resources, tasks are terminated if they
go above the cores, memory, or disk specified.
resources_mode : str
one of 'fixed', 'max-seen', or 'max-throughput'. Default is 'fixed'.
Sets the strategy to automatically allocate resources to tasks.
- 'fixed': allocate cores, memory, and disk specified for each task.
- 'max-seen' or 'auto': use the cores, memory, and disk given as maximum values to allocate,
but first try each task by allocating the maximum values seen. Leads
to a good compromise between parallelism and number of retries.
- 'max-throughput': Like max-seen, but first tries the task with an
allocation that maximizes overall throughput.
If resources_mode is other than 'fixed', preprocessing and
accumulation tasks always use the 'max-seen' strategy, as the
former tasks always use the same resources, the latter has a
distribution of resources that increases over time.
split_on_exhaustion: bool
Whether to split a processing task in half according to its chunksize when it exhausts its
the cores, memory, or disk allocated to it. If False, a task that exhausts resources
permanently fails. Default is True.
fast_terminate_workers: int
Terminate workers on which tasks have been running longer than average.
The time limit is computed by multiplying the average runtime of tasks
by the value of 'fast_terminate_workers'. Since there are
legitimately slow tasks, no task may trigger fast termination in
two distinct workers. Less than 1 disables it.
master_name : str
Name to refer to this work queue master.
Sets port to 0 (any available port) if port not given.
port : int
Port number for work queue master program. Defaults to 9123 if
master_name not given.
password_file: str
Location of a file containing a password used to authenticate workers.
extra_input_files: list
A list of files in the current working directory to send along with each task.
Useful for small custom libraries and configuration files needed by the processor.
x509_proxy : str
Path to the X509 user proxy. If None (the default), use the value of the
environment variable X509_USER_PROXY, or fallback to the file /tmp/x509up_u${UID} if
exists. If False, disables the default behavior and no proxy is sent.
environment_file : optional, str
Conda python environment tarball to use. If not given, assume that
the python environment is already setup at the execution site.
wrapper : str
Wrapper script to run/open python environment tarball. Defaults to python_package_run found in PATH.
chunks_per_accum : int
Number of processed chunks per accumulation task. Defaults is 10.
chunks_accum_in_mem : int
Maximum number of chunks to keep in memory at each accumulation step in an accumulation task. Default is 2.
verbose : bool
If true, emit a message on each task submission and completion.
Default is false.
debug_log : str
Filename for debug output
stats_log : str
Filename for tasks statistics output
transactions_log : str
Filename for tasks lifetime reports output
print_stdout : bool
If true (default), print the standard output of work queue task on completion.
custom_init : function, optional
A function that takes as an argument the queue's WorkQueue object.
The function is called just before the first work unit is submitted
to the queue.
"""
# Standard executor options:
compression: Optional[int] = 9 # as recommended by lz4
retries: int = 2 # task executes at most 3 times
# wq executor options:
master_name: Optional[str] = None
port: Optional[int] = None
filepath: str = "."
events_total: Optional[int] = None
x509_proxy: Optional[str] = None
verbose: bool = False
print_stdout: bool = False
bar_format: str = "{desc:<14}{percentage:3.0f}%|{bar}{r_bar:<55}"
debug_log: Optional[str] = None
stats_log: Optional[str] = None
transactions_log: Optional[str] = None
password_file: Optional[str] = None
environment_file: Optional[str] = None
extra_input_files: List = field(default_factory=list)
wrapper: Optional[str] = shutil.which("python_package_run")
resource_monitor: Optional[str] = "off"
resources_mode: Optional[str] = "fixed"
split_on_exhaustion: Optional[bool] = True
fast_terminate_workers: Optional[int] = None
cores: Optional[int] = None
memory: Optional[int] = None
disk: Optional[int] = None
gpus: Optional[int] = None
chunks_per_accum: int = 10
chunks_accum_in_mem: int = 2
chunksize: int = 1024
dynamic_chunksize: Optional[Dict] = None
custom_init: Optional[Callable] = None
def __call__(
self,
items: Iterable,
function: Callable,
accumulator: Accumulatable,
):
try:
import work_queue # noqa
import dill # noqa
from .work_queue_tools import work_queue_main
except ImportError as e:
print(
"You must have Work Queue and dill installed to use WorkQueueExecutor!"
)
raise e
from .work_queue_tools import _get_x509_proxy
if self.x509_proxy is None:
self.x509_proxy = _get_x509_proxy()
return work_queue_main(
items,
function,
accumulator,
**self.__dict__,
)
@dataclass
class IterativeExecutor(ExecutorBase):
"""Execute in one thread iteratively
Parameters
----------
items : list
List of input arguments
function : callable
A function to be called on each input, which returns an accumulator instance
accumulator : Accumulatable
An accumulator to collect the output of the function
status : bool
If true (default), enable progress bar
unit : str
Label of progress bar unit
desc : str
Label of progress bar description
compression : int, optional
Ignored for iterative executor
"""
workers: int = 1
def __call__(
self,
items: Iterable,
function: Callable,
accumulator: Accumulatable,
):
if len(items) == 0:
return accumulator
gen = tqdm(
items,
disable=not self.status,
unit=self.unit,
total=len(items),
desc=self.desc,
)
gen = map(function, gen)
return accumulate(gen, accumulator)
@dataclass
class FuturesExecutor(ExecutorBase):
"""Execute using multiple local cores using python futures
Parameters
----------
items : list
List of input arguments
function : callable
A function to be called on each input, which returns an accumulator instance
accumulator : Accumulatable
An accumulator to collect the output of the function
pool : concurrent.futures.Executor class or instance, optional
The type of futures executor to use, defaults to ProcessPoolExecutor.
You can pass an instance instead of a class to re-use an executor
workers : int, optional
Number of parallel processes for futures (default 1)
status : bool, optional
If true (default), enable progress bar
unit : str, optional
Label of progress bar unit (default: 'Processing')
desc : str, optional
Label of progress bar description (default: 'items')
compression : int, optional
Compress accumulator outputs in flight with LZ4, at level specified (default 1)
Set to ``None`` for no compression.
tailtimeout : int, optional
Timeout requirement on job tails. Cancel all remaining jobs if none have finished
in the timeout window.
"""
pool: Union[Callable[..., concurrent.futures.Executor], concurrent.futures.Executor] = concurrent.futures.ProcessPoolExecutor # fmt: skip
workers: int = 1
tailtimeout: Optional[int] = None
def __getstate__(self):
return dict(self.__dict__, pool=None)
def __call__(
self,
items: Iterable,
function: Callable,
accumulator: Accumulatable,
):
if len(items) == 0:
return accumulator
if self.compression is not None:
function = _compression_wrapper(self.compression, function)
def processwith():
i = 0
items_list = list(items)
while i < len(items_list):
print("{}/{}".format(i,len(items_list)))
try:
with self.pool(max_workers=self.workers) as poolinstance:
batch_size = 10000
gen = _futures_handler(
{poolinstance.submit(function, items_list[j]) for j in range(i,i+min(len(items_list)-i,batch_size))}, self.tailtimeout
)
if i == 0:
tmp = accumulator
tmp = accumulate(
tqdm(
gen if self.compression is None else map(_decompress, gen),
disable=not self.status,
unit=self.unit,
# total=len(items),
total=min(len(items_list)-i,batch_size),
desc=self.desc,
),
tmp,
)
i = i + batch_size
poolinstance.shutdown()
finally:
gen.close()
return tmp
gen = _futures_handler(
{pool.submit(function, item) for item in items}, self.tailtimeout
)
try:
tmp = accumulate(
tqdm(
gen if self.compression is None else map(_decompress, gen),
disable=not self.status,
unit=self.unit,
total=len(items),
desc=self.desc,
),
accumulator,
)
return tmp
finally:
gen.close()
if isinstance(self.pool, concurrent.futures.Executor):
return processwith(pool=self.pool)
else:
# assume its a class then
# with self.pool(max_workers=self.workers) as poolinstance:
# return processwith(pool=poolinstance)
return processwith()
@dataclass
class DaskExecutor(ExecutorBase):
"""Execute using dask futures
Parameters
----------
items : list
List of input arguments
function : callable
A function to be called on each input, which returns an accumulator instance
accumulator : Accumulatable
An accumulator to collect the output of the function
client : distributed.client.Client
A dask distributed client instance
treereduction : int, optional
Tree reduction factor for output accumulators (default: 20)
status : bool, optional
If true (default), enable progress bar
compression : int, optional
Compress accumulator outputs in flight with LZ4, at level specified (default 1)
Set to ``None`` for no compression.
priority : int, optional
Task priority, default 0
retries : int, optional
Number of retries for failed tasks (default: 3)
heavy_input : serializable, optional
Any value placed here will be broadcast to workers and joined to input
items in a tuple (item, heavy_input) that is passed to function.
function_name : str, optional
Name of the function being passed
use_dataframes: bool, optional
Retrieve output as a distributed Dask DataFrame (default: False).
The outputs of individual tasks must be Pandas DataFrames.
.. note:: If ``heavy_input`` is set, ``function`` is assumed to be pure.
"""
client: Optional["dask.distributed.Client"] = None # noqa
treereduction: int = 20
priority: int = 0
retries: int = 3
heavy_input: Optional[bytes] = None
use_dataframes: bool = False
# secret options
worker_affinity: bool = False
def __getstate__(self):
return dict(self.__dict__, client=None)
def __call__(
self,
items: Iterable,
function: Callable,
accumulator: Accumulatable,
):
if len(items) == 0:
return accumulator
import dask.dataframe as dd
from dask.distributed import Client
if self.client is None:
self.client = Client(threads_per_worker=1)
if self.use_dataframes:
self.compression = None
reducer = _reduce(self.compression)
if self.compression is not None:
function = _compression_wrapper(
self.compression, function, name=self.function_name
)
if self.heavy_input is not None:
# client.scatter is not robust against adaptive clusters
# https://github.com/CoffeaTeam/coffea/issues/465
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "Large object of size")
items = list(
zip(
items, repeat(self.client.submit(lambda x: x, self.heavy_input))
)
)
work = []
if self.worker_affinity:
workers = list(self.client.run(lambda: 0))
def belongsto(heavy_input, workerindex, item):
if heavy_input is not None:
item = item[0]
hashed = _hash(
(item.fileuuid, item.treename, item.entrystart, item.entrystop)
)
return hashed % len(workers) == workerindex
for workerindex, worker in enumerate(workers):
work.extend(
self.client.map(
function,
[
item
for item in items
if belongsto(self.heavy_input, workerindex, item)
],
pure=(self.heavy_input is not None),
priority=self.priority,
retries=self.retries,
workers={worker},
allow_other_workers=False,
)
)
else:
work = self.client.map(
function,
items,
pure=(self.heavy_input is not None),
priority=self.priority,
retries=self.retries,
)
if (self.function_name == "get_metadata") or not self.use_dataframes:
while len(work) > 1:
work = self.client.map(
reducer,
[
work[i : i + self.treereduction]
for i in range(0, len(work), self.treereduction)
],
pure=True,
priority=self.priority,
retries=self.retries,
)
work = work[0]
if self.status:
from distributed import progress
# FIXME: fancy widget doesn't appear, have to live with boring pbar
progress(work, multi=True, notebook=False)
return accumulate(
[
work.result()
if self.compression is None
else _decompress(work.result())
],
accumulator,
)
else:
if self.status:
from distributed import progress
progress(work, multi=True, notebook=False)
return {"out": dd.from_delayed(work)}
@dataclass
class ParslExecutor(ExecutorBase):
"""Execute using parsl pyapp wrapper
Parameters
----------
items : list
List of input arguments
function : callable
A function to be called on each input, which returns an accumulator instance
accumulator : Accumulatable
An accumulator to collect the output of the function
config : parsl.config.Config, optional
A parsl DataFlow configuration object. Necessary if there is no active kernel
.. note:: In general, it is safer to construct the DFK with ``parsl.load(config)`` prior to calling this function
status : bool
If true (default), enable progress bar
unit : str
Label of progress bar unit
desc : str
Label of progress bar description
compression : int, optional
Compress accumulator outputs in flight with LZ4, at level specified (default 1)
Set to ``None`` for no compression.
tailtimeout : int, optional
Timeout requirement on job tails. Cancel all remaining jobs if none have finished
in the timeout window.
"""
tailtimeout: Optional[int] = None
config: Optional["parsl.config.Config"] = None # noqa
def __call__(
self,
items: Iterable,
function: Callable,
accumulator: Accumulatable,
):
if len(items) == 0:
return accumulator
import parsl
from parsl.app.app import python_app
from .parsl.timeout import timeout
if self.compression is not None:
function = _compression_wrapper(self.compression, function)
cleanup = False
try:
parsl.dfk()
except RuntimeError:
cleanup = True
pass
if cleanup and self.config is None:
raise RuntimeError(
"No active parsl DataFlowKernel, must specify a config to construct one"
)
elif not cleanup and self.config is not None:
raise RuntimeError("An active parsl DataFlowKernel already exists")
elif self.config is not None:
parsl.clear()
parsl.load(self.config)
app = timeout(python_app(function))
gen = _futures_handler(map(app, items), self.tailtimeout)
try:
accumulator = accumulate(
tqdm(
gen if self.compression is None else map(_decompress, gen),
disable=not self.status,
unit=self.unit,
total=len(items),
desc=self.desc,
),
accumulator,
)
finally:
gen.close()
if cleanup:
parsl.dfk().cleanup()
parsl.clear()
return accumulator
class ParquetFileContext:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
pass
@dataclass
class Runner:
"""A tool to run a processor using uproot for data delivery
A convenience wrapper to submit jobs for a file set, which is a
dictionary of dataset: [file list] entries. Supports only uproot TTree
reading, via NanoEvents or LazyDataFrame. For more customized processing,
e.g. to read other objects from the files and pass them into data frames,
one can write a similar function in their user code.
Parameters
----------
executor : ExecutorBase instance
Executor, which implements a callable with inputs: items, function, accumulator
and performs some action equivalent to:
``for item in items: accumulator += function(item)``
pre_executor : ExecutorBase instance
Executor, used to calculate fileset metadata
Defaults to executor
chunksize : int, optional
Maximum number of entries to process at a time in the data frame, default: 100k
maxchunks : int, optional
Maximum number of chunks to process per dataset
Defaults to processing the whole dataset
metadata_cache : mapping, optional
A dict-like object to use as a cache for (file, tree) metadata that is used to
determine chunking. Defaults to a in-memory LRU cache that holds 100k entries
(about 1MB depending on the length of filenames, etc.) If you edit an input file
(please don't) during a session, the session can be restarted to clear the cache.
dynamic_chunksize : dict, optional
Whether to adapt the chunksize for units of work to run in the targets given.
Currently supported are 'wall_time' (in seconds), and 'memory' (in MB).
E.g., with {"wall_time": 120, "memory": 2048}, the chunksize will
be dynamically adapted so that processing jobs each run in about
two minutes, using two GB of memory. (Currently only for the WorkQueueExecutor.)
"""
executor: ExecutorBase
pre_executor: Optional[ExecutorBase] = None
chunksize: int = 100000
maxchunks: Optional[int] = None
metadata_cache: Optional[MutableMapping] = None
dynamic_chunksize: Optional[Dict] = None
skipbadfiles: bool = False
xrootdtimeout: Optional[int] = None
align_clusters: bool = False
savemetrics: bool = False
mmap: bool = False
schema: Optional[schemas.BaseSchema] = schemas.BaseSchema
cachestrategy: Optional[Union[Literal["dask-worker"], Callable[..., MutableMapping]]] = None # fmt: skip
processor_compression: int = 1
ceph_config_path: Optional[str] = None
format: str = "root"
def __post_init__(self):
if self.pre_executor is None:
self.pre_executor = self.executor
assert isinstance(
self.executor, ExecutorBase
), "Expected executor to derive from ExecutorBase"
assert isinstance(
self.pre_executor, ExecutorBase
), "Expected pre_executor to derive from ExecutorBase"
if self.metadata_cache is None:
self.metadata_cache = DEFAULT_METADATA_CACHE
if self.align_clusters and self.dynamic_chunksize:
raise RuntimeError(
"align_clusters and dynamic_chunksize cannot be used simultaneously"
)
if self.maxchunks and self.dynamic_chunksize:
raise RuntimeError(
"maxchunks and dynamic_chunksize cannot be used simultaneously"
)
if self.dynamic_chunksize and not isinstance(self.executor, WorkQueueExecutor):
raise RuntimeError(
"dynamic_chunksize currently only supported by the WorkQueueExecutor"
)
assert self.format in ("root", "parquet")
@property
def retries(self):
if isinstance(self.executor, DaskExecutor):
retries = 0
else:
retries = getattr(self.executor, "retries", 0)
assert retries >= 0
return retries
@property
def use_dataframes(self):
if isinstance(self.executor, DaskExecutor):
return self.executor.use_dataframes
else:
return False
@staticmethod
def get_cache(cachestrategy):
cache = None
if cachestrategy == "dask-worker":
from distributed import get_worker
from coffea.processor.dask import ColumnCache
worker = get_worker()
try:
cache = worker.plugins[ColumnCache.name]
except KeyError:
# emit warning if not found?
pass
elif callable(cachestrategy):
cache = cachestrategy()
return cache
@staticmethod
def automatic_retries(retries: int, skipbadfiles: bool, func, *args, **kwargs):
"""This should probably defined on Executor-level."""
import warnings
retry_count = 0
while retry_count <= retries:
try:
return func(*args, **kwargs)