Skip to content

Commit e09c466

Browse files
committed
tools: AutoTuner: Use Ray for parallelism in Vizier optimizations
Signed-off-by: Eryk Szpotanski <eszpotanski@antmicro.com>
1 parent 09663fc commit e09c466

5 files changed

Lines changed: 466 additions & 455 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
"""
2+
AutoTuner module integrating Ray Tune and Vizier framework
3+
for ORFS parameters optimization.
4+
"""

‎tools/AutoTuner/src/autotuner/distributed.py‎

Lines changed: 38 additions & 192 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,8 @@
2828
import json
2929
import os
3030
import sys
31-
from datetime import datetime
32-
from multiprocessing import cpu_count
3331
from itertools import product
3432
from collections import namedtuple
35-
from uuid import uuid4 as uuid
3633

3734
import numpy as np
3835

@@ -49,21 +46,24 @@
4946

5047
from ax.service.ax_client import AxClient
5148

52-
from utils import (
49+
from autotuner.utils import (
5350
add_common_args,
5451
openroad,
52+
consumer,
5553
parse_config,
5654
read_config,
5755
read_metrics,
58-
run_command,
56+
prepare_ray_server,
57+
DATE,
58+
CONSTRAINTS_SDC,
59+
FASTROUTE_TCL,
5960
)
6061

61-
DATE = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
62-
ORFS_URL = "https://github.com/The-OpenROAD-Project/OpenROAD-flow-scripts"
63-
FASTROUTE_TCL = "fastroute.tcl"
64-
CONSTRAINTS_SDC = "constraint.sdc"
62+
# Name of the final metric
6563
METRIC = "minimum"
64+
# The worst of optimized metric
6665
ERROR_METRIC = 9e99
66+
# Path to the FLOW_HOME directory
6767
ORFS_FLOW_DIR = os.path.abspath(
6868
os.path.join(os.path.dirname(__file__), "../../../../flow")
6969
)
@@ -81,17 +81,34 @@ def setup(self, config):
8181
# We create the following directory structure:
8282
# 1/ 2/ 3/ 4/ 5/ 6/
8383
# <repo>/<logs>/<platform>/<design>/<experiment>-DATE/<id>/<cwd>
84+
# Run by Ray in directory specified by `local_dir`
8485
repo_dir = os.getcwd() + "/../" * 6
8586
self.repo_dir = os.path.abspath(repo_dir)
86-
self.parameters = parse_config(config, args.platform, SDC_ORIGINAL, CONSTRAINTS_SDC, FR_ORIGINAL, FASTROUTE_TCL, path=os.getcwd())
87+
self.parameters = parse_config(
88+
config=config,
89+
base_dir=self.repo_dir,
90+
platform=args.platform,
91+
sdc_original=SDC_ORIGINAL,
92+
constraints_sdc=CONSTRAINTS_SDC,
93+
fr_original=FR_ORIGINAL,
94+
fastroute_tcl=FASTROUTE_TCL,
95+
path=os.getcwd(),
96+
)
8797
self.step_ = 0
8898
self.variant = f"variant-{self.__class__.__name__}-{self.trial_id}-or"
8999

90100
def step(self):
91101
"""
92102
Run step experiment and compute its score.
93103
"""
94-
metrics_file = openroad(args, self.repo_dir, self.parameters, self.variant, install_path=INSTALL_PATH, stage=args.to_stage)
104+
metrics_file = openroad(
105+
args=args,
106+
base_dir=self.repo_dir,
107+
parameters=self.parameters,
108+
flow_variant=self.variant,
109+
install_path=INSTALL_PATH,
110+
stage=args.to_stage,
111+
)
95112
self.step_ += 1
96113
score = self.evaluate(read_metrics(metrics_file, args.to_stage))
97114
# Feed the score back to Tune.
@@ -106,8 +123,6 @@ def evaluate(self, metrics):
106123
"""
107124
error = "ERR" in metrics.values()
108125
not_found = "N/A" in metrics.values()
109-
print("evaluate METRICS")
110-
print(metrics)
111126
if error or not_found:
112127
return ERROR_METRIC
113128
gamma = (metrics["clk_period"] - metrics["worst_slack"]) / 10
@@ -164,62 +179,6 @@ def evaluate(self, metrics):
164179
return score
165180

166181

167-
@ray.remote
168-
def openroad_distributed(repo_dir, config, path):
169-
"""Simple wrapper to run openroad distributed with Ray."""
170-
config = parse_config(args, config, SDC_ORIGINAL, CONSTRAINTS_SDC, FR_ORIGINAL, FASTROUTE_TCL)
171-
openroad(args, repo_dir, config, str(uuid()), path=path, install_path=INSTALL_PATH, stage=args.to_stage)
172-
173-
174-
def clone(path):
175-
"""
176-
Clone base repo in the remote machine. Only used for Kubernetes at GCP.
177-
"""
178-
if args.git_clone:
179-
run_command(args, f"rm -rf {path}")
180-
if not os.path.isdir(f"{path}/.git"):
181-
git_command = "git clone --depth 1 --recursive --single-branch"
182-
git_command += f" {args.git_clone_args}"
183-
git_command += f" --branch {args.git_orfs_branch}"
184-
git_command += f" {args.git_url} {path}"
185-
run_command(args, git_command)
186-
187-
188-
def build(base, install):
189-
"""
190-
Build OpenROAD, Yosys and other dependencies.
191-
"""
192-
build_command = f'cd "{base}"'
193-
if args.git_clean:
194-
build_command += " && git clean -xdf tools"
195-
build_command += " && git submodule foreach --recursive git clean -xdf"
196-
if (
197-
args.git_clean
198-
or not os.path.isfile(f"{install}/OpenROAD/bin/openroad")
199-
or not os.path.isfile(f"{install}/yosys/bin/yosys")
200-
):
201-
build_command += ' && bash -ic "./build_openroad.sh'
202-
# Some GCP machines have 200+ cores. Let's be reasonable...
203-
build_command += f" --local --nice --threads {min(32, cpu_count())}"
204-
if args.git_latest:
205-
build_command += " --latest"
206-
build_command += f' {args.build_args}"'
207-
run_command(args, build_command)
208-
209-
210-
@ray.remote
211-
def setup_repo(base):
212-
"""
213-
Clone ORFS repository and compile binaries.
214-
"""
215-
print(f"[INFO TUN-0000] Remote folder: {base}")
216-
install = f"{base}/tools/install"
217-
if args.server is not None:
218-
clone(base)
219-
build(base, install)
220-
return install
221-
222-
223182
def parse_arguments():
224183
"""
225184
Parse arguments from command line.
@@ -247,60 +206,6 @@ def parse_arguments():
247206
"--resume", action="store_true", help="Resume previous run."
248207
)
249208

