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

[MetaScheduleRefactor] Annotate&Unannotate #505

Merged
merged 7 commits into from
Nov 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
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
27 changes: 27 additions & 0 deletions include/tvm/tir/schedule/schedule.h
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,33 @@ class ScheduleNode : public runtime::Object {
int offset) = 0;
/******** Schedule: Blockize & Tensorize ********/
/******** Schedule: Annotation ********/
/*!
* \brief Annotate a loop with a key value pair
* \param loop The loop to be annotated
* \param ann_key The annotation key
* \param ann_val The annotation value, a string or a ExprRV
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not for nullptr

*/
virtual void Annotate(const LoopRV& loop_rv, const String& ann_key, const ObjectRef& ann_val) = 0;
/*!
* \brief Annotate a block with a key value pair
* \param loop The block to be annotated
* \param ann_key The annotation key
* \param ann_val The annotation value, a string or a ExprRV
*/
virtual void Annotate(const BlockRV& block_rv, const String& ann_key,
const ObjectRef& ann_val) = 0;
spectrometerHBH marked this conversation as resolved.
Show resolved Hide resolved
/*!
* \brief Unannotate a loop's annotation with key ann_key
* \param loop The loop to be unannotated
* \param ann_key The annotation key
*/
virtual void Unannotate(const LoopRV& loop_rv, const String& ann_key) = 0;
/*!
* \brief Unannotate a block's annotation with key ann_key
* \param loop The block to be unannotated
* \param ann_key The annotation key
*/
virtual void Unannotate(const BlockRV& block_rv, const String& ann_key) = 0;
/******** Schedule: Misc ********/
/*! \brief A no-op that marks the start of postprocessing phase of scheduling */
virtual void EnterPostproc() = 0;
Expand Down
4 changes: 2 additions & 2 deletions python/tvm/script/tir/scope_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

import synr
import tvm.tir
from tvm.runtime import Object
from tvm.runtime import Object, String
from tvm.ir import Span, Range
from tvm.tir import Stmt, PrimExpr, IterVar, Var, Buffer, BufferRegion, ForKind

Expand Down Expand Up @@ -485,7 +485,7 @@ def create_loop_info(
self.annotations: Mapping[str, Object] = {}
if annotations is not None:
self.annotations = {
key: tvm.tir.StringImm(val) if isinstance(val, str) else val
key: String(val) if isinstance(val, str) else val
for key, val in annotations.items()
}

Expand Down
4 changes: 2 additions & 2 deletions python/tvm/script/tir/special_stmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from tvm.ir.expr import PrimExpr, Range

import tvm.tir
from tvm.runtime import Object
from tvm.runtime import Object, String
from tvm import te
from tvm.ir import Span
from tvm.tir import IntImm, IterVar
Expand Down Expand Up @@ -389,7 +389,7 @@ def block_attr(attrs: Mapping[str, Object], span: Span = None):
span,
)
attrs = {
key: tvm.tir.StringImm(val) if isinstance(val, str) else val
key: String(val) if isinstance(val, str) else val
for key, val in attrs.items()
}
block_scope.annotations = attrs
Expand Down
43 changes: 42 additions & 1 deletion python/tvm/tir/schedule/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@
# under the License.
"""The TensorIR schedule class"""
from typing import Dict, List, Optional, Union
from typing_extensions import Annotated

from tvm._ffi import register_object as _register_object
from tvm.error import TVMError, register_error
from tvm.ir import IRModule, PrimExpr
from tvm.runtime import Object
from tvm.runtime import Object, String
from tvm.tir import Block, For, IntImm, PrimFunc
from tvm.tir.expr import FloatImm

from . import _ffi_api
from .state import ScheduleState, StmtSRef, _parse_debug_mask, _parse_mod
Expand Down Expand Up @@ -1656,6 +1658,45 @@ def after_storage_align(a: T.handle, c: T.handle) -> None:

########## Schedule: Annotation ##########

