-
Notifications
You must be signed in to change notification settings - Fork 6
feat(nvidia): add ntops rms norm backend #616
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
Open
voltjia
wants to merge
1
commit into
master
Choose a base branch
from
feat/nvidia-ntops-rms-norm
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| import argparse | ||
| import importlib.util | ||
| import pathlib | ||
| import shutil | ||
| import sys | ||
|
|
||
| _PROJECT_DIR = pathlib.Path(__file__).resolve().parents[1] | ||
| _OPS_DIR = _PROJECT_DIR / "src" / "ninetoothed" / "ops" | ||
|
|
||
|
|
||
| def _find_op_modules(): | ||
| return { | ||
| path.parent.name: path | ||
| for path in sorted(_OPS_DIR.glob("*/build.py")) | ||
| if path.is_file() | ||
| } | ||
|
|
||
|
|
||
| def _build_manifest(output_dir): | ||
| return sorted( | ||
| str(path) | ||
| for path in pathlib.Path(output_dir).rglob("*.cpp") | ||
| if not path.name.endswith(".tmp.cpp") | ||
| ) | ||
|
|
||
|
|
||
| def _write_cmake_manifest(output_dir, sources): | ||
| manifest_path = pathlib.Path(output_dir) / "manifest.cmake" | ||
| lines = ["set(INFINIOPS_NINETOOTHED_SOURCES"] | ||
| lines.extend(f' "{source}"' for source in sources) | ||
| lines.append(")") | ||
| lines.append("") | ||
| lines.append(f'set(INFINIOPS_NINETOOTHED_INCLUDE_DIRS "{output_dir}")') | ||
| lines.append("") | ||
| manifest_path.write_text("\n".join(lines) + "\n") | ||
|
|
||
|
|
||
| def _load_op_module(op): | ||
| path = _find_op_modules()[op] | ||
| sys.path.insert(0, str(path.parent)) | ||
| spec = importlib.util.spec_from_file_location(path.stem, path) | ||
| module = importlib.util.module_from_spec(spec) | ||
| assert spec.loader is not None | ||
| sys.modules[spec.name] = module | ||
| spec.loader.exec_module(module) | ||
|
|
||
| return module | ||
|
|
||
|
|
||
| def generate(ops, *, output_dir): | ||
| op_modules = _find_op_modules() | ||
| unknown_ops = tuple(op for op in ops if op not in op_modules) | ||
|
|
||
| if unknown_ops: | ||
| raise ValueError(f"unsupported NineToothed ops: {', '.join(unknown_ops)}") | ||
|
|
||
| output_dir = pathlib.Path(output_dir) | ||
| shutil.rmtree(output_dir, ignore_errors=True) | ||
| output_dir.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| for op in ops: | ||
| module = _load_op_module(op) | ||
| module.build(output_dir) | ||
|
|
||
| sources = _build_manifest(output_dir) | ||
| _write_cmake_manifest(output_dir, sources) | ||
|
|
||
| return sources | ||
|
|
||
|
|
||
| def _parse_args(): | ||
| parser = argparse.ArgumentParser( | ||
| description="Generate NineToothed operator sources for InfiniOps." | ||
| ) | ||
| parser.add_argument("--output-dir", required=True) | ||
| parser.add_argument("--ops", nargs="+", default=tuple(_find_op_modules())) | ||
|
|
||
| return parser.parse_args() | ||
|
|
||
|
|
||
| def main(): | ||
| args = _parse_args() | ||
| generate(args.ops, output_dir=args.output_dir) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import itertools | ||
|
|
||
| import ninetoothed | ||
| import ntops | ||
|
|
||
| _BLOCK_SIZES = (256, 512) | ||
|
|
||
| _DTYPES = ("float32", "float16", "bfloat16") | ||
|
|
||
| _DEFAULT_NDIMS = (2, 3, 4) | ||
|
|
||
| _CONFIGS = tuple( | ||
| ( | ||
| (), | ||
| { | ||
| "ndim": ndim, | ||
| "num_normalized_dims": 1, | ||
| "input_dtype": dtype, | ||
| "weight_dtype": dtype, | ||
| "output_dtype": dtype, | ||
| "block_size": block_size, | ||
| }, | ||
| {}, | ||
| ) | ||
| for ndim, dtype, block_size in itertools.product( | ||
| _DEFAULT_NDIMS, | ||
| (getattr(ninetoothed, name) for name in _DTYPES), | ||
| _BLOCK_SIZES, | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| def build(output_dir): | ||
| variant_dir = output_dir / "rms_norm" | ||
| variant_dir.mkdir(parents=True, exist_ok=True) | ||
| ninetoothed.build( | ||
| ntops.kernels.rms_norm.premake, | ||
| _CONFIGS, | ||
| meta_parameters=("block_size",), | ||
| caller="cuda", | ||
| kernel_name="infini_ops_ninetoothed_rms_norm", | ||
| output_dir=variant_dir, | ||
| lazy=False, | ||
| ) |
|
voltjia marked this conversation as resolved.
voltjia marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| #ifndef INFINI_OPS_NINETOOTHED_RMS_NORM_H_ | ||
| #define INFINI_OPS_NINETOOTHED_RMS_NORM_H_ | ||
|
|
||
| #include <cassert> | ||
| #include <cstdint> | ||
| #include <vector> | ||
|
|
||
| #include "base/rms_norm.h" | ||
| #include "data_type.h" | ||
| #include "ninetoothed/tensor.h" | ||
| #include "rms_norm/infini_ops_ninetoothed_rms_norm.h" | ||
|
|
||
| namespace infini::ops { | ||
|
|
||
| template <> | ||
| class Operator<RmsNorm, Device::Type::kNvidia, 9> : public RmsNorm { | ||
| public: | ||
| using RmsNorm::RmsNorm; | ||
| using RmsNorm::operator(); | ||
|
|
||
| void operator()(const Tensor input, const Tensor weight, float eps, | ||
| Tensor out) const override { | ||
| assert(input.dtype() == out.dtype() && out.dtype() == weight.dtype() && | ||
| "operator `RmsNorm` requires all input and output tensors to have " | ||
| "the same dtype"); | ||
| assert(input.shape() == out.shape() && | ||
| "NineToothed `RmsNorm` requires input and output tensors with the " | ||
| "same shape"); | ||
| assert(weight.ndim() == 1 && weight.size(-1) == out.size(-1) && | ||
| "NineToothed `RmsNorm` requires a 1D weight matching the last " | ||
| "dimension"); | ||
| assert( | ||
| (out.ndim() == 2 || out.ndim() == 3 || out.ndim() == 4) && | ||
| "NineToothed `RmsNorm` currently supports rank-2, rank-3, and rank-4 " | ||
| "tensors"); | ||
|
|
||
| std::vector<std::uint64_t> weight_sizes; | ||
| std::vector<std::int64_t> weight_strides; | ||
| double eps_value = static_cast<double>(eps); | ||
| std::int64_t num_normalized_elements = | ||
| static_cast<std::int64_t>(out.size(-1)); | ||
| std::uint64_t empty_shape[1] = {}; | ||
| std::int64_t empty_strides[1] = {}; | ||
|
|
||
| weight_sizes.assign(out.shape().begin(), out.shape().end()); | ||
| weight_strides.assign(out.ndim(), 0); | ||
| weight_strides.back() = | ||
| weight.strides().empty() ? 1 : weight.strides().back(); | ||
|
|
||
| const int dtype_index = ninetoothed::DataTypeIndex(out.dtype()); | ||
| assert( | ||
| dtype_index >= 0 && | ||
| "NineToothed `RmsNorm` supports only float16, bfloat16, and float32"); | ||
|
|
||
| ninetoothed::Tensor input_tensor(input); | ||
| ninetoothed::Tensor weight_tensor(const_cast<void*>(weight.data()), | ||
| weight_sizes.data(), | ||
| weight_strides.data()); | ||
| ninetoothed::Tensor eps_tensor(eps_value, empty_shape, empty_strides); | ||
| ninetoothed::Tensor out_tensor(out); | ||
| ninetoothed::Tensor num_normalized_elements_tensor( | ||
| num_normalized_elements, empty_shape, empty_strides); | ||
|
|
||
| auto result = launch_infini_ops_ninetoothed_rms_norm( | ||
| static_cast<NineToothedStream>(stream_), input_tensor, weight_tensor, | ||
| eps_tensor, out_tensor, num_normalized_elements_tensor, | ||
| static_cast<int>(out.ndim()), 1, dtype_index, dtype_index, dtype_index); | ||
|
|
||
| assert(result == 0 && "NineToothed `RmsNorm` launch failed"); | ||
| } | ||
| }; | ||
|
|
||
| } // namespace infini::ops | ||
|
|
||
| #endif |
|
voltjia marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| #ifndef INFINI_OPS_NINETOOTHED_TENSOR_H_ | ||
| #define INFINI_OPS_NINETOOTHED_TENSOR_H_ | ||
|
|
||
| #include <cstdint> | ||
| #include <type_traits> | ||
|
|
||
| #include "data_type.h" | ||
| #include "tensor.h" | ||
|
|
||
| namespace infini::ops::ninetoothed { | ||
|
|
||
| inline int DataTypeIndex(DataType dtype) { | ||
| switch (dtype) { | ||
|
voltjia marked this conversation as resolved.
|
||
| case DataType::kFloat16: | ||
| return 8; | ||
| case DataType::kBFloat16: | ||
| return 9; | ||
| case DataType::kFloat32: | ||
| return 10; | ||
| default: | ||
| return -1; | ||
| } | ||
| } | ||
|
|
||
| class Tensor { | ||
| public: | ||
| explicit Tensor(const ::infini::ops::Tensor& tensor) | ||
| : Tensor(const_cast<void*>(tensor.data()), | ||
| reinterpret_cast<std::uint64_t*>( | ||
| const_cast<::infini::ops::Tensor::Size*>( | ||
| tensor.shape().data())), | ||
| reinterpret_cast<std::int64_t*>( | ||
| const_cast<::infini::ops::Tensor::Stride*>( | ||
| tensor.strides().data()))) { | ||
| static_assert(sizeof(::infini::ops::Tensor::Size) == sizeof(std::uint64_t)); | ||
| static_assert(sizeof(::infini::ops::Tensor::Stride) == | ||
| sizeof(std::int64_t)); | ||
| static_assert(std::is_unsigned_v<::infini::ops::Tensor::Size>); | ||
| static_assert(std::is_signed_v<::infini::ops::Tensor::Stride>); | ||
| } | ||
|
|
||
| Tensor(void* data, std::uint64_t* shape, std::int64_t* strides) | ||
| : data_(data), shape_(shape), strides_(strides) {} | ||
|
|
||
| template <typename T> | ||
| Tensor(T& value, std::uint64_t* shape, std::int64_t* strides) | ||
| : Tensor(static_cast<void*>(&value), shape, strides) {} | ||
|
|
||
| template <typename NineToothedTensor> | ||
| operator NineToothedTensor() const { | ||
| return NineToothedTensor{data_, shape_, strides_}; | ||
| } | ||
|
|
||
| private: | ||
| void* data_; | ||
|
voltjia marked this conversation as resolved.
|
||
|
|
||
| std::uint64_t* shape_; | ||
|
|
||
| std::int64_t* strides_; | ||
| }; | ||
|
|
||
| } // namespace infini::ops::ninetoothed | ||
|
|
||
| #endif | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.