jiterator.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import torch
  2. from torch import Tensor
  3. from typing import Callable, List
  4. import re
  5. __all__ : List[str] = []
  6. class _CodeParser:
  7. def __init__(self, code_string: str):
  8. optional_ws = r"\s*"
  9. required_ws = r"\s+"
  10. template_params = r"(?P<template_params>\<.+\>)"
  11. return_type = r"(?P<return_type>\w+)"
  12. function_name = r"(?P<function_name>\w+)"
  13. function_params = r"(?P<function_params>\(.+\))"
  14. function_body = r"(?P<function_body>\{.+\})"
  15. pattern = \
  16. optional_ws \
  17. + "template" \
  18. + optional_ws + template_params \
  19. + optional_ws + return_type \
  20. + required_ws + function_name \
  21. + optional_ws + function_params \
  22. + optional_ws + function_body \
  23. + optional_ws
  24. result = re.match(pattern, code_string, re.DOTALL) # DOTALL for matching multiline
  25. if result is None:
  26. raise Exception(f"Couldn't parse code, please check correctness:\n {code_string}")
  27. self.template_params = result["template_params"]
  28. self.return_type = result["return_type"]
  29. self.function_name = result["function_name"]
  30. self.function_params = result["function_params"]
  31. self.function_body = result["function_body"]
  32. class _JittedFunction:
  33. def __init__(self, code_string: str, return_by_ref: bool, num_outputs: int, **kwargs):
  34. self.code_string = code_string
  35. assert return_by_ref or num_outputs == 1, "Return by value only works for single output. "
  36. self.return_by_ref = return_by_ref
  37. self.num_outputs = num_outputs
  38. parsed_code = _CodeParser(code_string)
  39. self.kernel_name = parsed_code.function_name
  40. self.kwargs_dict = kwargs
  41. self.is_cuda_available = torch.cuda.is_available()
  42. def __call__(self, *tensors: Tensor, **kwargs):
  43. # Jiterator follow torch.cuda's lazy initialization behavior
  44. # Defer checking cuda's availability at the function invocation time
  45. assert self.is_cuda_available, "Jiterator is only supported on CUDA and ROCm GPUs, none are available."
  46. assert len(tensors) <= 8, "jiterator only supports up to 8 tensor inputs."
  47. expanded_kwargs = self.kwargs_dict.copy()
  48. for key, value in kwargs.items():
  49. if key in self.kwargs_dict:
  50. expanded_kwargs[key] = value
  51. else:
  52. raise KeyError(f"{key} is not declared in function definition")
  53. return torch._C._cuda_jiterator_compile_and_launch_kernel(
  54. self.code_string,
  55. self.kernel_name,
  56. self.return_by_ref,
  57. self.num_outputs,
  58. tensors,
  59. expanded_kwargs)
  60. def _create_jit_fn(code_string: str, **kwargs) -> Callable:
  61. """
  62. Create a jiterator-generated cuda kernel for an elementwise op.
  63. The code string has to be a valid CUDA function that describes the computation for a single element. The code
  64. string has to follow the c++ template pattern, as shown in the example below. This function will be inlined
  65. into elementwise kernel template, and compiled on the fly. Compiled kernel will be cached in memory, as well as
  66. local temp dir.
  67. Jiterator-generated kernels accepts noncontiguous tensors, and supports boardcasting and type promotion.
  68. Args:
  69. code_string (str): CUDA code string to be compiled by jiterator. The entry functor must return by value.
  70. kwargs (Dict, optional): Keyword arguments for generated function
  71. Example::
  72. code_string = "template <typename T> T my_kernel(T x, T y, T alpha) { return -x + alpha * y; }"
  73. jitted_fn = create_jit_fn(code_string, alpha=1.0)
  74. a = torch.rand(3, device='cuda')
  75. b = torch.rand(3, device='cuda')
  76. # invoke jitted function like a regular python function
  77. result = jitted_fn(a, b, alpha=3.14)
  78. code_string also allows multiple function definitions, and the last function will be treated as the entry function.
  79. Example::
  80. code_string = "template <typename T> T util_fn(T x, T y) { return ::sin(x) + ::cos(y); }"
  81. code_string += "template <typename T> T my_kernel(T x, T y, T val) { return ::min(val, util_fn(x, y)); }"
  82. jitted_fn = create_jit_fn(code_string, val=0.0)
  83. a = torch.rand(3, device='cuda')
  84. b = torch.rand(3, device='cuda')
  85. # invoke jitted function like a regular python function
  86. result = jitted_fn(a, b) # using default val=0.0
  87. Jiterator can be used together with python registration to override an operator's cuda kernel.
  88. Following example is overriding gelu's cuda kernel with relu.
  89. Example::
  90. code_string = "template <typename T> T my_gelu(T a) { return a > 0 ? a : 0; }"
  91. my_gelu = create_jit_fn(code_string)
  92. my_lib = torch.library.Library("aten", "IMPL")
  93. my_lib.impl('aten::gelu', my_gelu, "CUDA")
  94. # torch.nn.GELU and torch.nn.function.gelu are now overridden
  95. a = torch.rand(3, device='cuda')
  96. torch.allclose(torch.nn.functional.gelu(a), torch.nn.functional.relu(a))
  97. .. warning::
  98. This API is in beta and may change in future releases.
  99. .. warning::
  100. This API only supports up to 8 inputs and 1 output
  101. .. warning::
  102. All input tensors must live in CUDA device
  103. """
  104. return _JittedFunction(code_string, return_by_ref=False, num_outputs=1, **kwargs)
  105. def _create_multi_output_jit_fn(code_string: str, num_outputs: int, **kwargs) -> Callable:
  106. """
  107. Create a jiterator-generated cuda kernel for an elementwise op that supports returning one or more outputs.
  108. Args:
  109. code_string (str): CUDA code string to be compiled by jiterator. The entry functor must return value by reference.
  110. num_outputs(int): number of outputs return by the kernel
  111. kwargs (Dict, optional): Keyword arguments for generated function
  112. Example::
  113. code_string = "template <typename T> void my_kernel(T x, T y, T alpha, T& out) { out = -x + alpha * y; }"
  114. jitted_fn = create_jit_fn(code_string, alpha=1.0)
  115. a = torch.rand(3, device='cuda')
  116. b = torch.rand(3, device='cuda')
  117. # invoke jitted function like a regular python function
  118. result = jitted_fn(a, b, alpha=3.14)
  119. .. warning::
  120. This API is in beta and may change in future releases.
  121. .. warning::
  122. This API only supports up to 8 inputs and 8 outputs
  123. """
  124. return _JittedFunction(code_string, return_by_ref=True, num_outputs=num_outputs, **kwargs)