def annotate(
self,
block_or_loop: Union[BlockRV, LoopRV],
ann_key: str,
ann_val: Union[str, int, float, ExprRV],
) -> None:
"""Annotate a block/loop with a key value pair

Parameters
----------
block_or_loop: Union[BlockRV, LoopRV]
The block/loop to be annotated
ann_key : str
The annotation key
ann_val : Union[str, int, float, ExprRV]
The annotation value
"""
if isinstance(ann_val, str):
ann_val = String(ann_val)
elif isinstance(ann_val, int):
ann_val = IntImm("int32", ann_val)
elif isinstance(ann_val, float):
ann_val = FloatImm("float32", ann_val)
_ffi_api.ScheduleAnnotate( # pylint: disable=no-member
self, block_or_loop, ann_key, ann_val
)

def unannotate(self, block_or_loop: Union[BlockRV, LoopRV], ann_key: str) -> None:
"""Unannotate a block/loop's annotation with key ann_key

Parameters
----------
block_or_loop: Union[BlockRV, LoopRV]
The block/loop to be unannotated
ann_key : str
The annotation key
"""
_ffi_api.ScheduleUnannotate(self, block_or_loop, ann_key) # pylint: disable=no-member

########## Schedule: Misc ##########

def enter_postproc(self) -> None:
Expand Down
53 changes: 53 additions & 0 deletions src/tir/schedule/concrete_schedule.cc
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,59 @@ BlockRV ConcreteScheduleNode::RFactor(const LoopRV& loop_rv, int factor_axis) {

/******** Schedule: Blockize & Tensorize ********/
/******** Schedule: Annotation ********/

void ConcreteScheduleNode::Annotate(const LoopRV& loop_rv, const String& ann_key,
const ObjectRef& ann_val) {
TVM_TIR_SCHEDULE_BEGIN();
if (const auto* str = ann_val.as<StringObj>()) {
tir::Annotate(state_, this->GetSRef(loop_rv), ann_key, GetRef<String>(str));
} else if (const auto* expr = ann_val.as<PrimExprNode>()) {
ICHECK(ann_val.as<tir::StringImmNode>() == nullptr)
<< "TypeError: runtime::String is expected, but gets tir::StringImm";
tir::Annotate(state_, this->GetSRef(loop_rv), ann_key, this->Get(GetRef<PrimExpr>(expr)));
} else {
LOG(FATAL)
<< "TypeError: Only strings, integers, floats and ExprRVs are supported for now, but gets: "
<< ann_val->GetTypeKey();
throw;
}
this->state_->DebugVerify();
TVM_TIR_SCHEDULE_END("annotate", this->error_render_level_);
}

void ConcreteScheduleNode::Unannotate(const LoopRV& loop_rv, const String& ann_key) {
TVM_TIR_SCHEDULE_BEGIN();
tir::Unannotate(state_, this->GetSRef(loop_rv), ann_key);
this->state_->DebugVerify();
TVM_TIR_SCHEDULE_END("unannotate", this->error_render_level_);
}

void ConcreteScheduleNode::Annotate(const BlockRV& block_rv, const String& ann_key,
const ObjectRef& ann_val) {
TVM_TIR_SCHEDULE_BEGIN();
if (const auto* str = ann_val.as<StringObj>()) {
tir::Annotate(state_, this->GetSRef(block_rv), ann_key, GetRef<String>(str));
} else if (const auto* expr = ann_val.as<PrimExprNode>()) {
ICHECK(ann_val.as<tir::StringImmNode>() == nullptr)
<< "TypeError: runtime::String is expected, but gets tir::StringImm";
tir::Annotate(state_, this->GetSRef(block_rv), ann_key, this->Get(GetRef<PrimExpr>(expr)));
} else {
LOG(FATAL)
<< "TypeError: Only strings, integers, floats and ExprRVs are supported for now, but gets: "
<< ann_val->GetTypeKey();
throw;
}
this->state_->DebugVerify();
TVM_TIR_SCHEDULE_END("annotate", this->error_render_level_);
}

void ConcreteScheduleNode::Unannotate(const BlockRV& loop_rv, const String& ann_key) {
TVM_TIR_SCHEDULE_BEGIN();
tir::Unannotate(state_, this->GetSRef(loop_rv), ann_key);
this->state_->DebugVerify();
TVM_TIR_SCHEDULE_END("unannotate", this->error_render_level_);
}

/******** Schedule: Misc ********/

} // namespace tir
Expand Down
4 changes: 4 additions & 0 deletions src/tir/schedule/concrete_schedule.h
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ class ConcreteScheduleNode : public ScheduleNode {
int offset) override;
/******** Schedule: Blockize & Tensorize ********/
/******** Schedule: Annotation ********/
void Annotate(const LoopRV& loop_rv, const String& ann_key, const ObjectRef& ann_val) override;
void Unannotate(const LoopRV& loop_rv, const String& ann_key) override;
void Annotate(const BlockRV& loop_rv, const String& ann_key, const ObjectRef& ann_val) override;
void Unannotate(const BlockRV& loop_rv, const String& ann_key);
/******** Schedule: Misc ********/
void EnterPostproc() override {}

