-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_evolution_parallel.py
197 lines (170 loc) · 4.94 KB
/
test_evolution_parallel.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
# TODO: this test file is not up to date
# but not needed, as run_evolution.py works
from evolution import *
from functools import partial
from time import time
# import matplotlib.pyplot as plt
# from datetime import datetime
from deap import base
from deap import creator
from deap import tools
from deap import algorithms
from deap import cma
from dask import delayed, compute
import dask.multiprocessing
import dask.bag as db
import argparse
parser = argparse.ArgumentParser(
description = 'testing parallelisation of EA'
)
parallel_group = parser.add_mutually_exclusive_group()
parallel_group.add_argument(
'--pm',
action='store_true',
help='whether to use custom parallel map function. ' +\
'Seems faster than --pr'
)
parallel_group.add_argument(
'--db',
action='store_true',
help='whether to use dask.bag.map'
)
parallel_group.add_argument(
'--pr',
action='store_true',
help='whether to use parallel restarts'
)
parser.add_argument(
'-n', '--n_gen',
type=int, default=100,
help='number of generations to run the EA'
)
parser.add_argument(
'-r', '--n_runs',
type=int, default=10,
help='number of runs of the trial'
)
parser.add_argument(
'-m', '--n_multiples',
type=int, default=10,
help='number of repeats of the trial'
)
parser.add_argument(
'--sigma',
type=float, default=0.0005,
help='initial sigma for the EA'
)
parser.add_argument(
'-v', '--verbose',
action='store_true',
help='whether to print progress'
)
parser.add_argument(
'--scheduler',
type=str, default='processes',
help="Scheduler for dask. " +\
"Options are ['threads', 'processes', 'synchronous']"
)
args = parser.parse_args()
assert args.scheduler in ['threads', 'processes', 'synchronous']
dask.config.set(scheduler=args.scheduler)
def map_dask(f, *iters):
"""
Following the solution here:
https://stackoverflow.com/questions/42051318/programming-deap-with-scoop
Use with `toolbox.register("map", map_dask)`
"""
f_delayed = delayed(f)
return compute(*[f_delayed(*args) for args in zip(*iters)])
def map_dask_bag(f, seq):
return db.from_sequence(seq).map(f).compute()
def get_fitness_dask(
W_initial, plasticity_params,
trial_func,
n_runs,
n_multiples,
verbose=False
):
fitness = 0.0
# very crude parallelisation
run_repeated_trial_delayed = delayed(run_repeated_trial)
computations = [run_repeated_trial_delayed(
W_initial=W_initial,
plasticity_params=plasticity_params,
trial_func=trial_func,
n_runs=n_runs,
verbose=verbose)
for i in range(n_multiples)]
results_dicts = compute(computations)[0]
for results_dict in results_dicts:
for rew_array in results_dict['reward']:
if not np.any(np.isnan(rew_array)):
fitness += np.sum(rew_array)
return fitness
#### THIS DEFINES THE EA TO RUN IN PARALLEL ####
trial_func = partial(
run_trial_coherence_2afc,
total_time=runtime,
coherence=0.068,
use_phi_fitted=True
)
W_initial = get_weights()
if args.pr:
def fitness_EA(genome):
plasticity_params = get_params_from_genome(
np.array(genome)
)
return get_fitness_dask(
W_initial=W_initial,
plasticity_params=plasticity_params,
n_runs=args.n_runs,
n_multiples=args.n_multiples,
trial_func=trial_func
),
else:
def fitness_EA(genome):
plasticity_params = get_params_from_genome(
np.array(genome)
)
return get_fitness(
W_initial=W_initial,
plasticity_params=plasticity_params,
n_runs=args.n_runs,
n_multiples=args.n_multiples,
trial_func=trial_func
),
###############################################
creator.create("FitnessMax", base.Fitness, weights=(1.,))
creator.create("Individual", list, fitness=creator.FitnessMax)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", np.mean)
stats.register("std", np.std)
stats.register("min", np.min)
stats.register("max", np.max)
strategy = cma.Strategy(
centroid=nolearn_genome,
sigma=args.sigma
)
hof = tools.HallOfFame(10)
toolbox = base.Toolbox()
toolbox.register("evaluate", fitness_EA)
toolbox.register("generate", strategy.generate, creator.Individual)
toolbox.register("update", strategy.update)
if args.pm:
toolbox.register("map", map_dask)
elif args.db:
toolbox.register("map", map_dask_bag)
if __name__ == '__main__':
start = time()
pop, logbook = algorithms.eaGenerateUpdate(
toolbox,
ngen=args.n_gen,
stats=stats,
halloffame=hof,
verbose=args.verbose
)
end = time()
# print(logbook)
print("\nEvolutionary algorithm complete with args:")
print(*map(lambda x: f"{x[0]}:{x[1]}", vars(args).items()))
print(f"Total time taken: {end-start:.2f}s")