Skip to content

Commit 8e4f3ee

Browse files
committed
Fix flake8 lint issues
1 parent c0b8979 commit 8e4f3ee

File tree

9 files changed

+58
-49
lines changed

9 files changed

+58
-49
lines changed

pkg/metricscollector/v1beta1/common/pns.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,8 @@ def WaitPIDs(pids, main_pid, pool_interval, timout, wait_all, completed_marked_d
109109
contents = file_obj.read()
110110
if contents.strip() != const.TRAINING_COMPLETED:
111111
raise Exception(
112-
"Unable to find marker: {} in file: {} with contents: {} for pid: {}".format(
112+
"Unable to find marker: {} in file: {} with contents: {} "
113+
"for pid: {}".format(
113114
const.TRAINING_COMPLETED,
114115
mark_file,
115116
contents,

pkg/metricscollector/v1beta1/tfevent-metricscollector/tfevent_loader.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
# limitations under the License.
1414

1515
# TFEventFileParser parses tfevent files and returns an ObservationLog of the metrics specified.
16-
# When the event file is under a directory(e.g. test dir), please specify "{{dirname}}/{{metrics name}}"
16+
# When the event file is under a directory(e.g. test dir), please specify
17+
# "{{dirname}}/{{metrics name}}"
1718
# For example, in the Tensorflow MNIST Classification With Summaries:
1819
# https://github.com/kubeflow/katib/blob/master/examples/v1beta1/trial-images/tf-mnist-with-summaries/mnist.py.
1920
# The "accuracy" and "loss" metric is saved under "train" and "test" directories.
@@ -28,10 +29,7 @@
2829
import api_pb2
2930
import rfc3339
3031
import tensorflow as tf
31-
from tensorboard.backend.event_processing.event_accumulator import (
32-
EventAccumulator,
33-
TensorEvent,
34-
)
32+
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
3533
from tensorboard.backend.event_processing.tag_types import TENSORS
3634

3735
from pkg.metricscollector.v1beta1.common import const
@@ -53,7 +51,6 @@ def parse_summary(self, tfefile):
5351
event_accumulator.Reload()
5452
for tag in event_accumulator.Tags()[TENSORS]:
5553
for m in self.metric_names:
56-
5754
tfefile_parent_dir = (
5855
os.path.dirname(m)
5956
if len(m.split("/")) >= 2

pkg/suggestion/v1beta1/hyperopt/base_service.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ def __init__(
5858
self.is_first_run = True
5959

6060
def create_hyperopt_domain(self):
61-
# Construct search space, example: {"x": hyperopt.hp.uniform('x', -10, 10), "x2": hyperopt.hp.uniform('x2', -10, 10)}
61+
# Construct search space, example: {"x": hyperopt.hp.uniform('x', -10, 10), "x2":
62+
# hyperopt.hp.uniform('x2', -10, 10)}
6263
hyperopt_search_space = {}
6364
for param in self.search_space.params:
6465
if param.type == INTEGER:
@@ -108,7 +109,8 @@ def getSuggestions(self, trials, current_request_number):
108109
new_id = self.fmin.trials.new_trial_ids(1)
109110
hyperopt_trial_new_ids.append(new_id[0])
110111
hyperopt_trial_miscs_idxs = {}
111-
# Example: {'l1_normalization': [0.1], 'learning_rate': [0.1], 'hidden2': [1], 'optimizer': [1]}
112+
# Example: {'l1_normalization': [0.1], 'learning_rate': [0.1],
113+
# 'hidden2': [1], 'optimizer': [1]}
112114
hyperopt_trial_miscs_vals = {}
113115

114116
# Insert Trial assignment to the misc
@@ -147,7 +149,8 @@ def getSuggestions(self, trials, current_request_number):
147149
# TODO: Do we need to analyse additional_metrics?
148150
objective_for_hyperopt = float(trial.target_metric.value)
149151
if self.search_space.goal == MAX_GOAL:
150-
# Now hyperopt only supports fmin and we need to reverse objective value for maximization
152+
# Now hyperopt only supports fmin and we need to reverse
153+
# objective value for maximization
151154
objective_for_hyperopt = -1 * objective_for_hyperopt
152155
hyperopt_trial_result = {
153156
"loss": objective_for_hyperopt,
@@ -156,7 +159,6 @@ def getSuggestions(self, trials, current_request_number):
156159
hyperopt_trial_results.append(hyperopt_trial_result)
157160

158161
if len(trials) > 0:
159-
160162
# Create new Trial doc
161163
hyperopt_trials = hyperopt.Trials().new_trial_docs(
162164
tids=hyperopt_trial_new_ids,
@@ -226,7 +228,7 @@ def getSuggestions(self, trials, current_request_number):
226228
trials=self.fmin.trials,
227229
seed=random_state,
228230
n_startup_jobs=current_request_number,
229-
**self.algorithm_conf
231+
**self.algorithm_conf,
230232
)
231233
self.is_first_run = False
232234
else:
@@ -239,7 +241,7 @@ def getSuggestions(self, trials, current_request_number):
239241
trials=self.fmin.trials,
240242
seed=random_state,
241243
n_startup_jobs=current_request_number,
242-
**self.algorithm_conf
244+
**self.algorithm_conf,
243245
)[0]
244246
)
245247

pkg/suggestion/v1beta1/internal/search_space.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,8 @@ def convert_to_combinations(search_space):
5757
elif parameter.type == DOUBLE:
5858
if parameter.step == "" or parameter.step is None:
5959
raise Exception(
60-
"Param {} step is nil; For discrete search space, all parameters must include step".format(
61-
parameter.name
62-
)
60+
"Param {} step is nil; For discrete search space, all parameters "
61+
"must include step".format(parameter.name)
6362
)
6463
double_list = np.arange(
6564
float(parameter.min),

pkg/suggestion/v1beta1/internal/trial.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,11 +80,14 @@ def __str__(self):
8080
", ".join([str(e) for e in self.assignments])
8181
)
8282
else:
83-
return "Trial(assignment: {}, metric_name: {}, metric: {}, additional_metrics: {})".format(
84-
", ".join([str(e) for e in self.assignments]),
85-
self.metric_name,
86-
self.target_metric,
87-
", ".join(str(e) for e in self.additional_metrics),
83+
return (
84+
"Trial(assignment: {}, metric_name: {}, metric: {}, "
85+
"additional_metrics: {})".format(
86+
", ".join(str(e) for e in self.assignments),
87+
self.metric_name,
88+
self.target_metric,
89+
", ".join(str(e) for e in self.additional_metrics),
90+
)
8891
)
8992

9093

pkg/suggestion/v1beta1/nas/common/validation.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,8 @@
1616

1717

1818
def validate_operations(operations: list[api_pb2.Operation]) -> (bool, str):
19-
2019
# Validate each operation
2120
for operation in operations:
22-
2321
# Check OperationType
2422
if not operation.operation_type:
2523
return False, "Missing operationType in Operation:\n{}".format(operation)
@@ -31,7 +29,6 @@ def validate_operations(operations: list[api_pb2.Operation]) -> (bool, str):
3129
# Validate each ParameterConfig in Operation
3230
parameters_list = list(operation.parameter_specs.parameters)
3331
for parameter in parameters_list:
34-
3532
# Check Name
3633
if not parameter.name:
3734
return False, "Missing Name in ParameterConfig:\n{}".format(parameter)
@@ -78,16 +75,16 @@ def validate_operations(operations: list[api_pb2.Operation]) -> (bool, str):
7875
):
7976
return (
8077
False,
81-
"Step parameter should be > 0 in ParameterConfig.feasibleSpace:\n{}".format(
82-
parameter
83-
),
78+
"Step parameter should be > 0 in ParameterConfig.feasibleSpace:\n"
79+
"{}".format(parameter),
8480
)
8581
except Exception as e:
8682
return (
8783
False,
88-
"failed to validate ParameterConfig.feasibleSpace \n{parameter}):\n{exception}".format(
89-
parameter=parameter, exception=e
90-
),
84+
(
85+
"failed to validate ParameterConfig.feasibleSpace \n"
86+
"{parameter}):\n{exception}"
87+
).format(parameter=parameter, exception=e),
9188
)
9289

9390
return True, ""

pkg/suggestion/v1beta1/nas/enas/service.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,10 @@ def ValidateAlgorithmSettings(self, request, context):
237237
):
238238
return self.set_validate_context_error(
239239
context,
240-
"Algorithm Setting {}: {} with {} type must be in range ({}, {}]".format(
240+
(
241+
"Algorithm Setting {}: {} with {} type must be in range "
242+
"({}, {})"
243+
).format(
241244
setting.name,
242245
converted_value,
243246
setting_type.__name__,
@@ -309,7 +312,8 @@ def GetSuggestions(self, request, context):
309312

310313
if self.is_first_run:
311314
self.logger.info(
312-
">>> First time running suggestion for {}. Random architecture will be given.".format(
315+
">>> First time running suggestion for {}. "
316+
"Random architecture will be given.".format(
313317
experiment.experiment_name
314318
)
315319
)
@@ -319,7 +323,8 @@ def GetSuggestions(self, request, context):
319323
for _ in range(experiment.num_trials):
320324
candidates.append(sess.run(controller_ops["sample_arc"]))
321325

322-
# TODO: will use PVC to store the checkpoint to protect against unexpected suggestion pod restart
326+
# TODO: will use PVC to store the checkpoint to protect
327+
# against unexpected suggestion pod restart
323328
saver.save(sess, experiment.ctrl_cache_file)
324329

325330
self.is_first_run = False
@@ -331,17 +336,22 @@ def GetSuggestions(self, request, context):
331336
result = self.GetEvaluationResult(request.trials)
332337

333338
# TODO: (andreyvelich) I deleted this part, should it be handle by controller?
334-
# Sometimes training container may fail and GetEvaluationResult() will return None
339+
# Sometimes training container may fail and GetEvaluationResult()
340+
# will return None
335341
# In this case, the Suggestion will:
336-
# 1. Firstly try to respawn the previous trials after waiting for RESPAWN_SLEEP seconds
337-
# 2. If respawning the trials for RESPAWN_LIMIT times still cannot collect valid results,
338-
# then fail the task because it may indicate that the training container has errors.
342+
# 1. Firstly try to respawn the previous trials after waiting for
343+
# RESPAWN_SLEEP seconds
344+
# 2. If respawning the trials for RESPAWN_LIMIT times still cannot
345+
# collect valid results,
346+
# then fail the task because it may indicate that the training
347+
# container has errors.
339348
if result is None:
340349
self.logger.warning(
341350
">>> Suggestion has spawned trials, but they all failed."
342351
)
343352
self.logger.warning(
344-
">>> Please check whether the training container is correctly implemented"
353+
">>> Please check whether the training container "
354+
"is correctly implemented"
345355
)
346356
self.logger.info(
347357
">>> Experiment {} failed".format(
@@ -351,7 +361,8 @@ def GetSuggestions(self, request, context):
351361
return []
352362

353363
# This LSTM network is designed to maximize the metrics
354-
# However, if the user wants to minimize the metrics, we can take the negative of the result
364+
# However, if the user wants to minimize the metrics,
365+
# we can take the negative of the result
355366

356367
if experiment.opt_direction == api_pb2.MINIMIZE:
357368
result = -result
@@ -426,9 +437,8 @@ def GetSuggestions(self, request, context):
426437
nn_config_str = str(nn_config_json).replace('"', "'")
427438

428439
self.logger.info(
429-
"\n>>> New Neural Network Architecture Candidate #{} (internal representation):".format(
430-
i
431-
)
440+
"\n>>> New Neural Network Architecture Candidate #{} "
441+
"(internal representation):".format(i)
432442
)
433443
self.logger.info(organized_arc_json)
434444
self.logger.info("\n>>> Corresponding Seach Space Description:")

pkg/suggestion/v1beta1/optuna/service.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,8 @@ def _validate_grid_setting(cls, experiment):
244244
if max_trial_count > num_combinations:
245245
return (
246246
False,
247-
"Max Trial Count: {max_trial} > all possible search combinations: {combinations}".format(
247+
"Max Trial Count: {max_trial} > all possible search combinations: "
248+
"{combinations}".format(
248249
max_trial=max_trial_count, combinations=num_combinations
249250
),
250251
)

pkg/suggestion/v1beta1/pbt/service.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
HyperParameter,
2828
HyperParameterSearchSpace,
2929
)
30-
from pkg.suggestion.v1beta1.internal.trial import Assignment, Trial
30+
from pkg.suggestion.v1beta1.internal.trial import Assignment
3131

3232
logger = logging.getLogger(__name__)
3333

@@ -70,7 +70,8 @@ def ValidateAlgorithmSettings(self, request, context):
7070
):
7171
return self._set_validate_context_error(
7272
context,
73-
"Param(resample_probability) should be null to perturb at 0.8 or 1.2, or be between 0 and 1, inclusive, to resample",
73+
"Param(resample_probability) should be null to perturb at 0.8 or 1.2, "
74+
"or be between 0 and 1, inclusive, to resample",
7475
)
7576

7677
return api_pb2.ValidateAlgorithmSettingsReply()
@@ -98,7 +99,7 @@ def GetSuggestions(self, request, context):
9899
float(settings["truncation_threshold"]),
99100
(
100101
None
101-
if not "resample_probability" in settings
102+
if "resample_probability" not in settings
102103
else float(settings["resample_probability"])
103104
),
104105
search_space,
@@ -184,7 +185,7 @@ def get(self):
184185
labels = {
185186
"pbt.suggestion.katib.kubeflow.org/generation": self.generation,
186187
}
187-
if not self.parent is None:
188+
if self.parent is not None:
188189
labels["pbt.suggestion.katib.kubeflow.org/parent"] = self.parent
189190
return assignments, labels, self.uid
190191

@@ -284,9 +285,7 @@ def get(self):
284285
return obj.get()
285286

286287
def update(self, trial):
287-
trial_labels = trial.spec.labels
288288
uid = trial.name
289-
generation = trial_labels["pbt.suggestion.katib.kubeflow.org/generation"]
290289

291290
# Do not update active/pending trials
292291
if trial.status.condition in (

0 commit comments

Comments
 (0)