Skip to content

Commit

Permalink
[Relay] Continuation Passing Style (apache#3456)
Browse files Browse the repository at this point in the history
* save

add

me find type checker problem

save

save

lint

do

lint

reset ti

add some doc

add failed test case

add recursion for cps

add recursion for cps

fix pytest

lint

save

fix test error

lint

save

fix error

* fix rebase

* fix

* fix test

* lint

* lint

* restore rewriteannotationops

* do
  • Loading branch information
MarisaKirisame authored and wweic committed Jul 11, 2019
1 parent 43206d7 commit e5154d4
Show file tree
Hide file tree
Showing 19 changed files with 840 additions and 157 deletions.
11 changes: 0 additions & 11 deletions include/tvm/relay/analysis.h
Original file line number Diff line number Diff line change
Expand Up @@ -251,17 +251,6 @@ TVM_DLL tvm::Array<TypeVar> AllTypeVars(const Expr& expr, const Module& mod);
*/
TVM_DLL tvm::Array<TypeVar> AllTypeVars(const Type& t, const Module& mod);

/*!
* \brief Rewrite the annotated program.
*
* \param expr The expression.
* \param fallback_device The fallback device which is the default device for
* operators without annotation.
*
* \return The updated program.
*/
TVM_DLL Expr RewriteAnnotatedOps(const Expr& expr, int fallback_device);

/*!
* \brief Collect the device mapping information of each expression.
*
Expand Down
67 changes: 67 additions & 0 deletions include/tvm/relay/transform.h
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,22 @@ TVM_DLL Pass RewriteAnnotatedOps(int fallback_device);
*/
TVM_DLL Pass ToANormalForm();

/*!
* \brief Turn an expression into continuation passing style(CPS).
*
* CPS mean that every function will, instead of returning the result directly,
* be passed down an extra function (called the continuation) as argument,
* and pass the result to the continuation instead.
*
* Thus, every function call has to be passed an extra argument
* that represent the rest of the computation (Hence the name of continuation).
*
* Similarly, all other compute will be wrapped and call the continuation as well.
*
* \return the pass.
*/
TVM_DLL Pass ToCPS();

/*!
* \brief Remove let binding and directly share via pointer instead.
*
Expand Down Expand Up @@ -586,6 +602,57 @@ TVM_DLL Expr ForwardRewrite(const Expr& expr,
std::function<NodeRef(const Call&)> fcontext = nullptr,
std::function<Expr(const Expr&)> fmulti_ref_trigger = nullptr);

/*!
* \brief Rewrite the annotated program.
*
* \param expr The expression.
* \param fallback_device The fallback device which is the default device for
* operators without annotation.
*
* \return The updated program.
*/
TVM_DLL Expr RewriteAnnotatedOps(const Expr& expr, int fallback_device);

/*!
* \brief Turn an expression into continuation passing style(CPS).
*
* CPS mean that every function will, instead of returning the result directly,
* be passed down an extra function (called the continuation) as argument,
* and pass the result to the continuation instead.
*
* Thus, every function call has to be passed an extra argument
* that represent the rest of the computation (Hence the name of continuation).
*
* Similarly, all other compute will be wrapped and call the continuation as well.
*
* \param f the function.
* \param mod the module.
*
* \return the converted Function.
*/
TVM_DLL Function ToCPS(const Function& f, const Module& mod);

/*!
* \brief Remove the continuation argument of a CPS function.
*
* Note that this only transform the type back into un-CPS form
* when there is no higher order input/output.
*
* \param f the function.
*
* \return the converted Function.
*/
TVM_DLL Function UnCPS(const Function& f);

/*!
* \brief Deduplicate the bound variables and type variables in the expression.
*
* \param e the expression.
*
* \return the deduplicated expression.
*/
TVM_DLL Expr DeDup(const Expr& e);

} // namespace relay
} // namespace tvm

Expand Down
15 changes: 15 additions & 0 deletions python/tvm/relay/testing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
"""Utilities for testing and benchmarks"""
from __future__ import absolute_import as _abs

