1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
|
#include <algorithm>
#include <type_traits>
#include <vector>
#include <torch/csrc/jit/tensorexpr/cpp_codegen.h>
#include <torch/csrc/jit/tensorexpr/cpp_intrinsics.h>
#include <torch/csrc/jit/tensorexpr/external_functions_registry.h>
#include <torch/csrc/jit/tensorexpr/types.h>
namespace torch {
namespace jit {
namespace tensorexpr {
// Rewrites the variables' name according to valid C++ naming convention.
// E.g. in Graph IR, variable name may contain '.', in C++, they are replaced
// with '_'.
class CppVarNameRewriter : public IRVisitor {
public:
void visit(VarPtr v) override {
constexpr char kDot = '.';
constexpr char kUnderscore = '_';
if (v->name_hint().find(kDot) == std::string::npos) {
return;
}
std::string name = v->name_hint();
std::replace(name.begin(), name.end(), kDot, kUnderscore);
v->set_name_hint(std::move(name));
}
void visit(BufPtr v) override {
v->base_handle()->accept(this);
}
};
static std::string declareExternalFunction(const std::string& func_name) {
return "void " + func_name +
"("
"int64_t bufs_num, "
"void** buf_data, "
"int64_t* buf_ranks, "
"int64_t* buf_dims, "
"int8_t* buf_dtypes, "
"int64_t args_num, "
"int64_t* extra_args);";
}
CppPrinter::CppPrinter(std::ostream* os) : IRPrinter(*os), lane_(0) {}
CppPrinter::~CppPrinter() = default;
void CppPrinter::printPrologue() {
os() << "#include <cassert>" << std::endl;
os() << "#include <cmath>" << std::endl;
os() << "#include <algorithm>" << std::endl;
os() << "#include <type_traits>" << std::endl;
os() << std::endl;
os() << "#define POS_INFINITY INFINITY" << std::endl;
os() << "#define NEG_INFINITY -INFINITY" << std::endl;
os() << std::endl;
os() << cpp_intrinsics_definition << std::endl;
os() << std::endl;
os() << "namespace torch {" << std::endl;
os() << "namespace jit {" << std::endl;
os() << "namespace tensorexpr {" << std::endl;
for (auto const& it : getNNCFunctionRegistry()) {
os() << declareExternalFunction(it.first) << std::endl;
}
os() << "} // namespace tensorexpr" << std::endl;
os() << "} // namespace jit" << std::endl;
os() << "} // namespace torch" << std::endl;
os() << std::endl;
os() << "using namespace torch::jit::tensorexpr;" << std::endl;
os() << std::endl;
}
template <typename T>
inline typename std::enable_if<!std::is_floating_point<T>::value, void>::type
visit_mod(std::ostream& os, const ExprPtr lhs, const ExprPtr rhs) {
os << *lhs << " % " << *rhs;
}
template <typename T>
inline typename std::enable_if<std::is_floating_point<T>::value, void>::type
visit_mod(std::ostream& os, const ExprPtr lhs, const ExprPtr rhs) {
os << "std::fmod(" << *lhs << ", " << *rhs << ")";
}
template <typename T>
inline typename std::enable_if<
std::is_floating_point<T>::value || std::is_integral<T>::value,
void>::type
visit_max(std::ostream& os, const ExprPtr lhs, const ExprPtr rhs) {
os << "std::max(" << *lhs << ", " << *rhs << ")";
}
template <typename T>
inline typename std::enable_if<
!std::is_floating_point<T>::value && !std::is_integral<T>::value,
void>::type
visit_max(std::ostream& os, const ExprPtr lhs, const ExprPtr rhs) {
os << "(" << *lhs << " < " << *rhs << ") ? " << *rhs << " : " << *lhs;
}
template <typename T>
inline typename std::enable_if<
std::is_floating_point<T>::value || std::is_integral<T>::value,
void>::type
visit_min(std::ostream& os, const ExprPtr lhs, const ExprPtr rhs) {
os << "std::min(" << *lhs << ", " << *rhs << ")";
}
template <typename T>
inline typename std::enable_if<
!std::is_floating_point<T>::value && !std::is_integral<T>::value,
void>::type
visit_min(std::ostream& os, const ExprPtr lhs, const ExprPtr rhs) {
os << *lhs << " < " << *rhs << " ? " << *lhs << " : " << *rhs;
}
template <typename T>
void visit_binary_op(
std::ostream& os,
const ExprPtr lhs,
const ExprPtr rhs,
IRNodeType op_type) {
switch (op_type) {
case IRNodeType::kMod:
visit_mod<T>(os, lhs, rhs);
break;
case IRNodeType::kMax:
visit_max<T>(os, lhs, rhs);
break;
case IRNodeType::kMin:
visit_min<T>(os, lhs, rhs);
break;
default:
throw std::runtime_error("invalid op type");
}
}
template <typename Op>
void dispatch_binary_op(std::ostream& os, const BinaryOpNode<Op>* v) {
switch (v->lhs()->dtype().scalar_type()) {
#define TYPE_CASE(Type, Name) \
case ScalarType::Name: \
visit_binary_op<Type>(os, v->lhs(), v->rhs(), v->expr_type()); \
break;
AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE);
#undef TYPE_CASE
default:
throw unsupported_dtype();
}
}
void CppPrinter::visit(RampPtr v) {
visit(alloc<Add>(v->base(), alloc<Mul>(alloc<IntImm>(lane_), v->stride())));
}
void CppPrinter::visit(BroadcastPtr v) {
v->value()->accept(this);
}
void CppPrinter::visit(ModPtr v) {
dispatch_binary_op(os(), v.get());
}
void CppPrinter::visit(MaxPtr v) {
dispatch_binary_op(os(), v.get());
}
void CppPrinter::visit(MinPtr v) {
dispatch_binary_op(os(), v.get());
}
void CppPrinter::visit(CompareSelectPtr v) {
os() << "((" << *v->lhs() << " "
<< IRPrinter::to_string(v->compare_select_op()) << " " << *v->rhs()
<< ") ? " << *v->ret_val1() << " : " << *v->ret_val2() << ")";
}
void CppPrinter::visit(IfThenElsePtr v) {
os() << "((" << *v->condition() << ") ? " << *v->true_value() << " : "
<< *v->false_value() << ")";
}
void CppPrinter::visit(AllocatePtr v) {
size_t size = v->dtype().byte_size();
for (const auto& dim : v->dims()) {
IntImmPtr d = to<IntImm>(dim);
if (d) {
size *= d->value();
} else {
throw std::runtime_error("Only IntImm dimensions are supported for now");
}
}
emitIndent();
os() << v->dtype().ToCppString() << "* " << (*v->buffer_var())
<< " = static_cast<" << v->dtype().ToCppString() << "*>(malloc(" << size
<< "));" << std::endl;
}
void CppPrinter::visit(FreePtr v) {
emitIndent();
os() << "free(" << *v->buffer_var() << ");" << std::endl;
}
void CppPrinter::visit(LoadPtr v) {
auto flat_idx =
flatten_index(v->buf()->dims(), v->indices(), v->buf()->strides());
os() << *v->base_handle() << "[" << *flat_idx << "]";
}
void CppPrinter::visit(StorePtr v) {
auto flat_idx =
flatten_index(v->buf()->dims(), v->indices(), v->buf()->strides());
const int lanes = v->value()->dtype().lanes();
for (int lane = 0; lane < lanes; lane++) {
lane_ = lane;
emitIndent();
os() << *v->base_handle() << "[" << *flat_idx << "] = " << *v->value()
<< ";" << std::endl;
}
}
void CppPrinter::visit(CastPtr v) {
os() << "static_cast<" << v->dtype().ToCppString() << ">(" << *v->src_value()
<< ")";
}
void CppPrinter::visit(BitCastPtr v) {
os() << "std::bitcast<" << v->src_value()->dtype().ToCppString() << ", "
<< v->dtype().ToCppString() << ">(" << *v->src_value() << ")";
}
void CppPrinter::visit(IntrinsicsPtr v) {
if (v->op_type() == kRand || v->op_type() == kSigmoid) {
throw std::runtime_error("kRand and kSigmoid are not supported");
}
os() << "std::" << v->func_name() << "(";
for (int i = 0; i < v->nparams(); i++) {
if (i > 0) {
os() << ", ";
}
os() << *v->param(i);
}
os() << ")";
}
void CppPrinter::visit(ExternalCallPtr v) {
// The generated code needs to link against functions defined
// in external_functions.cpp.
auto& func_registry = getNNCFunctionRegistry();
if (!func_registry.count(v->func_name())) {
throw unimplemented_lowering(v);
}
std::vector<BufPtr> bufs(v->buf_args());
bufs.insert(bufs.begin(), v->buf());
auto for_buf = [&](const std::function<void(const BufPtr)>& print_buf) {
for (size_t i = 0; i < bufs.size(); i++) {
if (i > 0) {
os() << ", ";
}
print_buf(bufs[i]);
}
};
emitIndent();
os() << "{" << std::endl;
indent_++;
emitIndent();
os() << "void* buf_ptrs[]{";
for_buf([&](const BufPtr b) { os() << *b->base_handle(); });
os() << "};" << std::endl;
emitIndent();
os() << "int64_t buf_ranks[]{";
for_buf([&](const BufPtr b) { os() << b->ndim(); });
os() << "};" << std::endl;
emitIndent();
os() << "int64_t buf_dims[]{";
for_buf([&](const BufPtr buf) {
for (size_t i = 0; i < buf->ndim(); i++) {
if (i > 0) {
os() << ", ";
}
os() << *buf->dim(i);
}
});
os() << "};" << std::endl;
emitIndent();
os() << "int8_t buf_dtypes[]{";
for_buf([&](const BufPtr buf) {
os() << static_cast<int>(buf->dtype().scalar_type());
});
os() << "};" << std::endl;
emitIndent();
os() << "int64_t extra_args[]{";
for (size_t i = 0; i < v->args().size(); i++) {
if (i > 0) {
os() << ", ";
}
os() << *v->args()[i];
}
os() << "};" << std::endl;
emitIndent();
os() << v->func_name() << "(" << std::endl;
emitIndent();
os() << " " << bufs.size() << "," << std::endl;
emitIndent();
os() << " buf_ptrs," << std::endl;
emitIndent();
os() << " buf_ranks," << std::endl;
emitIndent();
os() << " buf_dims," << std::endl;
emitIndent();
os() << " buf_dtypes," << std::endl;
emitIndent();
os() << " " << v->args().size() << "," << std::endl;
emitIndent();
os() << " extra_args);" << std::endl;
indent_--;
emitIndent();
os() << "}" << std::endl;
}
void CppPrinter::visit(LetPtr v) {
if (v->var()->dtype().lanes() == 1) {
emitIndent();
os() << v->var()->dtype().ToCppString() << " " << *v->var() << " = "
<< *v->value() << ";" << std::endl;
} else {
vector_vars_[v->var()] = v->value();
}
}
void CppPrinter::visit(VarPtr v) {
if (v->dtype().lanes() == 1) {
os() << name_manager()->get_unique_name(v);
} else {
os() << *vector_vars_.at(v);
}
}
CppCodeGen::CppCodeGen(
StmtPtr stmt,
const std::vector<BufferArg>& buffer_args,
at::Device device,
const std::string& kernel_func_name)
: CodeGen(stmt, buffer_args, device, kernel_func_name) {
init();
}
void CppCodeGen::init() {
printer_ = std::make_unique<CppPrinter>(&oss_);
var_name_rewriter_ = std::make_unique<CppVarNameRewriter>();
apply_visitor(var_name_rewriter_.get());
printer_->printPrologue();
os() << "void " << kernel_func_name() << "(";
const std::vector<BufferArg> buffer_args = this->buffer_args();
for (size_t i = 0; i < buffer_args.size(); i++) {
if (i > 0) {
os() << ", ";
}
const BufferArg& buffer_arg = buffer_args[i];
const VarPtr var = buffer_arg.var();
Dtype dtype = buffer_arg.dtype();
os() << dtype.ToCppString() << (buffer_arg.isVar() ? " " : "* ") << *var;
}
os() << ")";
stmt()->accept(printer_.get());
os() << std::endl;
}
CppCodeGen::~CppCodeGen() = default;
void CppCodeGen::call(const std::vector<CallArg>& args) {
// TODO: compile the generated C++ kernel into a library,
// and call the library here.
os() << "int main() {}" << std::endl;
}
void CppCodeGen::call_raw(const std::vector<void*>& args) {
// TODO: compile the generated C++ kernel into a library,
// and call the library here.
os() << "int main() {}" << std::endl;
}
RegisterCodeGen<CppCodeGen> cpp_codegen_reg("cpp_codegen");
} // namespace tensorexpr
} // namespace jit
} // namespace torch
|