Skip to content

Commit a81765a

Browse files
formatted with black
1 parent c39b87e commit a81765a

File tree

2 files changed

+50
-25
lines changed

2 files changed

+50
-25
lines changed

kernel_tuner/strategies/diff_evo.py

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""A simple Different Evolution for parameter search."""
2+
23
import re
34
import numpy as np
45

@@ -12,10 +13,23 @@
1213
maxiter=("maximum number of generations", 200),
1314
F=("mutation factor (differential weight)", 0.8),
1415
CR=("crossover rate", 0.9),
15-
method=("method", "best1bin")
16+
method=("method", "best1bin"),
1617
)
1718

18-
supported_methods = ["best1bin", "rand1bin", "best2bin", "rand2bin", "best1exp", "rand1exp", "best2exp", "rand2exp", "currenttobest1bin", "currenttobest1exp", "randtobest1bin", "randtobest1exp"]
19+
supported_methods = [
20+
"best1bin",
21+
"rand1bin",
22+
"best2bin",
23+
"rand2bin",
24+
"best1exp",
25+
"rand1exp",
26+
"best2exp",
27+
"rand2exp",
28+
"currenttobest1bin",
29+
"currenttobest1exp",
30+
"randtobest1bin",
31+
"randtobest1exp",
32+
]
1933

2034

2135
def tune(searchspace: Searchspace, runner, tuning_options):
@@ -59,7 +73,7 @@ def indices_to_values(individual_indices, tune_params):
5973

6074

6175
def parse_method(method):
62-
""" Helper func to parse the preferred method into its components. """
76+
"""Helper func to parse the preferred method into its components."""
6377
pattern = r"^(best|rand|currenttobest|randtobest)(1|2)(bin|exp)$"
6478
match = re.fullmatch(pattern, method)
6579

@@ -76,7 +90,7 @@ def random_draw(idxs, mutation, best):
7690
Draw without replacement unless there is not enough to draw from.
7791
"""
7892
draw = 2 * mutation + 1 - int(best)
79-
return np.random.choice(idxs, draw, replace=draw>=len(idxs))
93+
return np.random.choice(idxs, draw, replace=draw >= len(idxs))
8094

8195

