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 409 410 411 412 413 414 415 416 417
|
#include <ATen/CUDAGeneratorImpl.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDACachingAllocator.h>
#include <torch/csrc/jit/codegen/cuda/executor_utils.h>
#include <torch/csrc/jit/codegen/cuda/instrumentation.h>
#include <torch/csrc/jit/codegen/cuda/ir_all_nodes.h>
#include <torch/csrc/jit/codegen/cuda/kernel_resource_strings.h>
#include <torch/csrc/jit/resource_guard.h>
#include <fstream>
namespace torch {
namespace jit {
namespace fuser {
namespace cuda {
namespace executor_utils {
std::string kernelPreamble() {
std::stringstream ss;
ss << code_template_tensor_struct << "\n"
<< code_fp16_support << "\n"
<< code_random_number_gen << "\n"
<< code_helper_funcs << "\n"
<< code_template_block_reduction << "\n"
<< code_template_grid_reduction << "\n"
<< code_template_block_broadcast << "\n";
return ss.str();
}
namespace {
// return false if arg's type, number of dimensions, and device, doesn't match
// param and provided c10:device
bool validateKernelArgTensor(
const at::Tensor& arg,
const Val* param,
const c10::Device& device,
std::stringstream& msg) {
// Arg is a tensor. Param must be a tensor too.
if (*param->getValType() != ValType::TensorView) {
msg << "Argument is a tensor, but the parameter is not.\n";
return false;
}
// Check the rank of the tensors.
size_t arg_dim = arg.dim();
// Note: This requires current Fusion to be active.
size_t param_dim =
TensorDomain::noReductions(param->as<TensorView>()->getRootDomain())
.size();
// see [Note - broadcast support in integration]
// Because of broadcasting support handled in integration, we relax the rank
// check as necessary.
if (arg_dim > param_dim) {
msg << "Argument tensor's rank is " << arg_dim << ", but the parameter is "
<< param_dim << "\n";
return false;
}
if (arg.device() != device) {
msg << "Argument is on device that is not compiled for."
<< "\n";
return false;
}
// Check element type
at::ScalarType arg_data_type = arg.scalar_type();
DataType param_data_type = *param->getDataType();
bool match = false;
switch (arg_data_type) {
case at::ScalarType::Half:
match = param_data_type == DataType::Half;
break;
case at::ScalarType::Float:
match = param_data_type == DataType::Float;
break;
case at::ScalarType::Bool:
match = param_data_type == DataType::Bool;
break;
default:
msg << "Argument element type, " << arg_data_type << ", is not supported."
<< "\n";
return false;
}
if (!match)
msg << "Argument element type is " << arg_data_type
<< ", but the parameter is " << param_data_type << "\n";
return match;
}
// Return false if arg_type doesn't match the type in param
bool validateKernelArgScalar(
const c10::TypePtr& arg_type,
const Val* param,
std::stringstream& msg) {
if (!param->isScalar()) {
msg << "Argument is a scalar, but the parameter is not."
<< "\n";
return false;
}
DataType param_type = *param->getDataType();
bool match = false;
switch (arg_type->kind()) {
case c10::TypeKind::IntType:
match = param_type == DataType::Int;
break;
case c10::TypeKind::FloatType:
match = param_type == DataType::Float;
break;
case c10::TypeKind::BoolType:
match = param_type == DataType::Bool;
break;
default:
match = false;
}
if (!match) {
msg << "Argument type is " << *arg_type << ", but the parameter is "
<< param_type << "\n";
}
return match;
}
// Return false if arg and param don't match up and if arg's device (if a
// tensor) doesn't match provided device
bool validateKernelArg(
const c10::IValue& arg,
const Val* param,
const c10::Device& device,
std::stringstream& msg) {
if (arg.isTensor()) {
return validateKernelArgTensor(arg.toTensor(), param, device, msg);
} else {
return validateKernelArgScalar(arg.type(), param, msg);
}
}
} // namespace
void validateKernelInputs(
Fusion* fusion,
const at::ArrayRef<IValue>& inputs,
const c10::Device& device) {
FUSER_PERF_SCOPE("validateKernelInputs");
// This is necessary as we were traversing the fusion graph later in the check
FusionGuard fg(fusion);
// Check inputs
TORCH_INTERNAL_ASSERT(
inputs.size() == fusion->inputs().size(),
"Wrong number of kernel inputs.");
std::stringstream msg;
bool mismatch = false;
for (size_t i = 0; i < inputs.size(); ++i) {
const IValue& arg = inputs[i];
const Val* param = fusion->inputs()[i];
mismatch = !validateKernelArg(arg, param, device, msg) || mismatch;
}
TORCH_INTERNAL_ASSERT(
!mismatch, "Found one or more invalid arguments: ", msg.str());
}
void validateKernelOutputs(
Fusion* fusion,
const std::vector<at::Tensor>& outputs,
const c10::Device& device) {
FUSER_PERF_SCOPE("validateKernelOutputs");
TORCH_INTERNAL_ASSERT(
fusion->outputs().size() != 0,
"Kernel should have at least one output tensor.");
TORCH_INTERNAL_ASSERT(
outputs.size() == fusion->outputs().size(),
"Wrong number of kernel outputs.");
std::stringstream msg;
bool mismatch = false;
for (size_t i = 0; i < outputs.size(); ++i) {
const at::Tensor& arg = outputs[i];
const Val* param = fusion->outputs()[i];
mismatch = !validateKernelArg(arg, param, device, msg) || mismatch;
}
TORCH_INTERNAL_ASSERT(
!mismatch, "Found one or more invalid arguments: ", msg.str());
}
StatefulExpressionEvaluator statefulBindInputs(
const at::ArrayRef<IValue>& aten_inputs,
Fusion* fusion,
GpuLower* lower) {
FUSER_PERF_SCOPE("statefulBindInputs");
TORCH_INTERNAL_ASSERT(
fusion->inputs().size() == aten_inputs.size(),
"Something went wrong configuring launch. Inputs no longer match.");
auto fusion_inputs = fusion->inputs();
StatefulExpressionEvaluator evaluator(fusion);
// This should probably move to EvaluationContext as we may want to bind
// input values frequently. Bind fusion input values to runtime values.
for (size_t i = 0; i < fusion->inputs().size(); i++) {
if (fusion->inputs()[i]->getValType() == ValType::TensorView) {
TensorView* cg_tensor = fusion->inputs()[i]->as<TensorView>();
TORCH_INTERNAL_ASSERT(
aten_inputs[i].isTensor(),
"Something went wrong configuring launch. Inputs no longer match.");
auto aten_tensor = aten_inputs[i].toTensor();
auto root_dom = TensorDomain::noReductions(cg_tensor->getRootDomain());
TORCH_INTERNAL_ASSERT(
aten_tensor.ndimension() == (int64_t)root_dom.size(),
"Something went wrong configuring launch. Inputs no longer match.");
for (size_t dim = 0; dim < root_dom.size(); dim++) {
evaluator.safeBind(
root_dom[dim]->extent(), aten_tensor.sizes()[dim], lower);
}
} else if (
fusion->inputs()[i]->getValType().value() == ValType::Scalar &&
fusion->inputs()[i]->getDataType().value() == DataType::Int) {
TORCH_INTERNAL_ASSERT(
aten_inputs[i].type()->kind() == c10::TypeKind::IntType);
evaluator.safeBind(fusion->inputs()[i], aten_inputs[i].toInt(), lower);
}
}
return evaluator;
}
NvrtcFunction nvrtcCompile(
const std::string& code,
const std::string& func_name,
int id) {
FUSER_PERF_SCOPE("NVRTC");
// lazily construct context if non-existing yet;
CUcontext pctx = nullptr;
AT_CUDA_DRIVER_CHECK(at::globalContext().getNVRTC().cuCtxGetCurrent(&pctx));
if (!pctx) {
std::unique_lock<std::mutex> cudaFreeMutexLock(
*(c10::cuda::CUDACachingAllocator::getFreeMutex()));
cudaFree(nullptr);
}
const auto prop = at::cuda::getCurrentDeviceProperties();
int nvrtc_major, nvrtc_minor;
AT_CUDA_NVRTC_CHECK(
at::globalContext().getNVRTC().nvrtcVersion(&nvrtc_major, &nvrtc_minor));
// Short-circuits if NVRTC version too low
TORCH_INTERNAL_ASSERT(nvrtc_major >= 6);
// Major and minor is determined by device properties and
// possibly "downcompiled" to a lower (compatible) compute architecture
// based on the NVRTC version
const int major = prop->major;
const int minor = prop->minor;
nvrtcProgram program;
{
FUSER_PERF_SCOPE("nvrtcCreateProgram");
AT_CUDA_NVRTC_CHECK(at::globalContext().getNVRTC().nvrtcCreateProgram(
&program, code.c_str(), nullptr, 0, nullptr, nullptr));
}
ResourceGuard holdProgram([&] {
FUSER_PERF_SCOPE("nvrtcDestroyProgram");
AT_CUDA_NVRTC_CHECK(
at::globalContext().getNVRTC().nvrtcDestroyProgram(&program));
});
const std::string compute = "--gpu-architecture=compute_" +
std::to_string(major) + std::to_string(minor);
std::vector<const char*> args = {
"--std=c++14", compute.c_str(), "-default-device"};
const char* disable_fma = getenv("PYTORCH_CUDA_FUSER_DISABLE_FMA");
// int disable_fma_flag = disable_fma ? atoi(disable_fma) : 0;
if (disable_fma && atoi(disable_fma)) {
args.push_back("--fmad=false");
}
const char* ptxas_opt_level = getenv("PYTORCH_CUDA_FUSER_JIT_OPT_LEVEL");
uint32_t jit_opt_level;
std::vector<CUjit_option> options;
std::vector<void*> option_vals;
if (ptxas_opt_level) {
int val = atoi(ptxas_opt_level);
if (val <= 4 && val >= 0) {
jit_opt_level = static_cast<uint32_t>(val);
options.push_back(CU_JIT_OPTIMIZATION_LEVEL);
option_vals.emplace_back(&jit_opt_level);
} else {
TORCH_WARN_ONCE(
"acceptable range for PYTORCH_CUDA_FUSER_JIT_OPT_LEVEL is between 0 and 4, but received ",
jit_opt_level,
", ignoring the option");
}
}
at::globalContext().getNVRTC().nvrtcAddNameExpression(
program, func_name.c_str());
{
FUSER_PERF_SCOPE("nvrtcCompileProgram");
const auto result = at::globalContext().getNVRTC().nvrtcCompileProgram(
program, args.size(), args.data());
if (result != NVRTC_SUCCESS) {
size_t logsize;
at::globalContext().getNVRTC().nvrtcGetProgramLogSize(program, &logsize);
std::vector<char> log(logsize);
at::globalContext().getNVRTC().nvrtcGetProgramLog(program, log.data());
TORCH_INTERNAL_ASSERT(
false, code.c_str(), "\nCUDA NVRTC compile error: ", log.data());
}
AT_CUDA_NVRTC_CHECK(result);
}
const char* lowered_kernel_name = nullptr;
at::globalContext().getNVRTC().nvrtcGetLoweredName(
program, func_name.c_str(), &lowered_kernel_name);
size_t ptx_size = 0;
std::vector<char> ptx;
{
FUSER_PERF_SCOPE("get PTX");
AT_CUDA_NVRTC_CHECK(
at::globalContext().getNVRTC().nvrtcGetPTXSize(program, &ptx_size));
ptx.resize(ptx_size);
AT_CUDA_NVRTC_CHECK(
at::globalContext().getNVRTC().nvrtcGetPTX(program, ptx.data()));
}
NvrtcFunction compiled_kernel_;
// TODO: We do go through different code path, should investigate whether this
// has an impact on generated binary.
const char* prefix_env = getenv("PYTORCH_CUDA_FUSER_CUBIN");
if (prefix_env) {
FUSER_PERF_SCOPE("load CUBIN");
// Output ptx file
std::stringstream ptx_file_name;
ptx_file_name << prefix_env << "_" << id << ".ptx";
std::ofstream myPtxFile(ptx_file_name.str().c_str(), std::ios::out);
if (myPtxFile.is_open()) {
myPtxFile.write(ptx.data(), ptx.size());
myPtxFile.close();
}
CUlinkState linkState;
AT_CUDA_DRIVER_CHECK(at::globalContext().getNVRTC().cuLinkCreate(
0, nullptr, nullptr, &linkState));
AT_CUDA_DRIVER_CHECK(at::globalContext().getNVRTC().cuLinkAddData(
linkState,
CU_JIT_INPUT_PTX,
ptx.data(),
ptx_size,
"compiling PTX",
options.size(),
options.data(),
option_vals.data()));
size_t cubinSize;
void* cubin;
AT_CUDA_DRIVER_CHECK(at::globalContext().getNVRTC().cuLinkComplete(
linkState, &cubin, &cubinSize));
// Output binary file
std::stringstream cubin_file_name;
cubin_file_name << prefix_env << "_" << id << ".cubin";
std::ofstream myCubinFile(
cubin_file_name.str().c_str(), std::ios::out | std::ios::binary);
if (myCubinFile.is_open()) {
myCubinFile.write(static_cast<const char*>(cubin), cubinSize);
myCubinFile.close();
}
// load compiled cubin
AT_CUDA_DRIVER_CHECK(at::globalContext().getNVRTC().cuModuleLoadData(
&(compiled_kernel_.module), cubin));
} else {
FUSER_PERF_SCOPE("load PTX");
// load ptx directly
AT_CUDA_DRIVER_CHECK(at::globalContext().getNVRTC().cuModuleLoadDataEx(
&(compiled_kernel_.module),
ptx.data(),
options.size(),
options.data(),
option_vals.data()));
}
AT_CUDA_DRIVER_CHECK(at::globalContext().getNVRTC().cuModuleGetFunction(
&(compiled_kernel_.function),
compiled_kernel_.module,
lowered_kernel_name));
return compiled_kernel_;
}
} // namespace executor_utils
} // namespace cuda
} // namespace fuser
} // namespace jit
} // namespace torch
|