Expand Down
16 changes: 16 additions & 0 deletions src/tir/schedule/primitive.h
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,22 @@ TVM_DLL void StorageAlign(ScheduleState self, const StmtSRef& block_sref, int bu

/******** Schedule: Blockize & Tensorize ********/
/******** Schedule: Annotation ********/
/*!
* \brief Annotate a block/loop with a key value pair
* \param self The state of the schedule
* \param sref The block/loop sref to be annotated
* \param ann_key The annotation key
* \param ann_val The annotation value
*/
TVM_DLL void Annotate(ScheduleState self, const StmtSRef& sref, const String& ann_key,
const ObjectRef& ann_val);
/*!
* \brief Unannotate a block/loop's annotation with key ann_key
* \param self The state of the schedule
* \param sref The block/loop to be unannotated
* \param ann_key The annotation key
*/
TVM_DLL void Unannotate(ScheduleState self, const StmtSRef& sref, const String& ann_key);
/******** Schedule: Misc ********/

} // namespace tir
Expand Down
168 changes: 168 additions & 0 deletions src/tir/schedule/primitive/annotate.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* 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 tir {

void Annotate(ScheduleState self, const StmtSRef& sref, const String& ann_key,
const ObjectRef& ann_val) {
// Extract annotation
const Map<String, ObjectRef>* annotations = nullptr;
if (const auto* loop = sref->StmtAs<ForNode>()) {
annotations = &loop->annotations;
} else if (const auto* block = sref->StmtAs<BlockNode>()) {
annotations = &block->annotations;
} else {
LOG(FATAL) << "TypeError: Unknown type of sref: " << sref->stmt->GetTypeKey();
}
// Check if the annotation already exists
if (annotations->find(ann_key) != annotations->end()) {
return;
}
// Add the new annotation
Map<String, ObjectRef> new_ann(*annotations);
new_ann.Set(ann_key, ann_val);
// Create the new stmt
if (const auto* loop = sref->StmtAs<ForNode>()) {
ObjectPtr<ForNode> n = make_object<ForNode>(*loop);
n->annotations = std::move(new_ann);
self->Replace(sref, For(n), {});
} else if (const auto* block = sref->StmtAs<BlockNode>()) {
ObjectPtr<BlockNode> n = make_object<BlockNode>(*block);
n->annotations = std::move(new_ann);
Block p(n);
self->Replace(sref, p, {{GetRef<Block>(block), p}});
} else {
LOG(FATAL) << "TypeError: Unknown type of sref: " << sref->stmt->GetTypeKey();
throw;
}
}

void Unannotate(ScheduleState self, const StmtSRef& sref, const String& ann_key) {
// Extract annotation
const Map<String, ObjectRef>* annotations = nullptr;
if (const auto* loop = sref->StmtAs<tir::ForNode>()) {
annotations = &loop->annotations;
} else if (const auto* block = sref->StmtAs<tir::BlockNode>()) {
annotations = &block->annotations;
} else {
LOG(FATAL) << "TypeError: Unknown type of sref: " << sref->stmt->GetTypeKey();
}
// Remove the annotation
ICHECK(annotations->find(ann_key) != annotations->end())
<< "IndexError: Cannot find annotation key: " << ann_key;
Map<String, ObjectRef> new_ann(*annotations);
new_ann.erase(ann_key);
// Create the new stmt
if (const auto* loop = sref->StmtAs<tir::ForNode>()) {
ObjectPtr<tir::ForNode> n = make_object<tir::ForNode>(*loop);
n->annotations = std::move(new_ann);
self->Replace(sref, tir::For(n), {});
} else if (const auto* block = sref->StmtAs<tir::BlockNode>()) {
ObjectPtr<tir::BlockNode> n = make_object<tir::BlockNode>(*block);
n->annotations = std::move(new_ann);
tir::Block p(n);
self->Replace(sref, p, {{GetRef<tir::Block>(block), p}});
} else {
LOG(FATAL) << "TypeError: Unknown type of sref: " << sref->stmt->GetTypeKey();
throw;
}
}

struct AnnotateTraits : public UnpackedInstTraits<AnnotateTraits> {
static constexpr const char* kName = "Annotate";
static constexpr bool kIsPure = false;

private:
static constexpr size_t kNumInputs = 2;
static constexpr size_t kNumAttrs = 1;
static constexpr size_t kNumDecisions = 0;

static void UnpackedApplyToSchedule(Schedule sch, ObjectRef block_or_loop_rv, ObjectRef ann_val,
String ann_key) {
if (const auto* block = block_or_loop_rv.as<BlockRVNode>()) {
return sch->Annotate(GetRef<BlockRV>(block), ann_key, ann_val);
}
if (const auto* loop = block_or_loop_rv.as<LoopRVNode>()) {
return sch->Annotate(GetRef<LoopRV>(loop), ann_key, ann_val);
}
LOG(FATAL) << "TypeError: Expected Block or Loop, but gets: " << block_or_loop_rv->GetTypeKey();
throw;
}

static String UnpackedAsPython(Array<String> outputs, ObjectRef block_or_loop_rv,
ObjectRef ann_val, String ann_key) {
PythonAPICall py("annotate");
py.Input("block_or_loop", block_or_loop_rv);
py.Input("ann_key", ann_key);
if (const auto* int_imm = ann_val.as<IntImmNode>()) {
py.Input("ann_val", std::to_string(int_imm->value));
} else if (const auto* str_imm = ann_val.as<StringObj>()) {
py.Input("ann_val", GetRef<String>(str_imm));
} else if (const auto* expr = ann_val.as<PrimExprNode>()) {
std::ostringstream os;
os << GetRef<PrimExpr>(expr);
py.Input("ann_val", os.str());
} else {
LOG(FATAL) << "TypeError: Cannot handle type: " << ann_val->GetTypeKey();
throw;
}
return py.Str();
}

friend struct UnpackedInstTraits;
};

struct UnannotateTraits : public UnpackedInstTraits<UnannotateTraits> {
static constexpr const char* kName = "Unannotate";
static constexpr bool kIsPure = false;

private:
static constexpr size_t kNumInputs = 1;
static constexpr size_t kNumAttrs = 1;
static constexpr size_t kNumDecisions = 0;

static void UnpackedApplyToSchedule(Schedule sch, ObjectRef block_or_loop_rv, String ann_key) {
if (const auto* block = block_or_loop_rv.as<BlockRVNode>()) {
return sch->Unannotate(GetRef<BlockRV>(block), ann_key);
}
if (const auto* loop = block_or_loop_rv.as<LoopRVNode>()) {
return sch->Unannotate(GetRef<LoopRV>(loop), ann_key);
}
LOG(FATAL) << "TypeError: Expected Block or Loop, but gets: " << block_or_loop_rv->GetTypeKey();
throw;
}

static String UnpackedAsPython(Array<String> outputs, ObjectRef block_or_loop_rv,
String ann_key) {
PythonAPICall py("unannotate");
py.Input("block_or_loop", block_or_loop_rv);
py.Input("ann_key", ann_key);
return py.Str();
}

friend struct UnpackedInstTraits;
};

TVM_REGISTER_INST_KIND_TRAITS(AnnotateTraits);
TVM_REGISTER_INST_KIND_TRAITS(UnannotateTraits);

} // namespace tir
} // namespace tvm
Loading