250-
# Setup
251-
parser.add_argument(
252-
"--git_clean",
253-
action="store_true",
254-
help="Clean binaries and build files."
255-
" WARNING: may lose previous data."
256-
" Use carefully.",
257-
)
258-
parser.add_argument(
259-
"--git_clone",
260-
action="store_true",
261-
help="Force new git clone."
262-
" WARNING: may lose previous data."
263-
" Use carefully.",
264-
)
265-
parser.add_argument(
266-
"--git_clone_args",
267-
type=str,
268-
metavar="<str>",
269-
default="",
270-
help="Additional git clone arguments.",
271-
)
272-
parser.add_argument(
273-
"--git_latest", action="store_true", help="Use latest version of OpenROAD app."
274-
)
275-
parser.add_argument(
276-
"--git_or_branch",
277-
type=str,
278-
metavar="<str>",
279-
default="",
280-
help="OpenROAD app branch to use.",
281-
)
282-
parser.add_argument(
283-
"--git_orfs_branch",
284-
type=str,
285-
metavar="<str>",
286-
default="master",
287-
help="OpenROAD-flow-scripts branch to use.",
288-
)
289-
parser.add_argument(
290-
"--git_url",
291-
type=str,
292-
metavar="<url>",
293-
default=ORFS_URL,
294-
help="OpenROAD-flow-scripts repo URL to use.",
295-
)
296-
parser.add_argument(
297-
"--build_args",
298-
type=str,
299-
metavar="<str>",
300-
default="",
301-
help="Additional arguments given to ./build_openroad.sh.",
302-
)
303-
304209
# ML
305210
tune_parser.add_argument(
306211
"--algorithm",
@@ -335,7 +240,7 @@ def parse_arguments():
335240
type=int,
336241
metavar="<int>",
337242
default=1,
338-
help="Number of CPUs to request for each tunning job.",
243+
help="Number of CPUs to request for each tuning job.",
339244
)
340245
tune_parser.add_argument(
341246
"--reference",
@@ -355,29 +260,6 @@ def parse_arguments():
355260
"--seed", type=int, metavar="<int>", default=42, help="Random seed."
356261
)
357262

