Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[M3c][Meta Schedule] Measure Callbacks #498

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions include/tvm/meta_schedule/measure_callback.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
* 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.
*/

#ifndef TVM_META_SCHEDULE_MEASURE_CALLBACK_H_
#define TVM_META_SCHEDULE_MEASURE_CALLBACK_H_

#include <tvm/meta_schedule/builder.h>
#include <tvm/meta_schedule/runner.h>
#include <tvm/meta_schedule/search_strategy.h>
#include <tvm/tir/schedule/schedule.h>

namespace tvm {
namespace meta_schedule {

class TuneContext;

/*! \brief Rules to apply after measure results is available. */
class MeasureCallbackNode : public runtime::Object {
public:
/*! \brief Virtual destructor. */
virtual ~MeasureCallbackNode() = default;

void VisitAttrs(tvm::AttrVisitor* v) {}

/*!
* \brief The function type of `InitializeWithTuneContext` method.
* \param tune_context The tuning context for initialization.
*/
virtual void InitializeWithTuneContext(const TuneContext& context) = 0;

/*!
* \brief Apply a measure callback rule with given arguments.
* \param measure_candidates The measure candidates.
* \param builds The builder results by building the measure candidates.
* \param results The runner results by running the built measure candidates.
* \return Whether the measure callback was successfully applied.
*/
virtual bool Apply(const Array<MeasureCandidate>& measure_candidates, //
zxybazh marked this conversation as resolved.
Show resolved Hide resolved
const Array<BuilderResult>& builds, //
const Array<RunnerResult>& results) = 0;

static constexpr const char* _type_key = "meta_schedule.MeasureCallback";
TVM_DECLARE_BASE_OBJECT_INFO(MeasureCallbackNode, Object);
};

/*! \brief The measure callback with customized methods on the python-side. */
class PyMeasureCallbackNode : public MeasureCallbackNode {
public:
/*!
* \brief The function type of `InitializeWithTuneContext` method.
* \param tune_context The tuning context for initialization.
*/
using FInitializeWithTuneContext = runtime::TypedPackedFunc<void(const TuneContext&)>;
/*!
* \brief Apply a measure callback to the given schedule.
* \param measure_candidates The measure candidates.
* \param builds The builder results by building the measure candidates.
* \param results The runner results by running the built measure candidates.
* \return Whether the measure callback was successfully applied.
*/
using FApply =
runtime::TypedPackedFunc<bool(const Array<MeasureCandidate>& measure_candidates, //
const Array<BuilderResult>& builds, //
const Array<RunnerResult>& results)>;
/*!
* \brief Get the measure callback function as string with name.
* \return The string of the measure callback function.
*/
using FAsString = runtime::TypedPackedFunc<String()>;

/*! \brief The packed function to the `InitializeWithTuneContext` funcion. */
FInitializeWithTuneContext f_initialize_with_tune_context;
/*! \brief The packed function to the `Apply` funcion. */
FApply f_apply;
/*! \brief The packed function to the `AsString` funcion. */
FAsString f_as_string;

void VisitAttrs(tvm::AttrVisitor* v) {
// `f_initialize_with_tune_context` is not visited
// `f_apply` is not visited
// `f_as_string` is not visited
}

void InitializeWithTuneContext(const TuneContext& context) final {
this->f_initialize_with_tune_context(context);
}

bool Apply(const Array<MeasureCandidate>& measure_candidates, //
const Array<BuilderResult>& builds, //
const Array<RunnerResult>& results) final {
return this->f_apply(measure_candidates, builds, results);
}

static constexpr const char* _type_key = "meta_schedule.PyMeasureCallback";
TVM_DECLARE_FINAL_OBJECT_INFO(PyMeasureCallbackNode, MeasureCallbackNode);
};

/*!
* \brief Managed reference to MeasureCallbackNode
* \sa MeasureCallbackNode
*/
class MeasureCallback : public runtime::ObjectRef {
public:
/*!
* \brief Create a measure callback with customized methods on the python-side.
* \param f_initialize_with_tune_context The packed function of `InitializeWithTuneContext`.
* \param f_apply The packed function of `Apply`.
* \return The measure callback created.
*/
TVM_DLL static MeasureCallback PyMeasureCallback(
PyMeasureCallbackNode::FInitializeWithTuneContext f_initialize_with_tune_context, //
PyMeasureCallbackNode::FApply f_apply, //
PyMeasureCallbackNode::FAsString f_as_string);
TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(MeasureCallback, ObjectRef, MeasureCallbackNode);
};

} // namespace meta_schedule
} // namespace tvm

