forked from ActivitySim/activitysim
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mp_tasks.py
2180 lines (1742 loc) · 82.1 KB
/
mp_tasks.py
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
# ActivitySim
# See full license in LICENSE.txt.
from __future__ import annotations
import glob
import importlib
import logging
import multiprocessing
import os
import sys
import time
import traceback
from collections import OrderedDict
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from activitysim.core import config, mem, tracing, util, workflow
from activitysim.core.configuration import FileSystem, Settings
from activitysim.core.workflow.checkpoint import (
CHECKPOINT_NAME,
CHECKPOINT_TABLE_NAME,
FINAL_CHECKPOINT_NAME,
NON_TABLE_COLUMNS,
ParquetStore,
)
logger = logging.getLogger(__name__)
LAST_CHECKPOINT = "_"
MEM_TRACE_TICKS = 5
"""
mp_tasks - activitysim multiprocessing overview
Activitysim runs a list of models sequentially, performing various computational operations
on tables. Model steps can modify values in existing tables, add columns, or create additional
tables. Activitysim provides the facility, via expression files, to specify vectorized operations
on data tables. The ability to vectorize operations depends upon the independence of the
computations performed on the vectorized elements.
Python is agonizingly slow performing scalar operations sequentially on large datasets, so
vectorization (using pandas and/or numpy) is essential for good performance.
Fortunately most activity based model simulation steps are row independent at the household,
person, tour, or trip level. The decisions for one household are independent of the choices
made by other households. Thus it is (generally speaking) possible to run an entire simulation
on a household sample with only one household, and get the same result for that household as
you would running the simulation on a thousand households. (See the shared data section below
for an exception to this highly convenient situation.)
The random number generator supports this goal by providing streams of random numbers
for each households and person that are mutually independent and repeatable across model runs
and processes.
To the extent that simulation model steps are row independent, we can implement most simulations
as a series of vectorized operations on pandas DataFrames and numpy arrays. These vectorized
operations are much faster than sequential python because they are implemented by native code
(compiled C) and are to some extent multi-threaded. But the benefits of numpy multi-processing are
limited because they only apply to atomic numpy or pandas calls, and as soon as control returns
to python it is single-threaded and slow.
Multi-threading is not an attractive strategy to get around the python performance problem because
of the limitations imposed by python's global interpreter lock (GIL). Rather than struggling with
python multi-threading, this module uses the python multiprocessing to parallelize certain models.
Because of activitysim's modular and extensible architecture, we don't hardwire the multiprocessing
architecture. The specification of which models should be run in parallel, how many processers
should be used, and the segmentation of the data between processes are all specified in the
settings config file. For conceptual simplicity, the single processing model as treated as
dominant (because even though in practice multiprocessing may be the norm for production runs,
the single-processing model will be used in development and debugging and keeping it dominant
will tend to concentrate the multiprocessing-specific code in one place and prevent multiprocessing
considerations from permeating the code base obscuring the model-specific logic.
The primary function of the multiprocessing settings are to identify distinct stages of
computation, and to specify how many simultaneous processes should be used to perform them,
and how the data to be treated should be apportioned between those processes. We assume that
the data can be apportioned between subprocesses according to the index of a single primary table
(e.g. households) or else are by derivative or dependent tables that reference that table's index
(primary key) with a ref_col (foreign key) sharing the name of the primary table's key.
Generally speaking, we assume that any new tables that are created are directly dependent on the
previously existing tables, and all rows in new tables are either attributable to previously
existing rows in the pipeline tables, or are global utility tables that are identical across
sub-processes.
Note: There are a few exceptions to 'row independence', such as school and location choice models,
where the model behavior is externally constrained or adjusted. For instance, we want school
location choice to match known aggregate school enrollments by zone. Similarly, a parking model
(not yet implemented) might be constrained by availability. These situations require special
handling.
::
models:
### mp_initialize step
- initialize_landuse
- compute_accessibility
- initialize_households
### mp_households step
- school_location
- workplace_location
- auto_ownership_simulate
- free_parking
### mp_summarize step
- write_tables
multiprocess_steps:
- name: mp_initialize
begin: initialize_landuse
- name: mp_households
begin: school_location
num_processes: 2
slice:
tables:
- households
- persons
- name: mp_summarize
begin: write_tables
The multiprocess_steps setting above annotates the models list to indicate that the simulation
should be broken into three steps.
The first multiprocess_step (mp_initialize) begins with the initialize_landuse step and is
implicity single-process because there is no 'slice' key indicating how to apportion the tables.
This first step includes all models listed in the 'models' setting up until the first step
in the next multiprocess_steps.
The second multiprocess_step (mp_households) starts with the school location model and continues
through auto_ownership_simulate. The 'slice' info indicates that the tables should be sliced by
households, and that persons is a dependent table and so and persons with a ref_col (foreign key
column with the same name as the Households table index) referencing a household record should be
taken to 'belong' to that household. Similarly, any other table that either share an index
(i.e. having the same name) with either the households or persons table, or have a ref_col to
either of their indexes, should also be considered a dependent table.
The num_processes setting of 2 indicates that the pipeline should be split in two, and half of the
households should be apportioned into each subprocess pipeline, and all dependent tables should
likewise be apportioned accordingly. All other tables (e.g. land_use) that do share an index (name)
or have a ref_col should be considered mirrored and be included in their entirety.
The primary table is sliced by num_processes-sized strides. (e.g. for num_processes == 2, the
sub-processes get every second record starting at offsets 0 and 1 respectively. All other dependent
tables slices are based (directly or indirectly) on this primary stride segmentation of the primary
table index.
Two separate sub-process are launched (num_processes == 2) and each passed the name of their
apportioned pipeline file. They execute independently and if they terminate successfully, their
contents are then coalesced into a single pipeline file whose tables should then be essentially
the same as it had been generated by a single process.
We assume that any new tables that are created by the sub-processes are directly dependent on the
previously primary tables or are mirrored. Thus we can coalesce the sub-process pipelines by
concatenating the primary and dependent tables and simply retaining any copy of the mirrored tables
(since they should all be identical.)
The third multiprocess_step (mp_summarize) then is handled in single-process mode and runs the
write_tables model, writing the results, but also leaving the tables in the pipeline, with
essentially the same tables and results as if the whole simulation had been run as a single process.
"""
"""
shared data
Although multiprocessing subprocesses each have their (apportioned) pipeline, they also share some
data passed to them by the parent process. There are essentially two types of shared data.
read-only shared data
Skim files are read-only and take up a lot of RAM, so we share them across sub-processes, loading
them into shared-memory (multiprocessing.sharedctypes.RawArray) in the parent process and passing
them to the child sub-processes when they are launched/forked. (unlike ordinary python data,
sharedctypes are not pickled and reconstituted, but passed through to the subprocess by address
when launch/forked multiprocessing.Process. Since they are read-only, no Locks are required to
access their data safely. The receiving process needs to know to wrap them using numpy.frombuffer
but they can thereafter be treated as ordinary numpy arrays.
read-write shared memory
There are a few circumstances in which the assumption of row independence breaks down.
This happens if the model must respect some aggregated resource or constraint such as school
enrollments or parking availability. In these cases, the individual choice models have to be
influenced or constrained in light of aggregate choices.
Currently school and workplace location choice are the only such aggregate constraints.
The details of these are handled by the shadow_pricing module (q.v.), and our only concern here
is the need to provide shared read-write data buffers for communication between processes.
It is worth noting here that the shared buffers are instances of multiprocessing.Array which
incorporates a multiprocessing.Lock object to mediate access of the underlying data. You might
think that the existence of such a lock would make shared access pretty straightforward, but
this is not the case as the level of locking is very low, reportedly not very performant, and
essentially useless in any event since we want to use numpy.frombuffer to wrap and handle them
as numpy arrays. The Lock is a convenient bundled locking primative, but shadow_pricing rolls
its own semaphore system using the Lock.
FIXME - The code below knows that it need to allocate skim and shadow price buffers by calling
the appropriate methods in abm.tables.skims and abm.tables.shadow_pricing to allocate shared
buffers. This is not very extensible and should be generalized.
"""
# FIXME - pathological knowledge of abm.tables.skims and abm.tables.shadow_pricing (see note above)
def log(state: workflow.State, msg, level, write_to_log_file=True):
process_name = multiprocessing.current_process().name
if not write_to_log_file:
print(f"############ mp_tasks - {process_name} - {msg}")
if write_to_log_file:
with state.filesystem.open_log_file("mp_tasks_log.txt", "a") as log_file:
print(f"mp_tasks - {process_name} - {msg}", file=log_file)
if write_to_log_file:
# logger.log(level, f"mp_tasks - {process_name} - {msg}")
logger.log(level, msg)
def debug(state: workflow.State, msg, write_to_log_file=True):
log(state, msg, level=logging.DEBUG, write_to_log_file=write_to_log_file)
def info(state: workflow.State, msg, write_to_log_file=True):
log(state, msg, level=logging.INFO, write_to_log_file=write_to_log_file)
def warning(state: workflow.State, msg, write_to_log_file=True):
log(state, msg, level=logging.WARNING, write_to_log_file=write_to_log_file)
def error(state: workflow.State, msg, write_to_log_file=True):
log(state, msg, level=logging.ERROR, write_to_log_file=write_to_log_file)
def exception(state: workflow.State, msg, write_to_log_file=True):
process_name = multiprocessing.current_process().name
if not write_to_log_file:
print(f"mp_tasks - {process_name} - {msg}")
print(f"---\n{traceback.format_exc()}---")
with state.filesystem.open_log_file("mp_tasks_log.txt", "a") as log_file:
print(f"---\nmp_tasks - {process_name} - {msg}", file=log_file)
traceback.print_exc(limit=10, file=log_file)
print("---", file=log_file)
if write_to_log_file:
logger.log(logging.ERROR, f"mp_tasks - {process_name} - {msg}")
logger.log(logging.ERROR, f"\n---\n{traceback.format_exc()}---\n")
"""
### child process methods (called within sub process)
"""
def pipeline_table_keys(pipeline_store):
"""
return dict of current (as of last checkpoint) pipeline tables
and their checkpoint-specific hdf5_keys
This facilitates reading pipeline tables directly from a 'raw' open pandas.HDFStore without
opening it as a pipeline (e.g. when apportioning and coalescing pipelines)
We currently only ever need to do this from the last checkpoint, so the ability to specify
checkpoint_name is not required, and thus omitted.
Parameters
----------
pipeline_store : open hdf5 pipeline_store
Returns
-------
checkpoint_name : name of the checkpoint
checkpoint_tables : dict {<table_name>: <table_key>}
"""
checkpoints = pipeline_store[CHECKPOINT_TABLE_NAME]
# last checkpoint row as series
checkpoint = checkpoints.iloc[-1]
checkpoint_name = checkpoint.loc[CHECKPOINT_NAME]
# series with table name as index and checkpoint_name as value
checkpoint_tables = checkpoint[~checkpoint.index.isin(NON_TABLE_COLUMNS)]
# omit dropped tables with empty checkpoint name
checkpoint_tables = checkpoint_tables[checkpoint_tables != ""]
# hdf5 key is <table_name>/<checkpoint_name>
checkpoint_tables = {
table_name: workflow.State.pipeline_table_key(None, table_name, checkpoint_name)
for table_name, checkpoint_name in checkpoint_tables.items()
}
# checkpoint name and series mapping table name to hdf5 key for tables in that checkpoint
return checkpoint_name, checkpoint_tables
def parquet_pipeline_table_keys(pipeline_path: Path):
"""
return dict of current (as of last checkpoint) pipeline tables
and their checkpoint-specific hdf5_keys
This facilitates reading pipeline tables directly from a 'raw' open pandas.HDFStore without
opening it as a pipeline (e.g. when apportioning and coalescing pipelines)
We currently only ever need to do this from the last checkpoint, so the ability to specify
checkpoint_name is not required, and thus omitted.
Returns
-------
checkpoint_name : name of the checkpoint
checkpoint_tables : dict {<table_name>: <table_path>}
"""
checkpoints = ParquetStore(pipeline_path).get_dataframe(CHECKPOINT_TABLE_NAME)
# pd.read_parquet(
# pipeline_path.joinpath(CHECKPOINT_TABLE_NAME, "None.parquet")
# )
# last checkpoint row as series
checkpoint = checkpoints.iloc[-1]
checkpoint_name = checkpoint.loc[CHECKPOINT_NAME]
# series with table name as index and checkpoint_name as value
checkpoint_tables = checkpoint[~checkpoint.index.isin(NON_TABLE_COLUMNS)]
# omit dropped tables with empty checkpoint name
checkpoint_tables = checkpoint_tables[checkpoint_tables != ""]
# hdf5 key is <table_name>/<checkpoint_name>
checkpoint_tables = {
table_name: ParquetStore(pipeline_path)
._store_table_path(table_name, checkpoint_name)
.relative_to(ParquetStore(pipeline_path)._directory)
for table_name, checkpoint_name in checkpoint_tables.items()
}
# checkpoint name and series mapping table name to path for tables in that checkpoint
return checkpoint_name, checkpoint_tables
def build_slice_rules(state: workflow.State, slice_info, pipeline_tables):
"""
based on slice_info for current step from run_list, generate a recipe for slicing
the tables in the pipeline (passed in tables parameter)
slice_info is a dict with two well-known keys:
'tables': required list of table names (order matters!)
'except': optional list of tables not to slice even if they have a sliceable index name
Note: tables listed in slice_info must appear in same order and before any others in tables dict
The index of the first table in the 'tables' list is the primary_slicer.
Any other tables listed are dependent tables with either ref_cols to the primary_slicer
or with the same index (i.e. having an index with the same name). This cascades, so any
tables dependent on the primary_table can in turn have dependent tables that will be sliced
by index or ref_col.
For instance, if the primary_slicer is households, then persons can be sliced because it
has a ref_col to (column with the same same name as) the household table index. And the
tours table can be sliced since it has a ref_col to persons. Tables can also be sliced
by index. For instance the person_windows table can be sliced because it has an index with
the same names as the persons table.
slice_info from multiprocess_steps
::
slice:
tables:
- households
- persons
tables from pipeline
+-----------------+--------------+---------------+
| Table Name | Index | ref_col |
+=================+==============+===============+
| households | household_id | |
+-----------------+--------------+---------------+
| persons | person_id | household_id |
+-----------------+--------------+---------------+
| person_windows | person_id | |
+-----------------+--------------+---------------+
| accessibility | zone_id | |
+-----------------+--------------+---------------+
generated slice_rules dict
::
households:
slice_by: primary <- primary table is sliced in num_processors-sized strides
persons:
source: households
slice_by: column
column: household_id <- slice by ref_col (foreign key) to households
person_windows:
source: persons
slice_by: index <- slice by index of persons table
accessibility:
slice_by: <- mirrored (non-dependent) tables don't get sliced
land_use:
slice_by:
Parameters
----------
slice_info : dict
'slice' info from run_list for this step
pipeline_tables : dict {<table_name>, <pandas.DataFrame>}
dict of all tables from the pipeline keyed by table name
Returns
-------
slice_rules : dict
"""
slicer_table_names = slice_info["tables"]
slicer_table_exceptions = slice_info.get("exclude", slice_info.get("except", []))
if slicer_table_exceptions is None:
slicer_table_exceptions = []
primary_slicer = slicer_table_names[0]
# - ensure that tables listed in slice_info appear in correct order and before any others
tables = OrderedDict([(table_name, None) for table_name in slicer_table_names])
for table_name in pipeline_tables.keys():
tables[table_name] = pipeline_tables[table_name]
if primary_slicer not in tables:
raise RuntimeError("primary slice table '%s' not in pipeline" % primary_slicer)
# allow wildcard 'True' to avoid slicing (or coalescing) any tables no explicitly listed in slice_info.tables
# populationsim uses slice.except wildcards to avoid listing control tables (etc) that should not be sliced,
# followed by a slice.coalesce directive to explicitly list the omnibus tables created by the subprocesses.
# So don't change this behavior withoyt testing populationsim multiprocess!
if slicer_table_exceptions is True:
debug(
state,
f"slice.except wildcard (True): excluding all tables not explicitly listed in slice.tables",
)
slicer_table_exceptions = [t for t in tables if t not in slicer_table_names]
# dict mapping slicer table_name to index name
# (also presumed to be name of ref col name in referencing table)
slicer_ref_cols = OrderedDict()
if slicer_table_exceptions == "*":
slicer_table_exceptions = [t for t in tables if t not in slicer_table_names]
# build slice rules for loaded tables
slice_rules = OrderedDict()
for table_name, df in tables.items():
rule = {}
if table_name == primary_slicer:
# slice primary apportion table
rule = {"slice_by": "primary"}
elif table_name in slicer_table_exceptions:
rule["slice_by"] = None
else:
for slicer_table_name in slicer_ref_cols:
if df.index.name is not None and (
df.index.name == tables[slicer_table_name].index.name
):
# slice df with same index name as a known slicer
rule = {"slice_by": "index", "source": slicer_table_name}
else:
# if df has a column with same name as the ref_col (index) of a slicer?
try:
source, ref_col = next(
(t, c)
for t, c in slicer_ref_cols.items()
if c in df.columns
)
# then we can use that table to slice this df
rule = {
"slice_by": "column",
"column": ref_col,
"source": source,
}
except StopIteration:
rule["slice_by"] = None
if rule["slice_by"]:
# cascade sliceability
slicer_ref_cols[table_name] = df.index.name
slice_rules[table_name] = rule
for table_name, rule in slice_rules.items():
if rule["slice_by"] is not None:
debug(
state,
f"### table_name: {table_name} slice_rules: {slice_rules[table_name]}",
)
debug(state, f"### slicer_ref_cols: {slicer_ref_cols}")
return slice_rules
def apportion_pipeline(state: workflow.State, sub_proc_names, step_info):
"""
apportion pipeline for multiprocessing step
create pipeline files for sub_procs, apportioning data based on slice_rules
Called at the beginning of a multiprocess step prior to launching the sub-processes
Pipeline files have well known names (pipeline file name prefixed by subjob name)
Parameters
----------
sub_proc_names : list[str]
names of the sub processes to apportion
step_info : dict
step_info from multiprocess_steps for step we are apportioning pipeline tables for
Returns
-------
creates apportioned pipeline files for each sub job
"""
slice_info = step_info.get("slice", None)
if slice_info is None:
raise RuntimeError("missing slice_info.slice")
multiprocess_step_name = step_info.get("name", None)
pipeline_file_name = state.get_injectable("pipeline_file_name")
# ensure that if we are resuming, we don't apportion any tables from future model steps
last_checkpoint_in_previous_multiprocess_step = step_info.get(
"last_checkpoint_in_previous_multiprocess_step", None
)
if last_checkpoint_in_previous_multiprocess_step is None:
raise RuntimeError("missing last_checkpoint_in_previous_multiprocess_step")
state.checkpoint.restore(resume_after=last_checkpoint_in_previous_multiprocess_step)
# ensure all tables are in the pipeline
checkpointed_tables = state.checkpoint.list_tables()
for table_name in slice_info["tables"]:
if table_name not in checkpointed_tables:
raise RuntimeError(f"slicer table {table_name} not found in pipeline")
checkpoints_df = state.checkpoint.get_inventory()
# for the subprocess pipelines, keep only the last row of checkpoints and patch the last checkpoint name
checkpoints_df = checkpoints_df.tail(1).copy()
# load all tables from pipeline
checkpoint_name = multiprocess_step_name
tables = {}
for table_name in checkpointed_tables:
# patch last checkpoint name for all tables
checkpoints_df[table_name] = checkpoint_name
# load the dataframe
tables[table_name] = state.checkpoint.load_dataframe(table_name)
debug(state, f"loaded table {table_name} {tables[table_name].shape}")
state.checkpoint.close_store()
# should only be one checkpoint (named <multiprocess_step_name>)
assert len(checkpoints_df) == 1
# - build slice rules for loaded tables
slice_rules = build_slice_rules(state, slice_info, tables)
# - allocate sliced tables for each sub_proc
num_sub_procs = len(sub_proc_names)
for i in range(num_sub_procs):
# use well-known pipeline file name
process_name = sub_proc_names[i]
pipeline_path = state.get_output_file_path(
pipeline_file_name, prefix=process_name
)
if state.settings.checkpoint_format == "hdf":
# remove existing file
try:
os.unlink(pipeline_path)
except OSError:
pass
with pd.HDFStore(str(pipeline_path), mode="a") as pipeline_store:
# remember sliced_tables so we can cascade slicing to other tables
sliced_tables = {}
# - for each table in pipeline
for table_name, rule in slice_rules.items():
df = tables[table_name]
if rule["slice_by"] is not None and num_sub_procs > len(df):
# almost certainly a configuration error
raise RuntimeError(
f"apportion_pipeline: multiprocess step {multiprocess_step_name} "
f"slice table {table_name} has fewer rows {df.shape} "
f"than num_processes ({num_sub_procs})."
)
if rule["slice_by"] == "primary":
# slice primary apportion table by num_sub_procs strides
# this hopefully yields a more random distribution
# (e.g.) households are ordered by size in input store
# we are assuming that the primary table index is unique
# otherwise we should slice by strides in df.index.unique
# we could easily work around this, but it seems likely this was an error on the user's part
assert not df.index.duplicated().any()
primary_df = df[
np.asanyarray(list(range(df.shape[0]))) % num_sub_procs == i
]
sliced_tables[table_name] = primary_df
elif rule["slice_by"] == "index":
# slice a table with same index name as a known slicer
source_df = sliced_tables[rule["source"]]
sliced_tables[table_name] = df.loc[source_df.index]
elif rule["slice_by"] == "column":
# slice a table with a recognized slicer_column
source_df = sliced_tables[rule["source"]]
sliced_tables[table_name] = df[
df[rule["column"]].isin(source_df.index)
]
elif rule["slice_by"] is None:
# don't slice mirrored tables
sliced_tables[table_name] = df
else:
raise RuntimeError(
"Unrecognized slice rule '%s' for table %s"
% (rule["slice_by"], table_name)
)
# - write table to pipeline
hdf5_key = state.pipeline_table_key(table_name, checkpoint_name)
pipeline_store[hdf5_key] = sliced_tables[table_name]
debug(
state,
f"writing checkpoints ({checkpoints_df.shape}) "
f"to {CHECKPOINT_TABLE_NAME} in {pipeline_path}",
)
pipeline_store[CHECKPOINT_TABLE_NAME] = checkpoints_df
else:
# remove existing parquet files and directories
for pq_file in glob.glob(str(pipeline_path.joinpath("*", "*.parquet"))):
try:
os.unlink(pq_file)
except OSError:
pass
for pq_dir in glob.glob(str(pipeline_path.joinpath("*", "*"))):
try:
os.rmdir(pq_dir)
except OSError:
pass
for pq_dir in glob.glob(str(pipeline_path.joinpath("*"))):
try:
os.rmdir(pq_dir)
except OSError:
pass
# remember sliced_tables so we can cascade slicing to other tables
sliced_tables = {}
# YO pipeline_store
# - for each table in pipeline
for table_name, rule in slice_rules.items():
df = tables[table_name]
if rule["slice_by"] is not None and num_sub_procs > len(df):
# almost certainly a configuration error
raise RuntimeError(
f"apportion_pipeline: multiprocess step {multiprocess_step_name} "
f"slice table {table_name} has fewer rows {df.shape} "
f"than num_processes ({num_sub_procs})."
)
if rule["slice_by"] == "primary":
# slice primary apportion table by num_sub_procs strides
# this hopefully yields a more random distribution
# (e.g.) households are ordered by size in input store
# we are assuming that the primary table index is unique
# otherwise we should slice by strides in df.index.unique
# we could easily work around this, but it seems likely this was an error on the user's part
assert not df.index.duplicated().any()
primary_df = df[
np.asanyarray(list(range(df.shape[0]))) % num_sub_procs == i
]
sliced_tables[table_name] = primary_df
elif rule["slice_by"] == "index":
# slice a table with same index name as a known slicer
source_df = sliced_tables[rule["source"]]
sliced_tables[table_name] = df.loc[source_df.index]
elif rule["slice_by"] == "column":
# slice a table with a recognized slicer_column
source_df = sliced_tables[rule["source"]]
sliced_tables[table_name] = df[
df[rule["column"]].isin(source_df.index)
]
elif rule["slice_by"] is None:
# don't slice mirrored tables
sliced_tables[table_name] = df
else:
raise RuntimeError(
"Unrecognized slice rule '%s' for table %s"
% (rule["slice_by"], table_name)
)
# - write table to pipeline
pipeline_path.joinpath(table_name).mkdir(parents=True, exist_ok=True)
ParquetStore(pipeline_path).put(
table_name=table_name,
df=sliced_tables[table_name],
checkpoint_name=checkpoint_name,
)
#
# sliced_tables[table_name].to_parquet(
# pipeline_path.joinpath(table_name, f"{checkpoint_name}.parquet")
# )
debug(
state,
f"writing checkpoints ({checkpoints_df.shape}) "
f"to {CHECKPOINT_TABLE_NAME} in {pipeline_path}",
)
pipeline_path.joinpath(CHECKPOINT_TABLE_NAME).mkdir(
parents=True, exist_ok=True
)
ParquetStore(pipeline_path).put(
table_name=CHECKPOINT_TABLE_NAME,
df=checkpoints_df,
checkpoint_name=None,
)
# checkpoints_df.to_parquet(
# pipeline_path.joinpath(CHECKPOINT_TABLE_NAME, f"None.parquet")
# )
def coalesce_pipelines(state: workflow.State, sub_proc_names, slice_info):
"""
Coalesce the data in the sub_processes apportioned pipelines back into a single pipeline
We use slice_rules to distinguish sliced (apportioned) tables from mirrored tables.
Sliced tables are concatenated to create a single omnibus table with data from all sub_procs
but mirrored tables are the same across all sub_procs, so we can grab a copy from any pipeline.
Parameters
----------
sub_proc_names : list[str]
slice_info : dict
slice_info from multiprocess_steps
Returns
-------
creates an omnibus pipeline with coalesced data from individual sub_proc pipelines
"""
pipeline_file_name = state.get_injectable("pipeline_file_name")
debug(state, f"coalesce_pipelines to: {pipeline_file_name}")
# - read all tables from first process pipeline
# FIXME - note: assumes any new tables will be present in ALL subprocess pipelines
tables = {}
pipeline_path = state.get_output_file_path(
pipeline_file_name, prefix=sub_proc_names[0]
)
if state.settings.checkpoint_format == "hdf":
with pd.HDFStore(str(pipeline_path), mode="r") as pipeline_store:
# hdf5_keys is a dict mapping table_name to pipeline hdf5_key
checkpoint_name, hdf5_keys = pipeline_table_keys(pipeline_store)
for table_name, hdf5_key in hdf5_keys.items():
debug(state, f"loading table {table_name} {hdf5_key}")
tables[table_name] = pipeline_store[hdf5_key]
else:
checkpoint_name, hdf5_keys = parquet_pipeline_table_keys(pipeline_path)
pqstore = ParquetStore(pipeline_path, mode="r")
for table_name, parquet_path in hdf5_keys.items():
debug(state, f"loading table {table_name} from {pqstore.filename}")
tables[table_name] = pqstore.get_dataframe(table_name)
# slice.coalesce is an override list of omnibus tables created by subprocesses that should be coalesced,
# whether or not they satisfy the slice rules. Ordinarily all tables qualify for slicing by the slice rules
# will be coalesced, including any new tables created by the subprocess that have sliceable indexes or ref_cols.
# Any other new tables that don't match the slice rules will be considered mirrored. This is usually the desired
# behavior, especially in activitysim abm models. However, if the "slice.exclude: True" wildcard is used, it
# prevents the inference for newly generated tables, and this directive permits explicit specification of
# which new tables to coalesce. Populationsim uses this wildcard except directives to avoid having to list
# many slice exceptions, and just lists weigh tables to coalesce. So don't change this behavior without testing
# populationsim multiprocessing!
coalesce_tables = slice_info.get("coalesce", [])
# report absence of any slice_info.coalesce tables not in pipeline
# we don't require their presence in case there are tracing tables that will only be present if tracing is enabled
for table_name in coalesce_tables:
if table_name not in tables:
logger.warning(
"slicer coalesce.table %s not found in pipeline" % table_name
)
# - use slice rules followed by apportion_pipeline to identify mirrored tables
# (tables that are identical in every pipeline and so don't need to be concatenated)
slice_rules = build_slice_rules(state, slice_info, tables)
# table is mirrored if no slice rule or explicitly listed in slice_info.coalesce setting
mirrored_table_names = [
t
for t, rule in slice_rules.items()
if rule["slice_by"] is None and t not in coalesce_tables
]
mirrored_tables = {t: tables[t] for t in mirrored_table_names}
omnibus_keys = {t: k for t, k in hdf5_keys.items() if t not in mirrored_table_names}
debug(state, f"coalesce_pipelines to: {pipeline_file_name}")
debug(state, f"mirrored_table_names: {mirrored_table_names}")
debug(state, f"omnibus_keys: {omnibus_keys}")
# assemble lists of omnibus tables from all sub_processes
omnibus_tables = {table_name: [] for table_name in omnibus_keys}
for process_name in sub_proc_names:
pipeline_path = state.get_output_file_path(
pipeline_file_name, prefix=process_name
)
logger.info(f"coalesce pipeline {pipeline_path}")
if state.settings.checkpoint_format == "hdf":
with pd.HDFStore(str(pipeline_path), mode="r") as pipeline_store:
for table_name, hdf5_key in omnibus_keys.items():
omnibus_tables[table_name].append(pipeline_store[hdf5_key])
else:
pqstore = ParquetStore(pipeline_path, mode="r")
for table_name, hdf5_key in omnibus_keys.items():
omnibus_tables[table_name].append(pqstore.get_dataframe(table_name))
# open pipeline, preserving existing checkpoints (so resume_after will work for prior steps)
state.checkpoint.restore(resume_after="_")
# - add mirrored tables to pipeline
for table_name in mirrored_tables:
df = mirrored_tables[table_name]
info(state, f"adding mirrored table {table_name} {df.shape}")
state.add_table(table_name, df)
# - concatenate omnibus tables and add them to pipeline
for table_name in omnibus_tables:
df = pd.concat(omnibus_tables[table_name], sort=False)
info(state, f"adding omnibus table {table_name} {df.shape}")
state.add_table(table_name, df)
state.checkpoint.add(checkpoint_name)
state.checkpoint.close_store()
def setup_injectables_and_logging(injectables, locutor: bool = True) -> workflow.State:
"""
Setup injectables (passed by parent process) within sub process
we sometimes want only one of the sub-processes to perform an action (e.g. write shadow prices)
the locutor flag indicates that this sub process is the designated singleton spokesperson
Parameters
----------
injectables : dict {<injectable_name>: <value>}
dict of injectables passed by parent process
locutor : bool
is this sub process the designated spokesperson
Returns
-------
injects injectables
"""
state = workflow.State()
state = state.initialize_filesystem(**injectables)
state.settings = injectables.get("settings", Settings())
# register abm steps and other abm-specific injectables
# by default, assume we are running activitysim.abm
# other callers (e.g. piopulationsim) will have to arrange to register their own steps and injectables
# (presumably) in a custom run_simulation.py instead of using the 'activitysim run' command
if not "preload_injectables" in state:
# register abm steps and other abm-specific injectables
from activitysim import abm # noqa: F401
try:
for k, v in injectables.items():
state.add_injectable(k, v)
# re-import extension modules to register injectables
ext = state.get_injectable("imported_extensions", default=())
for e in ext:
basepath, extpath = os.path.split(e)
if not basepath:
basepath = "."
sys.path.insert(0, basepath)
try:
importlib.import_module(e)
except ImportError as err:
logger.exception("ImportError")
raise
finally:
del sys.path[0]
state.add_injectable("is_sub_task", True)
state.add_injectable("locutor", locutor)
config.filter_warnings(state)
process_name = multiprocessing.current_process().name
state.add_injectable("log_file_prefix", process_name)
except Exception as e:
exception(
state,
f"{type(e).__name__} exception while setting up injectables: {str(e)}",
write_to_log_file=False,
)
raise e
try:
state.logging.config_logger()
except Exception as e:
exception(
state, f"{type(e).__name__} exception while configuring logger: {str(e)}"
)
raise e
return state
def adjust_chunk_size_for_shared_memory(chunk_size, data_buffers, num_processes):
# even if there is only one subprocess,
# we are separate from parent who allocated the shared memory
# so we still need to compensate for it
if chunk_size == 0:
return chunk_size
shared_memory_size = mem.shared_memory_size(data_buffers)
if shared_memory_size == 0:
return chunk_size
fair_share_of_shared_memory = int(shared_memory_size / num_processes)
adjusted_chunk_size = chunk_size - fair_share_of_shared_memory
logger.info(
f"adjust_chunk_size_for_shared_memory "
f"adjusted_chunk_size {util.INT(adjusted_chunk_size)} "
f"chunk_size {util.INT(chunk_size)} "
f"shared_memory_size {util.INT(shared_memory_size)} "
f"num_processes {num_processes} "
f"fair_share_of_shared_memory {util.INT(fair_share_of_shared_memory)} "
)
if adjusted_chunk_size <= 0:
raise RuntimeError(
f"adjust_chunk_size_for_shared_memory: chunk_size too small for shared memory. "
f"adjusted_chunk_size: {adjusted_chunk_size}"
)
return adjusted_chunk_size
def run_simulation(
state: workflow.State, queue, step_info, resume_after, shared_data_buffer
):
"""
run step models as subtask
called once to run each individual sub process in multiprocess step
Unless actually resuming resuming, resume_after will be None for first step,
and then FINAL for subsequent steps so pipelines opened to resume where previous step left off
Parameters
----------
queue : multiprocessing.Queue
step_info : dict
step_info for current step from multiprocess_steps
resume_after : str or None
shared_data_buffer : dict
dict of shared data (e.g. skims and shadow_pricing)
"""