358-
# Workload
359-
parser.add_argument(
360-
"--jobs",
361-
type=int,
362-
metavar="<int>",
363-
default=int(np.floor(cpu_count() / 2)),
364-
help="Max number of concurrent jobs.",
365-
)
366-
parser.add_argument(
367-
"--server",
368-
type=str,
369-
metavar="<ip|servername>",
370-
default=None,
371-
help="The address of Ray server to connect.",
372-
)
373-
parser.add_argument(
374-
"--port",
375-
type=int,
376-
metavar="<int>",
377-
default=10001,
378-
help="The port of Ray server to connect.",
379-
)
380-
381263
arguments = parser.parse_args()
382264
if arguments.mode == "tune":
383265
arguments.algorithm = arguments.algorithm.lower()
@@ -466,17 +348,6 @@ def save_best(results):
466348
print(f"[INFO TUN-0003] Best parameters written to {new_best_path}")
467349

468350

469-
@ray.remote
470-
def consumer(queue):
471-
"""consumer"""
472-
while not queue.empty():
473-
next_item = queue.get()
474-
name = next_item[1]
475-
print(f"[INFO TUN-0007] Scheduling run for parameter {name}.")
476-
ray.get(openroad_distributed.remote(*next_item))
477-
print(f"[INFO TUN-0008] Finished run for parameter {name}.")
478-
479-
480351
def sweep():
481352
"""Run sweep of parameters"""
482353
if args.server is not None:
@@ -485,7 +356,7 @@ def sweep():
485356
# <repo>/<logs>/<platform>/<design>/
486357
repo_dir = os.path.abspath(LOCAL_DIR + "/../" * 4)
487358
else:
488-
repo_dir = os.path.abspath("../")
359+
repo_dir = os.path.abspath(os.path.join(ORFS_FLOW_DIR, ".."))
489360
print(f"[INFO TUN-0012] Log folder {LOCAL_DIR}.")
490361
queue = Queue()
491362
parameter_list = list()
@@ -502,50 +373,25 @@ def sweep():
502373
temp = dict()
503374
for value in parameter:
504375
temp.update(value)
505-
print(temp)
506-
queue.put([repo_dir, temp, LOCAL_DIR])
376+
queue.put(
377+
[args, repo_dir, temp, LOCAL_DIR, SDC_ORIGINAL, FR_ORIGINAL, INSTALL_PATH]
378+
)
507379
workers = [consumer.remote(queue) for _ in range(args.jobs)]
508380
print("[INFO TUN-0009] Waiting for results.")
509381
ray.get(workers)
510382
print("[INFO TUN-0010] Sweep complete.")
511383

512384

513-
if __name__=="__main__":
385+
if __name__ == "__main__":
514386
args = parse_arguments()
515387

516388
# Read config and original files before handling where to run in case we
517389
# need to upload the files.
518-
config_dict, SDC_ORIGINAL, FR_ORIGINAL = read_config(os.path.abspath(args.config), args.mode, args.algorithm)
390+
config_dict, SDC_ORIGINAL, FR_ORIGINAL = read_config(
391+
os.path.abspath(args.config), args.mode, getattr(args, "algorithm", None)
392+
)
519393

520-
# Connect to remote Ray server if any, otherwise will run locally
521-
if args.server is not None:
522-
# At GCP we have a NFS folder that is present for all worker nodes.
523-
# This allows to build required binaries once. We clone, build and
524-
# store intermediate files at LOCAL_DIR.
525-
with open(args.config) as config_file:
526-
LOCAL_DIR = "/shared-data/autotuner"
527-
LOCAL_DIR += f"-orfs-{args.git_orfs_branch}"
528-
if args.git_or_branch != "":
529-
LOCAL_DIR += f"-or-{args.git_or_branch}"
530-
if args.git_latest:
531-
LOCAL_DIR += "-or-latest"
532-
# Connect to ray server before first remote execution.
533-
ray.init(f"ray://{args.server}:{args.port}")
534-
# Remote functions return a task id and are non-blocking. Since we
535-
# need the setup repo before continuing, we call ray.get() to wait
536-
# for its completion.
537-
INSTALL_PATH = ray.get(setup_repo.remote(LOCAL_DIR))
538-
LOCAL_DIR += f"/flow/logs/{args.platform}/{args.design}"
539-
print("[INFO TUN-0001] NFS setup completed.")
540-
else:
541-
# For local runs, use the same folder as other ORFS utilities.
542-
ORFS_FLOW_DIR = os.path.abspath(
543-
os.path.join(os.path.dirname(__file__), "../../../../flow")
544-
)
545-
os.chdir(ORFS_FLOW_DIR)
546-
LOCAL_DIR = f"logs/{args.platform}/{args.design}"
547-
LOCAL_DIR = os.path.abspath(LOCAL_DIR)
548-
INSTALL_PATH = os.path.abspath("../tools/install")
394+
LOCAL_DIR, ORFS_FLOW_DIR, INSTALL_PATH = prepare_ray_server(args)
549395

550396
if args.mode == "tune":
551397
best_params = set_best_params(args.platform, args.design)

0 commit comments

Comments
 (0)