#endif // TVM_META_SCHEDULE_MEASURE_CALLBACK_H_
20 changes: 20 additions & 0 deletions python/tvm/meta_schedule/measure_callback/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 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.
"""
The tvm.meta_schedule.measure_callback package.
"""
from .measure_callback import MeasureCallback, PyMeasureCallback
104 changes: 104 additions & 0 deletions python/tvm/meta_schedule/measure_callback/measure_callback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# 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.
"""Meta Schedule MeasureCallback."""

from typing import TYPE_CHECKING, List

from tvm._ffi import register_object
from tvm.runtime import Object
from tvm.tir.schedule import Schedule
from tvm.meta_schedule.search_strategy import MeasureCandidate
from tvm.meta_schedule.builder import BuilderResult
from tvm.meta_schedule.runner import RunnerResult
from tvm.meta_schedule.utils import _get_hex_address

from .. import _ffi_api

if TYPE_CHECKING:
from ..tune_context import TuneContext


@register_object("meta_schedule.MeasureCallback")
class MeasureCallback(Object):
"""Rules to apply after measure results is available."""

def initialize_with_tune_context(self, tune_context: "TuneContext") -> None:
"""Initialize the measure callback with a tune context.

Parameters
----------
tune_context : TuneContext
The tuning context for initializing the measure callback.
"""
_ffi_api.MeasureCallbackInitializeWithTuneContext( # type: ignore # pylint: disable=no-member
self, tune_context
)

def apply(
self,
measure_candidates: List[MeasureCandidate],
builds: List[BuilderResult],
results: List[RunnerResult],
) -> bool:
"""Apply a measure callback to the given schedule.

Parameters
----------
measure_candidats: List[MeasureCandidate]
The measure candidates.
builds: List[BuilderResult]
The builder results by building the measure candidates.
results: List[RunnerResult]
The runner results by running the built measure candidates.

Returns
-------
result : bool
Whether the measure callback was successfully applied.
"""
return _ffi_api.MeasureCallbackApply(self, measure_candidates, builds, results)


@register_object("meta_schedule.PyMeasureCallback")
class PyMeasureCallback(MeasureCallback):
"""An abstract MeasureCallback with customized methods on the python-side."""

def __init__(self):
"""Constructor."""

def f_initialize_with_tune_context(tune_context: "TuneContext") -> None:
self.initialize_with_tune_context(tune_context)

def f_apply(
measure_candidates: List[MeasureCandidate],
builds: List[BuilderResult],
results: List[RunnerResult],
) -> bool:
return self.apply(measure_candidates, builds, results)

def f_as_string() -> str:
return str(self)

self.__init_handle_by_constructor__(
_ffi_api.MeasureCallbackPyMeasureCallback, # type: ignore # pylint: disable=no-member
f_initialize_with_tune_context,
f_apply,
f_as_string,
)