8296
def differential_evolution(searchspace, cost_func, bounds, popsize, maxiter, F, CR, method, verbose):
@@ -104,15 +118,12 @@ def differential_evolution(searchspace, cost_func, bounds, popsize, maxiter, F,
104118
"""
105119
tune_params = cost_func.tuning_options.tune_params
106120
min_idx = np.zeros(len(tune_params))
107-
max_idx = [len(v)-1 for v in tune_params.values()]
121+
max_idx = [len(v) - 1 for v in tune_params.values()]
108122

109123
best, mutation, mutation_method, crossover_method = parse_method(method)
110124

111125
# --- 1. Initialization ---
112126

113-
# Get the number of dimensions from the bounds list
114-
dimensions = len(bounds)
115-
116127
# Convert bounds to a numpy array for easier manipulation
117128
bounds = np.array(bounds)
118129

@@ -187,11 +198,11 @@ def differential_evolution(searchspace, cost_func, bounds, popsize, maxiter, F,
187198
if verbose:
188199
print(f"Generation {generation + 1}, Best Cost: {best_cost:.6f}")
189200

190-
return {'solution': best_solution, 'cost': best_cost}
201+
return {"solution": best_solution, "cost": best_cost}
191202

192203

193204
def round_and_clip(mutant_idx_float, min_idx, max_idx):
194-
""" Helper func to round floating index to nearest integer and clip within bounds. """
205+
"""Helper func to round floating index to nearest integer and clip within bounds."""
195206
# Round to the nearest integer
196207
rounded_idx = np.round(mutant_idx_float)
197208

@@ -277,7 +288,7 @@ def mutate_de_2(best_idx, randos_idx, F, min_idx, max_idx, best):
277288

278289

279290
def binomial_crossover(donor_vector, target, CR):
280-
""" Performs binomial crossover of donor_vector with target given crossover rate CR. """
291+
"""Performs binomial crossover of donor_vector with target given crossover rate CR."""
281292
# Create the trial vector by mixing parameters from the target and donor vectors
282293
trial_vector = np.copy(target)
283294
dimensions = len(donor_vector)
@@ -320,5 +331,11 @@ def exponential_crossover(donor_vector, target, CR):
320331

321332
return trial_idx
322333

323-
mutation = {"1": mutate_de_1, "2": mutate_de_2, "currenttobest1": mutate_currenttobest1, "randtobest1": mutate_randtobest1}
334+
335+
mutation = {
336+
"1": mutate_de_1,
337+
"2": mutate_de_2,
338+
"currenttobest1": mutate_currenttobest1,
339+
"randtobest1": mutate_randtobest1,
340+
}
324341
crossover = {"bin": binomial_crossover, "exp": exponential_crossover}

test/strategies/test_diff_evo.py

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
11
import numpy as np
22
import pytest
3-
from kernel_tuner.strategies.diff_evo import values_to_indices, indices_to_values, mutate_de_1, mutate_de_2, binomial_crossover, exponential_crossover
3+
from kernel_tuner.strategies.diff_evo import (
4+
values_to_indices,
5+
indices_to_values,
6+
mutate_de_1,
7+
mutate_de_2,
8+
binomial_crossover,
9+
exponential_crossover,
10+
)
411
from kernel_tuner.strategies.diff_evo import supported_methods
512
from kernel_tuner import tune_kernel
613

714
from .test_strategies import vector_add, cache_filename
815

16+
917
def test_values_to_indices():
1018

1119
tune_params = {}
@@ -37,7 +45,7 @@ def test_indices_to_values():
3745

3846
tune_params["block_size_y"] = [16, 32, 128, 1024]
3947
expected = [1024, 32]
40-
result = indices_to_values([3,1], tune_params)
48+
result = indices_to_values([3, 1], tune_params)
4149
assert result[0] == expected[0]
4250
assert result[1] == expected[1]
4351
assert len(result) == len(expected)
@@ -58,7 +66,7 @@ def test_mutate_de_1():
5866
F = 0.8
5967
params_list = list(tune_params)
6068
min_idx = np.zeros(len(tune_params))
61-
max_idx = [len(v)-1 for v in tune_params.values()]
69+
max_idx = [len(v) - 1 for v in tune_params.values()]
6270

6371
mutant = mutate_de_1(a_idx, randos_idx, F, min_idx, max_idx, False)
6472

@@ -94,7 +102,7 @@ def test_mutate_de_2():
94102
F = 0.8
95103
params_list = list(tune_params)
96104
min_idx = np.zeros(len(tune_params))
97-
max_idx = [len(v)-1 for v in tune_params.values()]
105+
max_idx = [len(v) - 1 for v in tune_params.values()]
98106

99107
mutant = mutate_de_2(a_idx, randos_idx, F, min_idx, max_idx, False)
100108

@@ -139,14 +147,14 @@ def test_exponential_crossover():
139147
assert (val == donor_vector[dim]) or (val == target[dim])
140148

141149

142-
@pytest.mark.parametrize('method', supported_methods)
150+
@pytest.mark.parametrize("method", supported_methods)
143151
def test_diff_evo(vector_add, method):
144-
result, _ = tune_kernel(*vector_add,
145-
strategy="diff_evo",
146-
strategy_options=dict(popsize=5, method=method),
147-
verbose=True,
148-
cache=cache_filename,
149-
simulation_mode=True)
152+
result, _ = tune_kernel(
153+
*vector_add,
154+
strategy="diff_evo",
155+
strategy_options=dict(popsize=5, method=method),
156+
verbose=True,
157+
cache=cache_filename,
158+
simulation_mode=True,
159+
)
150160
assert len(result) > 0
151-
152-

0 commit comments

Comments
 (0)