import tvm.relay as relay
from tvm.relay import transform

from . import mlp
from . import resnet
from . import dqn
Expand All @@ -32,3 +35,15 @@
from .config import ctx_list
from .init import create_workload
from .nat import add_nat_definitions, count, make_nat_value, make_nat_expr


def run_opt_pass(expr, opt_pass):
assert isinstance(opt_pass, transform.Pass)
mod = relay.Module.from_expr(expr)
mod = opt_pass(mod)
entry = mod[mod.entry_func]
return entry if isinstance(expr, relay.Function) else entry.body


def run_infer_type(expr):
return run_opt_pass(expr, transform.InferType())
64 changes: 56 additions & 8 deletions python/tvm/relay/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,20 @@ def ToANormalForm():
return _transform.ToANormalForm()


def ToCPS(expr, mod=None):
"""
Turn expression into continuation passing style(CPS).
Every intermediate compute will be passed to a continuation.
Returns
-------
result: tvm.relay.Pass
The registered pass that transforms an expression into CPS.
"""
return _ir_pass.to_cps(expr, mod)


def EtaExpand():
"""Add abstraction over a function
Expand Down Expand Up @@ -495,14 +509,6 @@ def PartialEvaluate():
expression is provided. Otherwise, it will rely on the pass manager to
carry out transformation.
Parameters
----------
expr : Optional[tvm.relay.Expr]
The input expression.
mod : Optional[tvm.relay.Module]
The global module.
Returns
-------
ret: tvm.relay.Pass
Expand Down Expand Up @@ -554,6 +560,48 @@ def gradient(expr, mod=None, mode='higher_order'):
raise Exception('unknown mode')


def to_cps(func, mod=None):
"""
Turn expression into CPS expression.
Every intermediate compute will be passed to a continuation.
Parameters
----------
func: tvm.relay.Function
The input function.
mod: Optional[tvm.relay.Module]
The global module.
Returns
-------
result: tvm.relay.Function
The output function.
"""
return _transform.to_cps(func, mod)


def un_cps(func):
"""
Turn an cps function into a Function without the continuation argument.
Note that this will not give the exact same interface as before cps:
If the input/output is higher order, they will still be in cps form.
Parameters
----------
func: tvm.relay.Function
The input function
Returns
-------
result: tvm.relay.Function
The output function
"""
return _transform.un_cps(func)


def _wrap_class_module_pass(pass_cls, pass_info):
"""Wrap a python class as function pass"""
class PyModulePass(ModulePass):
Expand Down
6 changes: 3 additions & 3 deletions src/relay/ir/adt.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
* 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
Expand All @@ -18,7 +18,7 @@
*/

/*!
* Copyright (c) 2018 by Contributors
* Copyright (c) 2019 by Contributors
* \file src/tvm/ir/adt.cc
* \brief AST nodes for Relay algebraic data types (ADTs).
*/
Expand Down
3 changes: 2 additions & 1 deletion src/relay/ir/module.cc
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,9 @@ GlobalTypeVar ModuleNode::GetGlobalTypeVar(const std::string& name) const {
}

void ModuleNode::Add(const GlobalVar& var,
const Function& func,
const Function& f,
bool update) {
Function func = Downcast<Function>(DeDup(f));
// Type check the item before we add it to the module.
auto mod = GetRef<Module>(this);
Function checked_func = InferType(func, mod, var);
Expand Down
12 changes: 11 additions & 1 deletion src/relay/ir/pretty_printer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -645,11 +645,21 @@ class PrettyPrinter :

Doc VisitType_(const FuncTypeNode* node) final {
Doc doc;
doc << "fn ";
if (node->type_params.size() != 0) {
doc << "<";
std::vector<Doc> type_params;
for (Type type_param : node->type_params) {
type_params.push_back(Print(type_param));
}
doc << PrintVec(type_params);
doc << ">";
}
std::vector<Doc> arg_types;
for (Type arg_type : node->arg_types) {
arg_types.push_back(Print(arg_type));
}
return doc << "fn (" << PrintVec(arg_types) << ") -> " << Print(node->ret_type);
return doc << "(" << PrintVec(arg_types) << ") -> " << Print(node->ret_type);
}

Doc VisitType_(const RefTypeNode* node) final {
Expand Down
2 changes: 1 addition & 1 deletion src/relay/ir/type_functor.cc
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ class TypeBinder : public TypeMutator {
};

Type Bind(const Type& type, const tvm::Map<TypeVar, Type>& args_map) {
return TypeBinder(args_map).VisitType(type);
return type.defined() ? TypeBinder(args_map).VisitType(type) : type;
}

} // namespace relay
Expand Down
122 changes: 122 additions & 0 deletions src/relay/pass/de_duplicate.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* 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.
*/

/*!
* Copyright (c) 2019 by Contributors
*
* \file de_duplicate.cc
* \brief Use a fresh Id for every Var to make the result well-formed.
*/

#include <tvm/relay/expr_functor.h>
#include <tvm/relay/analysis.h>
#include <tvm/relay/pattern_functor.h>
#include "../ir/type_functor.h"

namespace tvm {
namespace relay {

Expr DeDup(const Expr& e) {
class DeDupMutator : public TypeMutator,
public ExprMutator,
public PatternMutator {
public:
TypeVar Fresh(const TypeVar& tv) {
TypeVar ret = TypeVarNode::make(tv->var->name_hint, tv->kind);
type_rename_[tv] = ret;
return ret;
}

Var Fresh(const Var& v) {
Var ret = VarNode::make(v->name_hint(), VisitType(v->type_annotation));
rename_[v] = ret;
return ret;
}

Expr VisitExpr(const Expr& e) final {
return ExprMutator::VisitExpr(e);
}

Expr VisitExpr_(const VarNode* op) final {
Var v = GetRef<Var>(op);
return rename_.count(v) != 0 ? rename_.at(v) : v;
}

Expr VisitExpr_(const LetNode* op) final {
Var v = Fresh(op->var);
return LetNode::make(v, VisitExpr(op->value), VisitExpr(op->body));
}

Type VisitType(const Type& t) final {
return t.defined() ? TypeMutator::VisitType(t) : t;
}

Expr VisitExpr_(const FunctionNode* op) final {
tvm::Array<TypeVar> type_params;
for (const TypeVar& type_param : op->type_params) {
type_params.push_back(Fresh(type_param));
}
tvm::Array<Var> params;
for (const Var& param : op->params) {
params.push_back(Fresh(param));
}
return FunctionNode::make(params,
VisitExpr(op->body),
VisitType(op->ret_type),
type_params,
op->attrs);
}

Pattern VisitPattern(const Pattern& p) final {
return PatternMutator::VisitPattern(p);
}

Pattern VisitPattern_(const PatternVarNode* op) final {
return PatternVarNode::make(Fresh(op->var));
}

Clause VisitClause(const Clause& c) final {
Pattern pat = VisitPattern(c->lhs);
return ClauseNode::make(pat, VisitExpr(c->rhs));
}

Type VisitType_(const TypeVarNode* op) final {
TypeVar v = GetRef<TypeVar>(op);
return type_rename_.count(v) != 0 ? type_rename_.at(v) : v;
}

Var VisitVar(const Var& v) final {
return Fresh(v);
}

private:
std::unordered_map<Var, Var, NodeHash, NodeEqual> rename_;
std::unordered_map<TypeVar, TypeVar, NodeHash, NodeEqual> type_rename_;
};

Expr ret = DeDupMutator().VisitExpr(e);
CHECK_EQ(FreeVars(ret).size(), FreeVars(e).size());
return ret;
}

TVM_REGISTER_API("relay._transform.dedup")
.set_body_typed(DeDup);

} // namespace relay
} // namespace tvm
Loading

0 comments on commit e5154d4

Please sign in to comment.