def __str__(self) -> str:
return f"PyMeasureCallback({_get_hex_address(self.handle)})"
2 changes: 1 addition & 1 deletion python/tvm/meta_schedule/mutator/mutator.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def initialize_with_tune_context(self, tune_context: "TuneContext") -> None:
Parameters
----------
tune_context : TuneContext
The tuning context for initializing the design space generator.
The tuning context for initializing the mutator.
"""
_ffi_api.MutatorInitializeWithTuneContext( # type: ignore # pylint: disable=no-member
self, tune_context
Expand Down
2 changes: 1 addition & 1 deletion python/tvm/meta_schedule/postproc/postproc.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def initialize_with_tune_context(self, tune_context: "TuneContext") -> None:
Parameters
----------
tune_context : TuneContext
The tuning context for initializing the design space generator.
The tuning context for initializing the post processing.
"""
_ffi_api.PostprocInitializeWithTuneContext( # type: ignore # pylint: disable=no-member
self, tune_context
Expand Down
2 changes: 1 addition & 1 deletion python/tvm/meta_schedule/schedule_rule/schedule_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def initialize_with_tune_context(self, tune_context: "TuneContext") -> None:
Parameters
----------
tune_context : TuneContext
The tuning context for initializing the design space generator.
The tuning context for initializing the schedule rule.
"""
_ffi_api.ScheduleRuleInitializeWithTuneContext( # type: ignore # pylint: disable=no-member
self, tune_context
Expand Down
2 changes: 1 addition & 1 deletion python/tvm/meta_schedule/search_strategy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@
to generate measure candidates.
"""

from .search_strategy import SearchStrategy, PySearchStrategy
from .search_strategy import SearchStrategy, PySearchStrategy, MeasureCandidate
from .replay_trace import ReplayTrace
from .replay_func import ReplayFunc
55 changes: 55 additions & 0 deletions src/meta_schedule/measure_callback/measure_callback.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* 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.
*/
#include "../utils.h"

namespace tvm {
namespace meta_schedule {

MeasureCallback MeasureCallback::PyMeasureCallback(
PyMeasureCallbackNode::FInitializeWithTuneContext f_initialize_with_tune_context, //
PyMeasureCallbackNode::FApply f_apply, //
PyMeasureCallbackNode::FAsString f_as_string) {
ObjectPtr<PyMeasureCallbackNode> n = make_object<PyMeasureCallbackNode>();
n->f_initialize_with_tune_context = std::move(f_initialize_with_tune_context);
n->f_apply = std::move(f_apply);
n->f_as_string = std::move(f_as_string);
return MeasureCallback(n);
}

TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<PyMeasureCallbackNode>([](const ObjectRef& n, ReprPrinter* p) {
const auto* self = n.as<PyMeasureCallbackNode>();
ICHECK(self);
PyMeasureCallbackNode::FAsString f_as_string = (*self).f_as_string;
ICHECK(f_as_string != nullptr);
p->stream << f_as_string();
});

TVM_REGISTER_OBJECT_TYPE(MeasureCallbackNode);
TVM_REGISTER_NODE_TYPE(PyMeasureCallbackNode);

TVM_REGISTER_GLOBAL("meta_schedule.MeasureCallbackInitializeWithTuneContext")
.set_body_method<MeasureCallback>(&MeasureCallbackNode::InitializeWithTuneContext);
TVM_REGISTER_GLOBAL("meta_schedule.MeasureCallbackApply")
.set_body_method<MeasureCallback>(&MeasureCallbackNode::Apply);
TVM_REGISTER_GLOBAL("meta_schedule.MeasureCallbackPyMeasureCallback")
.set_body_typed(MeasureCallback::PyMeasureCallback);

} // namespace meta_schedule
} // namespace tvm
1 change: 1 addition & 0 deletions src/meta_schedule/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include <tvm/meta_schedule/arg_info.h>
#include <tvm/meta_schedule/builder.h>
#include <tvm/meta_schedule/database.h>
#include <tvm/meta_schedule/measure_callback.h>
#include <tvm/meta_schedule/mutator.h>
#include <tvm/meta_schedule/postproc.h>
#include <tvm/meta_schedule/runner.h>
Expand Down
Loading