/
tir_integration.py
269 lines (252 loc) · 9.06 KB
/
tir_integration.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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""MetaSchedule-TIR integration"""
from typing import List, Mapping, Optional, Tuple, Union
# isort: off
from typing_extensions import Literal
# isort: on
from tvm import ir, tir
from tvm._ffi import register_func
from tvm.target import Target
from tvm.tir.expr import IntImm
from .builder import Builder
from .cost_model import CostModel
from .database import Database
from .logging import get_loggers_from_work_dir
from .measure_callback import MeasureCallback
from .runner import Runner
from .search_strategy import SearchStrategy
from .space_generator import SpaceGenerator
from .task_scheduler import TaskScheduler
from .tune import tune_tasks
from .tune_context import TuneContext, _normalize_mod
from .utils import fork_seed
def tune_tir( # pylint: disable=too-many-locals
mod: Union[ir.IRModule, tir.PrimFunc],
target: Union[str, Target],
work_dir: str,
max_trials_global: int,
*,
max_trials_per_task: Optional[int] = None,
num_trials_per_iter: int = 64,
builder: Builder.BuilderType = "local",
runner: Runner.RunnerType = "local",
database: Database.DatabaseType = "json",
cost_model: CostModel.CostModelType = "xgb",
measure_callbacks: MeasureCallback.CallbackListType = "default",
task_scheduler: TaskScheduler.TaskSchedulerType = "gradient",
space: SpaceGenerator.SpaceGeneratorType = "post-order-apply",
strategy: SearchStrategy.SearchStrategyType = "evolutionary",
num_tuning_cores: Union[Literal["physical", "logical"], int] = "physical",
seed: Optional[int] = None,
module_equality: str = "structural",
special_space: Optional[Mapping[str, SpaceGenerator.SpaceGeneratorType]] = None,
) -> Database:
"""Tune a TIR function or an IRModule of TIR functions.
Parameters
----------
mod : Union[ir.IRModule, tir.PrimFunc]
The TIR IRModule to tune.
target : Union[str, Target]
The target to tune for.
work_dir : str
The working directory.
max_trials_global : int
The maximum number of trials to run globally.
max_trials_per_task : Optional[int]
The maximum number of trials to run per task.
num_trials_per_iter : int
The number of trials to run per iteration
builder : Builder.BuilderType
The builder.
runner : Runner.RunnerType
The runner.
database : Database.DatabaseType
The database.
cost_model : CostModel.CostModelType
The cost model.
measure_callbacks : MeasureCallback.CallbackListType
The measure callbacks.
task_scheduler : TaskScheduler.TaskSchedulerType
The task scheduler.
space : SpaceGenerator.SpaceGeneratorType
The space generator.
strategy : SearchStrategy.SearchStrategyType
The search strategy.
num_tuning_cores : Union[Literal["physical", "logical"], int]
The number of CPU cores to use during tuning.
seed : Optional[int]
The seed for the random number generator.
module_equality : Optional[str]
A string to specify the module equality testing and hashing method.
special_space : Optional[Mapping[str, SpaceGenerator.SpaceGeneratorType]]
A mapping from task name to a special space generator for that task.
Returns
-------
database : Database
The database with all tuning records
"""
if isinstance(mod, tir.PrimFunc):
mod = _normalize_mod(mod)
named_tasks: List[Tuple[str, tir.PrimFunc]] = []
for gv, func in mod.functions_items(): # pylint: disable=invalid-name
if isinstance(func, tir.PrimFunc):
named_tasks.append((gv.name_hint, func))
named_tasks.sort(key=lambda x: x[0])
task_names = [x for x, _ in named_tasks]
tasks: List[TuneContext] = []
for task_name, task_func, logger, rand_state in zip(
task_names,
[x for _, x in named_tasks],
get_loggers_from_work_dir(work_dir, task_names),
fork_seed(seed, n=len(named_tasks)),
):
if special_space and task_name in special_space:
task_space = special_space[task_name]
else:
task_space = space
if task_space is None:
continue
tasks.append(
TuneContext(
mod=task_func,
target=target,
space_generator=task_space,
search_strategy=strategy,
task_name=task_name,
rand_state=rand_state,
num_threads=num_tuning_cores,
logger=logger,
).clone()
)
return tune_tasks(
tasks=tasks,
task_weights=[1.0] * len(tasks),
work_dir=work_dir,
max_trials_global=max_trials_global,
max_trials_per_task=max_trials_per_task,
num_trials_per_iter=num_trials_per_iter,
builder=builder,
runner=runner,
database=database,
cost_model=cost_model,
measure_callbacks=measure_callbacks,
task_scheduler=task_scheduler,
module_equality=module_equality,
)
@register_func("tvm.meta_schedule.tune_tir")
def _tune_tir(
mod: Union[ir.IRModule, tir.PrimFunc],
target: Union[str, Target],
work_dir: str,
max_trials_global: int,
*,
num_trials_per_iter: int = 64,
builder: Builder.BuilderType = "local",
runner: Runner.RunnerType = "local",
database: Database.DatabaseType = "json",
cost_model: CostModel.CostModelType = "xgb",
measure_callbacks: MeasureCallback.CallbackListType = "default",
task_scheduler: TaskScheduler.TaskSchedulerType = "round-robin",
space: SpaceGenerator.SpaceGeneratorType = "post-order-apply",
strategy: SearchStrategy.SearchStrategyType = "evolutionary",
num_tuning_cores: Union[Literal["physical", "logical"], int] = "physical",
seed: Optional[int] = None,
) -> Database:
"""Interface with tuning api to tune a TIR program.
Parameters
----------
mod : Union[ir.IRModule, tir.PrimFunc]
The TIR function to tune.
target : Union[str, Target]
The target to tune for.
work_dir : str
The working directory.
max_trials_global : int
The maximum number of trials to run globally.
num_trials_per_iter : int
The number of trials to run per iteration
builder : Builder.BuilderType
The builder.
runner : Runner.RunnerType
The runner.
database : Database.DatabaseType
The database.
cost_model : CostModel.CostModelType
The cost model.
measure_callbacks : MeasureCallback.CallbackListType
The measure callbacks.
task_scheduler : TaskScheduler.TaskSchedulerType
The task scheduler.
space : SpaceGenerator.SpaceGeneratorType
The space generator.
strategy : SearchStrategy.SearchStrategyType
The search strategy.
num_tuning_cores : Union[Literal["physical", "logical"], int]
The number of CPU cores to use during tuning.
seed : Optional[int]
The seed for the random number generator.
Returns
-------
ret_mod : IRModule
IRModule
"""
if isinstance(max_trials_global, IntImm):
max_trials_global = int(max_trials_global)
tune_tir(
mod,
target,
work_dir,
max_trials_global,
num_trials_per_iter=num_trials_per_iter,
builder=builder,
runner=runner,
database=database,
cost_model=cost_model,
measure_callbacks=measure_callbacks,
task_scheduler=task_scheduler,
space=space,
strategy=strategy,
num_tuning_cores=num_tuning_cores,
seed=seed,
)
# Return original IRModule
# This pass only makes optimization decision
return mod
def compile_tir(
database: Database,
mod: Union[ir.IRModule, tir.PrimFunc],
target: Union[Target, str],
) -> tir.Schedule:
"""Compile a TIR to tir.Schedule, according to the records in the database.
Parameters
----------
database : Database
The database of tuning records.
mod : Union[ir.IRModule, tir.PrimFunc]
The TIR function to tune.
target : Union[str, Target]
The target to tune for.
Returns
-------
sch : tir.Schedule
The best schedule found in the database.
"""
mod = _normalize_mod(mod)
if not isinstance(target, Target):
target = Target(target)
return database.query_schedule(mod, target, workload_name="main")