You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by GitBox <gi...@apache.org> on 2022/04/12 23:22:23 UTC

[GitHub] [tvm] junrushao1994 opened a new pull request, #10986: [MetaSchedule][Refactor] Introduce TuneConfig

junrushao1994 opened a new pull request, #10986:
URL: https://github.com/apache/tvm/pull/10986

   This PR unifies the existing `EvolutionarySearchConfig`, `ReplayFuncConfig` and `ReplayTraceConfig` into `TuneConfig`, and refactored the logic in `meta_schedule/tune.py`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] masahi commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
masahi commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r849888664


##########
python/tvm/meta_schedule/search_strategy/evolutionary_search.py:
##########
@@ -64,13 +64,13 @@ def __init__(
         *,
         num_trials_per_iter: int,
         max_trials_per_task: int,
-        population_size: int,
-        init_measured_ratio: float,
-        init_min_unmeasured: int,
-        genetic_num_iters: int,
-        genetic_mutate_prob: float,
-        genetic_max_fail_count: int,
-        eps_greedy: float,
+        population_size: int = 2048,
+        init_measured_ratio: float = 0.2,
+        init_min_unmeasured: int = 50,
+        genetic_num_iters: int = 4,
+        genetic_mutate_prob: float = 0.85,
+        genetic_max_fail_count: int = 10,
+        eps_greedy: float = 0.05,

Review Comment:
   I don't know how often (if ever) we want to do this, but these default parameters seem hand-picked, so naturally I wonder if tweaking these params can lead to improvement. And if I do want to do that, the current API doesn't have an easy API like `tune_relay(...)` with manually constructed `EvolutionarySearch`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851887771


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   Hi Masa, this is actually a great point! Generally speaking, I would recommend `max_trials_per_task 
    == max_trials_global` by default, and leave the TaskSchedule to decide how to allocate those trials



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r849893934


##########
python/tvm/meta_schedule/search_strategy/evolutionary_search.py:
##########
@@ -64,13 +64,13 @@ def __init__(
         *,
         num_trials_per_iter: int,
         max_trials_per_task: int,
-        population_size: int,
-        init_measured_ratio: float,
-        init_min_unmeasured: int,
-        genetic_num_iters: int,
-        genetic_mutate_prob: float,
-        genetic_max_fail_count: int,
-        eps_greedy: float,
+        population_size: int = 2048,
+        init_measured_ratio: float = 0.2,
+        init_min_unmeasured: int = 50,
+        genetic_num_iters: int = 4,
+        genetic_mutate_prob: float = 0.85,
+        genetic_max_fail_count: int = 10,
+        eps_greedy: float = 0.05,

Review Comment:
   Thanks for sharing! If I read it correctly, while indeed it's less frequent, there is definitely usecase to tweak parameters. To allow this to happen, we have an extra parameter called `TuneConfig.search_strategy_config`. For example,
   
   ```python
   tune_relay(
     config=TuneConfig(
       strategy="evolutionary",
       num_trials_per_iter=64,
       max_trials_per_task=20000,
       max_trials_global=20000,
       search_strategy_config = {
         "genetic_num_iters": 10,
       },
     ),
   )
   ```
   
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] masahi commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
masahi commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r849897034


##########
python/tvm/meta_schedule/search_strategy/evolutionary_search.py:
##########
@@ -64,13 +64,13 @@ def __init__(
         *,
         num_trials_per_iter: int,
         max_trials_per_task: int,
-        population_size: int,
-        init_measured_ratio: float,
-        init_min_unmeasured: int,
-        genetic_num_iters: int,
-        genetic_mutate_prob: float,
-        genetic_max_fail_count: int,
-        eps_greedy: float,
+        population_size: int = 2048,
+        init_measured_ratio: float = 0.2,
+        init_min_unmeasured: int = 50,
+        genetic_num_iters: int = 4,
+        genetic_mutate_prob: float = 0.85,
+        genetic_max_fail_count: int = 10,
+        eps_greedy: float = 0.05,

Review Comment:
   Oh nice! I didn't notice that. `search_strategy_config` thing doesn't seem to be used in tests, can you add a trivial one (like your example above)?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] zxybazh commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
zxybazh commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851889294


##########
python/tvm/meta_schedule/tune.py:
##########
@@ -449,95 +336,189 @@ def _mutator_probs(
         # pylint: enable=protected-access
         raise ValueError(f"Unsupported target: {target}")
 
-    @staticmethod
-    def _tune_context(
-        tune_context: Optional[TuneContext],
-        mod: IRModule,
-        target: Target,
-        config: SearchStrategyConfig,
-        task_name: str,
-        space_generator: Optional[FnSpaceGenerator],
-        sch_rules: Optional[FnScheduleRule],
-        postprocs: Optional[FnPostproc],
-        mutator_probs: Optional[FnMutatorProb],
-        num_threads: Optional[int],
-    ) -> TuneContext:
-        if tune_context is None:
-            return TuneContext(
-                mod=mod,
-                target=target,
-                # pylint: disable=protected-access
-                space_generator=Parse._space_generator(space_generator),
-                search_strategy=config.create_strategy(),
-                sch_rules=Parse._sch_rules(sch_rules, target),
-                postprocs=Parse._postproc(postprocs, target),
-                mutator_probs=Parse._mutator_probs(mutator_probs, target),
-                # pylint: enable=protected-access
-                task_name=task_name,
-                rand_state=-1,
-                num_threads=num_threads,
-            )
-        if not isinstance(tune_context, TuneContext):
-            raise TypeError(f"Expected `tune_context` to be TuneContext, but gets: {tune_context}")
-        return tune_context
 
-    @staticmethod
-    def _task_scheduler(
-        task_scheduler: Union[None, TaskScheduler, FnTaskScheduler],
-        tasks: List[TuneContext],
-        task_weights: List[float],
-        builder: Builder,
-        runner: Runner,
-        database: Database,
-        max_trials: int,
-        cost_model: CostModel,
-        measure_callbacks: List[MeasureCallback],
-    ):
-        if task_scheduler is None:
-            return GradientBased(
-                tasks=tasks,
-                task_weights=task_weights,
-                builder=builder,
-                runner=runner,
-                database=database,
-                max_trials=max_trials,
-                cost_model=cost_model,
-                measure_callbacks=measure_callbacks,
+class TuneConfig(NamedTuple):
+    """Configuration for tuning
+
+    Parameters
+    ----------
+    max_trials_global: int
+        Maximum number of trials to run.
+    num_trials_per_iter: int
+        Number of trials to run per iteration.
+    max_trials_per_task: int
+        Maximum number of trials to run per task.
+    task_scheduler: str
+        Task scheduler to use.
+        Valid options are: round_robin, gradient.
+    search_strategy: str
+        Search strategy to use.
+        Valid options are: evolutionary, replay_func, replay_trace.
+    task_scheduler_config: Dict[str, Any]
+        Configuration for task scheduler.
+    search_strategy_config: Dict[str, Any]
+        Configuration for search strategy.
+    """
+
+    max_trials_global: int
+    num_trials_per_iter: int
+    max_trials_per_task: Optional[int] = None
+    task_scheduler: str = "gradient"
+    strategy: str = "evolutionary"
+    task_scheduler_config: Dict[str, Any] = {}
+    search_strategy_config: Dict[str, Any] = {}
+

Review Comment:
   Shall we also introduce `random_seed` as part of `TuneConfig`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851892520


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   Well, yes or no. There is no "definitely correct" suggestion in terms of how many trials should be allocated globally or locally...



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] masahi commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
masahi commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r849073870


##########
python/tvm/meta_schedule/search_strategy/evolutionary_search.py:
##########
@@ -64,13 +64,13 @@ def __init__(
         *,
         num_trials_per_iter: int,
         max_trials_per_task: int,
-        population_size: int,
-        init_measured_ratio: float,
-        init_min_unmeasured: int,
-        genetic_num_iters: int,
-        genetic_mutate_prob: float,
-        genetic_max_fail_count: int,
-        eps_greedy: float,
+        population_size: int = 2048,
+        init_measured_ratio: float = 0.2,
+        init_min_unmeasured: int = 50,
+        genetic_num_iters: int = 4,
+        genetic_mutate_prob: float = 0.85,
+        genetic_max_fail_count: int = 10,
+        eps_greedy: float = 0.05,

Review Comment:
   If I want to tweak these params, I need to manually call `config.create_strategy(...)`, and I don't see an easy tuning API for such case.  



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] zxybazh commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
zxybazh commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851096303


##########
python/tvm/meta_schedule/tune.py:
##########
@@ -449,95 +336,190 @@ def _mutator_probs(
         # pylint: enable=protected-access
         raise ValueError(f"Unsupported target: {target}")
 
-    @staticmethod
-    def _tune_context(
-        tune_context: Optional[TuneContext],
-        mod: IRModule,
-        target: Target,
-        config: SearchStrategyConfig,
-        task_name: str,
-        space_generator: Optional[FnSpaceGenerator],
-        sch_rules: Optional[FnScheduleRule],
-        postprocs: Optional[FnPostproc],
-        mutator_probs: Optional[FnMutatorProb],
-        num_threads: Optional[int],
-    ) -> TuneContext:
-        if tune_context is None:
-            return TuneContext(
-                mod=mod,
-                target=target,
-                # pylint: disable=protected-access
-                space_generator=Parse._space_generator(space_generator),
-                search_strategy=config.create_strategy(),
-                sch_rules=Parse._sch_rules(sch_rules, target),
-                postprocs=Parse._postproc(postprocs, target),
-                mutator_probs=Parse._mutator_probs(mutator_probs, target),
-                # pylint: enable=protected-access
-                task_name=task_name,
-                rand_state=-1,
-                num_threads=num_threads,
-            )
-        if not isinstance(tune_context, TuneContext):
-            raise TypeError(f"Expected `tune_context` to be TuneContext, but gets: {tune_context}")
-        return tune_context
 
-    @staticmethod
-    def _task_scheduler(
-        task_scheduler: Union[None, TaskScheduler, FnTaskScheduler],
-        tasks: List[TuneContext],
-        task_weights: List[float],
-        builder: Builder,
-        runner: Runner,
-        database: Database,
-        max_trials: int,
-        cost_model: CostModel,
-        measure_callbacks: List[MeasureCallback],
-    ):
-        if task_scheduler is None:
-            return GradientBased(
-                tasks=tasks,
-                task_weights=task_weights,
-                builder=builder,
-                runner=runner,
-                database=database,
-                max_trials=max_trials,
-                cost_model=cost_model,
-                measure_callbacks=measure_callbacks,
+class TuneConfig(NamedTuple):
+    """Configuration for tuning
+
+    Parameters
+    ----------
+    max_trials_global: int
+        Maximum number of trials to run.
+    num_trials_per_iter: int
+        Number of trials to run per iteration.
+    max_trials_per_task: int
+        Maximum number of trials to run per task.
+    task_scheduler: str
+        Task scheduler to use.
+        Valid options are: round_robin, gradient.
+    search_strategy: str
+        Search strategy to use.
+        Valid options are: evolutionary, replay_func, replay_trace.
+    task_scheduler_config: Dict[str, Any]
+        Configuration for task scheduler.
+    search_strategy_config: Dict[str, Any]
+        Configuration for search strategy.
+    """
+
+    max_trials_global: int
+    num_trials_per_iter: int
+    max_trials_per_task: Optional[int] = None
+    task_scheduler: str = "gradient"
+    strategy: str = "evolutionary"
+    task_scheduler_config: Dict[str, Any] = {}
+    search_strategy_config: Dict[str, Any] = {}
+
+    def create_strategy(self, **kwargs):
+        """Create search strategy from configuration"""
+        cls_tbl = {
+            "evolutionary": EvolutionarySearch,
+            "replay_func": ReplayFunc,
+            "replay_trace": ReplayTrace,
+        }
+        if self.strategy not in cls_tbl:
+            raise ValueError(
+                f"Invalid search strategy: {self.strategy}. "
+                "Valid options are: {}".format(", ".join(cls_tbl.keys()))
             )
-        if callable(task_scheduler):
-            return task_scheduler(
-                tasks,
-                task_weights,
-                builder,
-                runner,
-                database,
-                cost_model,
-                measure_callbacks,
+        max_trials_per_task = self.max_trials_per_task
+        if max_trials_per_task is None:
+            max_trials_per_task = self.max_trials_global
+        return cls_tbl[self.strategy](
+            num_trials_per_iter=self.num_trials_per_iter,
+            max_trials_per_task=max_trials_per_task,
+            **kwargs,
+            **self.search_strategy_config,
+        )
+
+    def create_task_scheduler(self, **kwargs):
+        """Create task scheduler from configuration"""
+        cls_tbl = {
+            "round_robin": RoundRobin,
+            "gradient": GradientBased,
+        }
+        if self.task_scheduler not in cls_tbl:
+            raise ValueError(
+                f"Invalid task scheduler: {self.task_scheduler}. "
+                "Valid options are: {}".format(", ".join(cls_tbl.keys()))
             )
-        if not isinstance(task_scheduler, TaskScheduler):
-            raise TypeError(
-                f"Expected `task_scheduler` to be TaskScheduler, but gets: {task_scheduler}"
+        return cls_tbl[self.task_scheduler](
+            max_trials=self.max_trials_global,
+            **kwargs,
+            **self.task_scheduler_config,
+        )
+
+
+def tune_extracted_tasks(
+    extracted_tasks: List[ExtractedTask],
+    config: TuneConfig,
+    work_dir: str,
+    *,
+    builder: Optional[Builder] = None,
+    runner: Optional[Runner] = None,
+    database: Optional[Database] = None,
+    cost_model: Optional[CostModel] = None,
+    measure_callbacks: Optional[List[MeasureCallback]] = None,
+    space: Optional[FnSpaceGenerator] = None,
+    sch_rules: Optional[FnScheduleRule] = None,
+    postprocs: Optional[FnPostproc] = None,
+    mutator_probs: Optional[FnMutatorProb] = None,
+    num_threads: Optional[int] = None,
+) -> Database:
+    """Tune extracted tasks with a given target.
+
+    Parameters
+    ----------
+    extracted_tasks : List[ExtractedTask]
+        The list of extraced tasks.
+    config : TuneConfig
+        The search strategy config.
+    work_dir : Optional[str]
+        The working directory to save intermediate results.
+    builder : Optional[Builder]
+        The builder to use.
+    runner : Optional[Runner]
+        The runner to use.
+    database : Optional[Database]
+        The database to use.
+    cost_model : Optional[CostModel]
+        The cost model to use.
+    measure_callbacks : Optional[List[MeasureCallback]]
+        The callbacks used during tuning.
+    task_scheduler : Optional[TaskScheduler]

Review Comment:
   Remove this.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851099605


##########
python/tvm/meta_schedule/tune.py:
##########
@@ -449,95 +336,190 @@ def _mutator_probs(
         # pylint: enable=protected-access
         raise ValueError(f"Unsupported target: {target}")
 
-    @staticmethod
-    def _tune_context(
-        tune_context: Optional[TuneContext],
-        mod: IRModule,
-        target: Target,
-        config: SearchStrategyConfig,
-        task_name: str,
-        space_generator: Optional[FnSpaceGenerator],
-        sch_rules: Optional[FnScheduleRule],
-        postprocs: Optional[FnPostproc],
-        mutator_probs: Optional[FnMutatorProb],
-        num_threads: Optional[int],
-    ) -> TuneContext:
-        if tune_context is None:
-            return TuneContext(
-                mod=mod,
-                target=target,
-                # pylint: disable=protected-access
-                space_generator=Parse._space_generator(space_generator),
-                search_strategy=config.create_strategy(),
-                sch_rules=Parse._sch_rules(sch_rules, target),
-                postprocs=Parse._postproc(postprocs, target),
-                mutator_probs=Parse._mutator_probs(mutator_probs, target),
-                # pylint: enable=protected-access
-                task_name=task_name,
-                rand_state=-1,
-                num_threads=num_threads,
-            )
-        if not isinstance(tune_context, TuneContext):
-            raise TypeError(f"Expected `tune_context` to be TuneContext, but gets: {tune_context}")
-        return tune_context
 
-    @staticmethod
-    def _task_scheduler(
-        task_scheduler: Union[None, TaskScheduler, FnTaskScheduler],
-        tasks: List[TuneContext],
-        task_weights: List[float],
-        builder: Builder,
-        runner: Runner,
-        database: Database,
-        max_trials: int,
-        cost_model: CostModel,
-        measure_callbacks: List[MeasureCallback],
-    ):
-        if task_scheduler is None:
-            return GradientBased(
-                tasks=tasks,
-                task_weights=task_weights,
-                builder=builder,
-                runner=runner,
-                database=database,
-                max_trials=max_trials,
-                cost_model=cost_model,
-                measure_callbacks=measure_callbacks,
+class TuneConfig(NamedTuple):
+    """Configuration for tuning
+
+    Parameters
+    ----------
+    max_trials_global: int
+        Maximum number of trials to run.
+    num_trials_per_iter: int
+        Number of trials to run per iteration.
+    max_trials_per_task: int
+        Maximum number of trials to run per task.
+    task_scheduler: str
+        Task scheduler to use.
+        Valid options are: round_robin, gradient.
+    search_strategy: str
+        Search strategy to use.
+        Valid options are: evolutionary, replay_func, replay_trace.
+    task_scheduler_config: Dict[str, Any]
+        Configuration for task scheduler.
+    search_strategy_config: Dict[str, Any]
+        Configuration for search strategy.
+    """
+
+    max_trials_global: int
+    num_trials_per_iter: int
+    max_trials_per_task: Optional[int] = None
+    task_scheduler: str = "gradient"
+    strategy: str = "evolutionary"
+    task_scheduler_config: Dict[str, Any] = {}
+    search_strategy_config: Dict[str, Any] = {}
+
+    def create_strategy(self, **kwargs):
+        """Create search strategy from configuration"""
+        cls_tbl = {
+            "evolutionary": EvolutionarySearch,
+            "replay_func": ReplayFunc,
+            "replay_trace": ReplayTrace,
+        }
+        if self.strategy not in cls_tbl:
+            raise ValueError(
+                f"Invalid search strategy: {self.strategy}. "
+                "Valid options are: {}".format(", ".join(cls_tbl.keys()))
             )
-        if callable(task_scheduler):
-            return task_scheduler(
-                tasks,
-                task_weights,
-                builder,
-                runner,
-                database,
-                cost_model,
-                measure_callbacks,
+        max_trials_per_task = self.max_trials_per_task
+        if max_trials_per_task is None:
+            max_trials_per_task = self.max_trials_global
+        return cls_tbl[self.strategy](
+            num_trials_per_iter=self.num_trials_per_iter,
+            max_trials_per_task=max_trials_per_task,
+            **kwargs,
+            **self.search_strategy_config,
+        )
+
+    def create_task_scheduler(self, **kwargs):
+        """Create task scheduler from configuration"""
+        cls_tbl = {
+            "round_robin": RoundRobin,
+            "gradient": GradientBased,
+        }
+        if self.task_scheduler not in cls_tbl:
+            raise ValueError(
+                f"Invalid task scheduler: {self.task_scheduler}. "
+                "Valid options are: {}".format(", ".join(cls_tbl.keys()))
             )
-        if not isinstance(task_scheduler, TaskScheduler):
-            raise TypeError(
-                f"Expected `task_scheduler` to be TaskScheduler, but gets: {task_scheduler}"
+        return cls_tbl[self.task_scheduler](
+            max_trials=self.max_trials_global,
+            **kwargs,
+            **self.task_scheduler_config,
+        )
+
+
+def tune_extracted_tasks(
+    extracted_tasks: List[ExtractedTask],
+    config: TuneConfig,
+    work_dir: str,
+    *,
+    builder: Optional[Builder] = None,
+    runner: Optional[Runner] = None,
+    database: Optional[Database] = None,
+    cost_model: Optional[CostModel] = None,
+    measure_callbacks: Optional[List[MeasureCallback]] = None,
+    space: Optional[FnSpaceGenerator] = None,
+    sch_rules: Optional[FnScheduleRule] = None,
+    postprocs: Optional[FnPostproc] = None,
+    mutator_probs: Optional[FnMutatorProb] = None,
+    num_threads: Optional[int] = None,
+) -> Database:
+    """Tune extracted tasks with a given target.
+
+    Parameters
+    ----------
+    extracted_tasks : List[ExtractedTask]
+        The list of extraced tasks.
+    config : TuneConfig
+        The search strategy config.
+    work_dir : Optional[str]
+        The working directory to save intermediate results.
+    builder : Optional[Builder]
+        The builder to use.
+    runner : Optional[Runner]
+        The runner to use.
+    database : Optional[Database]
+        The database to use.
+    cost_model : Optional[CostModel]
+        The cost model to use.
+    measure_callbacks : Optional[List[MeasureCallback]]
+        The callbacks used during tuning.
+    task_scheduler : Optional[TaskScheduler]
+        The task scheduler to use.
+    space : Optional[FnSpaceGenerator]
+        The space generator to use.
+    sch_rules : Optional[FnScheduleRule]
+        The search rules to use.
+    postprocs : Optional[FnPostproc]
+        The postprocessors to use.
+    mutator_probs : Optional[FnMutatorProb]
+        The probability distribution to use different mutators.
+    num_threads : Optional[int]
+        The number of threads to use.
+
+    Returns
+    -------
+    database : Database
+        The database containing all the tuning results.
+
+    """
+    logger.info("Working directory: %s", work_dir)
+    # pylint: disable=protected-access
+    database = Parse._database(database, work_dir)
+    builder = Parse._builder(builder)
+    runner = Parse._runner(runner)
+    cost_model = Parse._cost_model(cost_model)
+    measure_callbacks = Parse._callbacks(measure_callbacks)
+    # parse the tuning contexts
+    tune_contexts = []
+    for task in extracted_tasks:
+        assert len(task.dispatched) == 1, "Only size 1 dispatched task list is supported for now"
+        tune_contexts.append(
+            TuneContext(
+                mod=Parse._mod(task.dispatched[0]),
+                target=task.target,
+                space_generator=Parse._space_generator(space),
+                search_strategy=config.create_strategy(),
+                sch_rules=Parse._sch_rules(sch_rules, task.target),
+                postprocs=Parse._postproc(postprocs, task.target),
+                mutator_probs=Parse._mutator_probs(mutator_probs, task.target),
+                task_name=task.name,
+                rand_state=-1,  # TODO: random seed

Review Comment:
   oh good idea!



##########
python/tvm/meta_schedule/tune.py:
##########
@@ -449,95 +336,190 @@ def _mutator_probs(
         # pylint: enable=protected-access
         raise ValueError(f"Unsupported target: {target}")
 
-    @staticmethod
-    def _tune_context(
-        tune_context: Optional[TuneContext],
-        mod: IRModule,
-        target: Target,
-        config: SearchStrategyConfig,
-        task_name: str,
-        space_generator: Optional[FnSpaceGenerator],
-        sch_rules: Optional[FnScheduleRule],
-        postprocs: Optional[FnPostproc],
-        mutator_probs: Optional[FnMutatorProb],
-        num_threads: Optional[int],
-    ) -> TuneContext:
-        if tune_context is None:
-            return TuneContext(
-                mod=mod,
-                target=target,
-                # pylint: disable=protected-access
-                space_generator=Parse._space_generator(space_generator),
-                search_strategy=config.create_strategy(),
-                sch_rules=Parse._sch_rules(sch_rules, target),
-                postprocs=Parse._postproc(postprocs, target),
-                mutator_probs=Parse._mutator_probs(mutator_probs, target),
-                # pylint: enable=protected-access
-                task_name=task_name,
-                rand_state=-1,
-                num_threads=num_threads,
-            )
-        if not isinstance(tune_context, TuneContext):
-            raise TypeError(f"Expected `tune_context` to be TuneContext, but gets: {tune_context}")
-        return tune_context
 
-    @staticmethod
-    def _task_scheduler(
-        task_scheduler: Union[None, TaskScheduler, FnTaskScheduler],
-        tasks: List[TuneContext],
-        task_weights: List[float],
-        builder: Builder,
-        runner: Runner,
-        database: Database,
-        max_trials: int,
-        cost_model: CostModel,
-        measure_callbacks: List[MeasureCallback],
-    ):
-        if task_scheduler is None:
-            return GradientBased(
-                tasks=tasks,
-                task_weights=task_weights,
-                builder=builder,
-                runner=runner,
-                database=database,
-                max_trials=max_trials,
-                cost_model=cost_model,
-                measure_callbacks=measure_callbacks,
+class TuneConfig(NamedTuple):
+    """Configuration for tuning
+
+    Parameters
+    ----------
+    max_trials_global: int
+        Maximum number of trials to run.
+    num_trials_per_iter: int
+        Number of trials to run per iteration.
+    max_trials_per_task: int
+        Maximum number of trials to run per task.
+    task_scheduler: str
+        Task scheduler to use.
+        Valid options are: round_robin, gradient.
+    search_strategy: str
+        Search strategy to use.
+        Valid options are: evolutionary, replay_func, replay_trace.
+    task_scheduler_config: Dict[str, Any]
+        Configuration for task scheduler.
+    search_strategy_config: Dict[str, Any]
+        Configuration for search strategy.
+    """
+
+    max_trials_global: int
+    num_trials_per_iter: int
+    max_trials_per_task: Optional[int] = None
+    task_scheduler: str = "gradient"
+    strategy: str = "evolutionary"
+    task_scheduler_config: Dict[str, Any] = {}
+    search_strategy_config: Dict[str, Any] = {}
+
+    def create_strategy(self, **kwargs):
+        """Create search strategy from configuration"""
+        cls_tbl = {
+            "evolutionary": EvolutionarySearch,
+            "replay_func": ReplayFunc,
+            "replay_trace": ReplayTrace,
+        }
+        if self.strategy not in cls_tbl:
+            raise ValueError(
+                f"Invalid search strategy: {self.strategy}. "
+                "Valid options are: {}".format(", ".join(cls_tbl.keys()))
             )
-        if callable(task_scheduler):
-            return task_scheduler(
-                tasks,
-                task_weights,
-                builder,
-                runner,
-                database,
-                cost_model,
-                measure_callbacks,
+        max_trials_per_task = self.max_trials_per_task
+        if max_trials_per_task is None:
+            max_trials_per_task = self.max_trials_global
+        return cls_tbl[self.strategy](
+            num_trials_per_iter=self.num_trials_per_iter,
+            max_trials_per_task=max_trials_per_task,
+            **kwargs,
+            **self.search_strategy_config,
+        )
+
+    def create_task_scheduler(self, **kwargs):
+        """Create task scheduler from configuration"""
+        cls_tbl = {
+            "round_robin": RoundRobin,
+            "gradient": GradientBased,
+        }
+        if self.task_scheduler not in cls_tbl:
+            raise ValueError(
+                f"Invalid task scheduler: {self.task_scheduler}. "
+                "Valid options are: {}".format(", ".join(cls_tbl.keys()))
             )
-        if not isinstance(task_scheduler, TaskScheduler):
-            raise TypeError(
-                f"Expected `task_scheduler` to be TaskScheduler, but gets: {task_scheduler}"
+        return cls_tbl[self.task_scheduler](
+            max_trials=self.max_trials_global,
+            **kwargs,
+            **self.task_scheduler_config,
+        )
+
+
+def tune_extracted_tasks(
+    extracted_tasks: List[ExtractedTask],
+    config: TuneConfig,
+    work_dir: str,
+    *,
+    builder: Optional[Builder] = None,
+    runner: Optional[Runner] = None,
+    database: Optional[Database] = None,
+    cost_model: Optional[CostModel] = None,
+    measure_callbacks: Optional[List[MeasureCallback]] = None,
+    space: Optional[FnSpaceGenerator] = None,
+    sch_rules: Optional[FnScheduleRule] = None,
+    postprocs: Optional[FnPostproc] = None,
+    mutator_probs: Optional[FnMutatorProb] = None,
+    num_threads: Optional[int] = None,
+) -> Database:
+    """Tune extracted tasks with a given target.
+
+    Parameters
+    ----------
+    extracted_tasks : List[ExtractedTask]
+        The list of extraced tasks.
+    config : TuneConfig
+        The search strategy config.
+    work_dir : Optional[str]
+        The working directory to save intermediate results.
+    builder : Optional[Builder]
+        The builder to use.
+    runner : Optional[Runner]
+        The runner to use.
+    database : Optional[Database]
+        The database to use.
+    cost_model : Optional[CostModel]
+        The cost model to use.
+    measure_callbacks : Optional[List[MeasureCallback]]
+        The callbacks used during tuning.
+    task_scheduler : Optional[TaskScheduler]

Review Comment:
   my bad! thanks for spotting this!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] masahi commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
masahi commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r849889940


##########
python/tvm/meta_schedule/search_strategy/evolutionary_search.py:
##########
@@ -64,13 +64,13 @@ def __init__(
         *,
         num_trials_per_iter: int,
         max_trials_per_task: int,
-        population_size: int,
-        init_measured_ratio: float,
-        init_min_unmeasured: int,
-        genetic_num_iters: int,
-        genetic_mutate_prob: float,
-        genetic_max_fail_count: int,
-        eps_greedy: float,
+        population_size: int = 2048,
+        init_measured_ratio: float = 0.2,
+        init_min_unmeasured: int = 50,
+        genetic_num_iters: int = 4,
+        genetic_mutate_prob: float = 0.85,
+        genetic_max_fail_count: int = 10,
+        eps_greedy: float = 0.05,

Review Comment:
   If you never intend users to mess with these params, the new API looks fine.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r849903313


##########
python/tvm/meta_schedule/search_strategy/evolutionary_search.py:
##########
@@ -64,13 +64,13 @@ def __init__(
         *,
         num_trials_per_iter: int,
         max_trials_per_task: int,
-        population_size: int,
-        init_measured_ratio: float,
-        init_min_unmeasured: int,
-        genetic_num_iters: int,
-        genetic_mutate_prob: float,
-        genetic_max_fail_count: int,
-        eps_greedy: float,
+        population_size: int = 2048,
+        init_measured_ratio: float = 0.2,
+        init_min_unmeasured: int = 50,
+        genetic_num_iters: int = 4,
+        genetic_mutate_prob: float = 0.85,
+        genetic_max_fail_count: int = 10,
+        eps_greedy: float = 0.05,

Review Comment:
   Yes of course! Yeah as the principle that less frequent features should be put somewhere less significant, I simply hide it in a small config dict :-)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 merged pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 merged PR #10986:
URL: https://github.com/apache/tvm/pull/10986


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] masahi commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
masahi commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851881787


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   I see now that the value of `max_trials_per_task` is optional:
   
   ```
   max_trials_per_task: Optional[int] = None
   ```
   
   How about removing the explicit specification of ` max_trials_per_task` here and elsewhere in tests, if this value is not important? 
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] masahi commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
masahi commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r849897034


##########
python/tvm/meta_schedule/search_strategy/evolutionary_search.py:
##########
@@ -64,13 +64,13 @@ def __init__(
         *,
         num_trials_per_iter: int,
         max_trials_per_task: int,
-        population_size: int,
-        init_measured_ratio: float,
-        init_min_unmeasured: int,
-        genetic_num_iters: int,
-        genetic_mutate_prob: float,
-        genetic_max_fail_count: int,
-        eps_greedy: float,
+        population_size: int = 2048,
+        init_measured_ratio: float = 0.2,
+        init_min_unmeasured: int = 50,
+        genetic_num_iters: int = 4,
+        genetic_mutate_prob: float = 0.85,
+        genetic_max_fail_count: int = 10,
+        eps_greedy: float = 0.05,

Review Comment:
   Oh nice! I didn't notice that. `search_strategy_config` thing doesn't seem to be used in tests, can you add a trivial one (like your example above)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] masahi commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
masahi commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851881787


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   I see now that the value of `max_trials_per_task` is optional:
   
   ```
   max_trials_per_task: Optional[int] = None
   ```
   
   How about removing the explicit specification of ` max_trials_per_task` here and elsewhere in tests, if that's not important? 
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851888875


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   oh actually I just found myself implemented the logic in `create_strategy`...Let me update the docs to reflect this



##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   oh actually I just found myself implemented the logic in `create_strategy` already...Let me update the docs to reflect this



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on PR #10986:
URL: https://github.com/apache/tvm/pull/10986#issuecomment-1100591020

   @masahi @zxybazh comments addressed :-) To be extremely careful, please verify every test in `tests/python/unittest/test_meta_schedule_tune_relay/tir/te.py` before approving this PR. Thanks a lot!
   
   @michalpiszczek This API breaking change precisely follows our offload discussion on Tuesday. Having left it open for a few days, and will continue to keep you updated 👍 
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] zxybazh commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
zxybazh commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851882052


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   In this case, I think `max_trials_global` is the default for `max_trials_per_task`, except when we want to limit the trials for each task. In these cases, if the search space is very small, the evolutionary search strategy would do an early stopping; when we only want to do test, we can limit the `max_trials_global` to be a small number close to `num_trials_per_iter*task_num`. Therefore, I think it could be a good move to use `max_trials_global` as default to `max_trials_per_task` unless specified.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] zxybazh commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
zxybazh commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851095355


##########
python/tvm/meta_schedule/tune.py:
##########
@@ -449,95 +336,190 @@ def _mutator_probs(
         # pylint: enable=protected-access
         raise ValueError(f"Unsupported target: {target}")
 
-    @staticmethod
-    def _tune_context(
-        tune_context: Optional[TuneContext],
-        mod: IRModule,
-        target: Target,
-        config: SearchStrategyConfig,
-        task_name: str,
-        space_generator: Optional[FnSpaceGenerator],
-        sch_rules: Optional[FnScheduleRule],
-        postprocs: Optional[FnPostproc],
-        mutator_probs: Optional[FnMutatorProb],
-        num_threads: Optional[int],
-    ) -> TuneContext:
-        if tune_context is None:
-            return TuneContext(
-                mod=mod,
-                target=target,
-                # pylint: disable=protected-access
-                space_generator=Parse._space_generator(space_generator),
-                search_strategy=config.create_strategy(),
-                sch_rules=Parse._sch_rules(sch_rules, target),
-                postprocs=Parse._postproc(postprocs, target),
-                mutator_probs=Parse._mutator_probs(mutator_probs, target),
-                # pylint: enable=protected-access
-                task_name=task_name,
-                rand_state=-1,
-                num_threads=num_threads,
-            )
-        if not isinstance(tune_context, TuneContext):
-            raise TypeError(f"Expected `tune_context` to be TuneContext, but gets: {tune_context}")
-        return tune_context
 
-    @staticmethod
-    def _task_scheduler(
-        task_scheduler: Union[None, TaskScheduler, FnTaskScheduler],
-        tasks: List[TuneContext],
-        task_weights: List[float],
-        builder: Builder,
-        runner: Runner,
-        database: Database,
-        max_trials: int,
-        cost_model: CostModel,
-        measure_callbacks: List[MeasureCallback],
-    ):
-        if task_scheduler is None:
-            return GradientBased(
-                tasks=tasks,
-                task_weights=task_weights,
-                builder=builder,
-                runner=runner,
-                database=database,
-                max_trials=max_trials,
-                cost_model=cost_model,
-                measure_callbacks=measure_callbacks,
+class TuneConfig(NamedTuple):
+    """Configuration for tuning
+
+    Parameters
+    ----------
+    max_trials_global: int
+        Maximum number of trials to run.
+    num_trials_per_iter: int
+        Number of trials to run per iteration.
+    max_trials_per_task: int
+        Maximum number of trials to run per task.
+    task_scheduler: str
+        Task scheduler to use.
+        Valid options are: round_robin, gradient.
+    search_strategy: str
+        Search strategy to use.
+        Valid options are: evolutionary, replay_func, replay_trace.
+    task_scheduler_config: Dict[str, Any]
+        Configuration for task scheduler.
+    search_strategy_config: Dict[str, Any]
+        Configuration for search strategy.
+    """
+
+    max_trials_global: int
+    num_trials_per_iter: int
+    max_trials_per_task: Optional[int] = None
+    task_scheduler: str = "gradient"
+    strategy: str = "evolutionary"
+    task_scheduler_config: Dict[str, Any] = {}
+    search_strategy_config: Dict[str, Any] = {}
+
+    def create_strategy(self, **kwargs):
+        """Create search strategy from configuration"""
+        cls_tbl = {
+            "evolutionary": EvolutionarySearch,
+            "replay_func": ReplayFunc,
+            "replay_trace": ReplayTrace,
+        }
+        if self.strategy not in cls_tbl:
+            raise ValueError(
+                f"Invalid search strategy: {self.strategy}. "
+                "Valid options are: {}".format(", ".join(cls_tbl.keys()))
             )
-        if callable(task_scheduler):
-            return task_scheduler(
-                tasks,
-                task_weights,
-                builder,
-                runner,
-                database,
-                cost_model,
-                measure_callbacks,
+        max_trials_per_task = self.max_trials_per_task
+        if max_trials_per_task is None:
+            max_trials_per_task = self.max_trials_global
+        return cls_tbl[self.strategy](
+            num_trials_per_iter=self.num_trials_per_iter,
+            max_trials_per_task=max_trials_per_task,
+            **kwargs,
+            **self.search_strategy_config,
+        )
+
+    def create_task_scheduler(self, **kwargs):
+        """Create task scheduler from configuration"""
+        cls_tbl = {
+            "round_robin": RoundRobin,
+            "gradient": GradientBased,
+        }
+        if self.task_scheduler not in cls_tbl:
+            raise ValueError(
+                f"Invalid task scheduler: {self.task_scheduler}. "
+                "Valid options are: {}".format(", ".join(cls_tbl.keys()))
             )
-        if not isinstance(task_scheduler, TaskScheduler):
-            raise TypeError(
-                f"Expected `task_scheduler` to be TaskScheduler, but gets: {task_scheduler}"
+        return cls_tbl[self.task_scheduler](
+            max_trials=self.max_trials_global,
+            **kwargs,
+            **self.task_scheduler_config,
+        )
+
+
+def tune_extracted_tasks(
+    extracted_tasks: List[ExtractedTask],
+    config: TuneConfig,
+    work_dir: str,
+    *,
+    builder: Optional[Builder] = None,
+    runner: Optional[Runner] = None,
+    database: Optional[Database] = None,
+    cost_model: Optional[CostModel] = None,
+    measure_callbacks: Optional[List[MeasureCallback]] = None,
+    space: Optional[FnSpaceGenerator] = None,
+    sch_rules: Optional[FnScheduleRule] = None,
+    postprocs: Optional[FnPostproc] = None,
+    mutator_probs: Optional[FnMutatorProb] = None,
+    num_threads: Optional[int] = None,
+) -> Database:
+    """Tune extracted tasks with a given target.
+
+    Parameters
+    ----------
+    extracted_tasks : List[ExtractedTask]
+        The list of extraced tasks.
+    config : TuneConfig
+        The search strategy config.
+    work_dir : Optional[str]
+        The working directory to save intermediate results.
+    builder : Optional[Builder]
+        The builder to use.
+    runner : Optional[Runner]
+        The runner to use.
+    database : Optional[Database]
+        The database to use.
+    cost_model : Optional[CostModel]
+        The cost model to use.
+    measure_callbacks : Optional[List[MeasureCallback]]
+        The callbacks used during tuning.
+    task_scheduler : Optional[TaskScheduler]
+        The task scheduler to use.
+    space : Optional[FnSpaceGenerator]
+        The space generator to use.
+    sch_rules : Optional[FnScheduleRule]
+        The search rules to use.
+    postprocs : Optional[FnPostproc]
+        The postprocessors to use.
+    mutator_probs : Optional[FnMutatorProb]
+        The probability distribution to use different mutators.
+    num_threads : Optional[int]
+        The number of threads to use.
+
+    Returns
+    -------
+    database : Database
+        The database containing all the tuning results.
+
+    """
+    logger.info("Working directory: %s", work_dir)
+    # pylint: disable=protected-access
+    database = Parse._database(database, work_dir)
+    builder = Parse._builder(builder)
+    runner = Parse._runner(runner)
+    cost_model = Parse._cost_model(cost_model)
+    measure_callbacks = Parse._callbacks(measure_callbacks)
+    # parse the tuning contexts
+    tune_contexts = []
+    for task in extracted_tasks:
+        assert len(task.dispatched) == 1, "Only size 1 dispatched task list is supported for now"
+        tune_contexts.append(
+            TuneContext(
+                mod=Parse._mod(task.dispatched[0]),
+                target=task.target,
+                space_generator=Parse._space_generator(space),
+                search_strategy=config.create_strategy(),
+                sch_rules=Parse._sch_rules(sch_rules, task.target),
+                postprocs=Parse._postproc(postprocs, task.target),
+                mutator_probs=Parse._mutator_probs(mutator_probs, task.target),
+                task_name=task.name,
+                rand_state=-1,  # TODO: random seed

Review Comment:
   Shall we add random seed as part of the user input?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] masahi commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
masahi commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851880269


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   In general, do you recommend setting `max_trials_per_task` to be the same value as `max_trials_global`, or some arbitrary large number? This change makes me think that the value of `max_trials_per_task` doesn't matter much as long as it is sufficiently big.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] michalpiszczek commented on pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
michalpiszczek commented on PR #10986:
URL: https://github.com/apache/tvm/pull/10986#issuecomment-1100678705

   Thanks @junrushao1994 , this LGTM to me!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851887909


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   Let me improve this API by marking `max_trials_per_task` as optional



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851890224


##########
python/tvm/meta_schedule/tune.py:
##########
@@ -449,95 +336,189 @@ def _mutator_probs(
         # pylint: enable=protected-access
         raise ValueError(f"Unsupported target: {target}")
 
-    @staticmethod
-    def _tune_context(
-        tune_context: Optional[TuneContext],
-        mod: IRModule,
-        target: Target,
-        config: SearchStrategyConfig,
-        task_name: str,
-        space_generator: Optional[FnSpaceGenerator],
-        sch_rules: Optional[FnScheduleRule],
-        postprocs: Optional[FnPostproc],
-        mutator_probs: Optional[FnMutatorProb],
-        num_threads: Optional[int],
-    ) -> TuneContext:
-        if tune_context is None:
-            return TuneContext(
-                mod=mod,
-                target=target,
-                # pylint: disable=protected-access
-                space_generator=Parse._space_generator(space_generator),
-                search_strategy=config.create_strategy(),
-                sch_rules=Parse._sch_rules(sch_rules, target),
-                postprocs=Parse._postproc(postprocs, target),
-                mutator_probs=Parse._mutator_probs(mutator_probs, target),
-                # pylint: enable=protected-access
-                task_name=task_name,
-                rand_state=-1,
-                num_threads=num_threads,
-            )
-        if not isinstance(tune_context, TuneContext):
-            raise TypeError(f"Expected `tune_context` to be TuneContext, but gets: {tune_context}")
-        return tune_context
 
-    @staticmethod
-    def _task_scheduler(
-        task_scheduler: Union[None, TaskScheduler, FnTaskScheduler],
-        tasks: List[TuneContext],
-        task_weights: List[float],
-        builder: Builder,
-        runner: Runner,
-        database: Database,
-        max_trials: int,
-        cost_model: CostModel,
-        measure_callbacks: List[MeasureCallback],
-    ):
-        if task_scheduler is None:
-            return GradientBased(
-                tasks=tasks,
-                task_weights=task_weights,
-                builder=builder,
-                runner=runner,
-                database=database,
-                max_trials=max_trials,
-                cost_model=cost_model,
-                measure_callbacks=measure_callbacks,
+class TuneConfig(NamedTuple):
+    """Configuration for tuning
+
+    Parameters
+    ----------
+    max_trials_global: int
+        Maximum number of trials to run.
+    num_trials_per_iter: int
+        Number of trials to run per iteration.
+    max_trials_per_task: int
+        Maximum number of trials to run per task.
+    task_scheduler: str
+        Task scheduler to use.
+        Valid options are: round_robin, gradient.
+    search_strategy: str
+        Search strategy to use.
+        Valid options are: evolutionary, replay_func, replay_trace.
+    task_scheduler_config: Dict[str, Any]
+        Configuration for task scheduler.
+    search_strategy_config: Dict[str, Any]
+        Configuration for search strategy.
+    """
+
+    max_trials_global: int
+    num_trials_per_iter: int
+    max_trials_per_task: Optional[int] = None
+    task_scheduler: str = "gradient"
+    strategy: str = "evolutionary"
+    task_scheduler_config: Dict[str, Any] = {}
+    search_strategy_config: Dict[str, Any] = {}
+

Review Comment:
   This is beyond the scope of this PR, but is definitely a good item for future work :-)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] zxybazh commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
zxybazh commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851890813


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   IMHO we should still set `max_trials_global` as something like `2000` here and add comment `suggested 20k or 1k * num of subgraphs` beside because this is still a functionality test. I will send a PR for meta schedule tutorial as Masa suggested later this week and that would be a better example to show case our interface usage.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on PR #10986:
URL: https://github.com/apache/tvm/pull/10986#issuecomment-1097414387

   @masahi @zxybazh @michalpiszczek @mbrookhart would love to ask you guys to review this PR given it's going to be breaking the existing tune_relay interface


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r849873574


##########
python/tvm/meta_schedule/search_strategy/evolutionary_search.py:
##########
@@ -64,13 +64,13 @@ def __init__(
         *,
         num_trials_per_iter: int,
         max_trials_per_task: int,
-        population_size: int,
-        init_measured_ratio: float,
-        init_min_unmeasured: int,
-        genetic_num_iters: int,
-        genetic_mutate_prob: float,
-        genetic_max_fail_count: int,
-        eps_greedy: float,
+        population_size: int = 2048,
+        init_measured_ratio: float = 0.2,
+        init_min_unmeasured: int = 50,
+        genetic_num_iters: int = 4,
+        genetic_mutate_prob: float = 0.85,
+        genetic_max_fail_count: int = 10,
+        eps_greedy: float = 0.05,

Review Comment:
   Hey Masa, thanks for your feedback! I'm trying to understand this usecase you suggested here. Would you mind sharing an example for me to act on? Thanks a lot!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] junrushao1994 commented on pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
junrushao1994 commented on PR #10986:
URL: https://github.com/apache/tvm/pull/10986#issuecomment-1101182152

   Thanks @masahi @zxybazh @michalpiszczek for the careful review and discussion!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] masahi commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
masahi commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851883400


##########
tests/python/unittest/test_meta_schedule_tune_relay.py:
##########
@@ -144,14 +144,19 @@ def test_meta_schedule_tune_relay(
             mod=mod,
             params=params,
             target=target,
-            config=ReplayTraceConfig(
+            config=TuneConfig(
+                strategy="evolutionary",
                 num_trials_per_iter=32,
-                max_trials_per_task=32,
+                max_trials_per_task=20000,

Review Comment:
   yeah I mean, if this value is optional, at least one test should exercise that scenario / code path.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [tvm] zxybazh commented on a diff in pull request #10986: [MetaSchedule][Refactor] Introduce TuneConfig

Posted by GitBox <gi...@apache.org>.
zxybazh commented on code in PR #10986:
URL: https://github.com/apache/tvm/pull/10986#discussion_r851891047


##########
python/tvm/meta_schedule/tune.py:
##########
@@ -449,95 +336,189 @@ def _mutator_probs(
         # pylint: enable=protected-access
         raise ValueError(f"Unsupported target: {target}")
 
-    @staticmethod
-    def _tune_context(
-        tune_context: Optional[TuneContext],
-        mod: IRModule,
-        target: Target,
-        config: SearchStrategyConfig,
-        task_name: str,
-        space_generator: Optional[FnSpaceGenerator],
-        sch_rules: Optional[FnScheduleRule],
-        postprocs: Optional[FnPostproc],
-        mutator_probs: Optional[FnMutatorProb],
-        num_threads: Optional[int],
-    ) -> TuneContext:
-        if tune_context is None:
-            return TuneContext(
-                mod=mod,
-                target=target,
-                # pylint: disable=protected-access
-                space_generator=Parse._space_generator(space_generator),
-                search_strategy=config.create_strategy(),
-                sch_rules=Parse._sch_rules(sch_rules, target),
-                postprocs=Parse._postproc(postprocs, target),
-                mutator_probs=Parse._mutator_probs(mutator_probs, target),
-                # pylint: enable=protected-access
-                task_name=task_name,
-                rand_state=-1,
-                num_threads=num_threads,
-            )
-        if not isinstance(tune_context, TuneContext):
-            raise TypeError(f"Expected `tune_context` to be TuneContext, but gets: {tune_context}")
-        return tune_context
 
-    @staticmethod
-    def _task_scheduler(
-        task_scheduler: Union[None, TaskScheduler, FnTaskScheduler],
-        tasks: List[TuneContext],
-        task_weights: List[float],
-        builder: Builder,
-        runner: Runner,
-        database: Database,
-        max_trials: int,
-        cost_model: CostModel,
-        measure_callbacks: List[MeasureCallback],
-    ):
-        if task_scheduler is None:
-            return GradientBased(
-                tasks=tasks,
-                task_weights=task_weights,
-                builder=builder,
-                runner=runner,
-                database=database,
-                max_trials=max_trials,
-                cost_model=cost_model,
-                measure_callbacks=measure_callbacks,
+class TuneConfig(NamedTuple):
+    """Configuration for tuning
+
+    Parameters
+    ----------
+    max_trials_global: int
+        Maximum number of trials to run.
+    num_trials_per_iter: int
+        Number of trials to run per iteration.
+    max_trials_per_task: int
+        Maximum number of trials to run per task.
+    task_scheduler: str
+        Task scheduler to use.
+        Valid options are: round_robin, gradient.
+    search_strategy: str
+        Search strategy to use.
+        Valid options are: evolutionary, replay_func, replay_trace.
+    task_scheduler_config: Dict[str, Any]
+        Configuration for task scheduler.
+    search_strategy_config: Dict[str, Any]
+        Configuration for search strategy.
+    """
+
+    max_trials_global: int
+    num_trials_per_iter: int
+    max_trials_per_task: Optional[int] = None
+    task_scheduler: str = "gradient"
+    strategy: str = "evolutionary"
+    task_scheduler_config: Dict[str, Any] = {}
+    search_strategy_config: Dict[str, Any] = {}
+

Review Comment:
   Sure, I'll add that to my backlog.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org