-
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
Draft
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.
Draft
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,107 @@ | ||
| import argparse | ||
| import importlib.util | ||
| import pathlib | ||
| import shutil | ||
| import sys | ||
|
|
||
| import ninetoothed | ||
|
|
||
| _PROJECT_DIR = pathlib.Path(__file__).resolve().parents[1] | ||
| _DEFAULT_DTYPES = ("float32", "float16", "bfloat16") | ||
| _DEFAULT_RMS_NORM_NDIMS = (2, 3) | ||
| _OP_MODULES = { | ||
| "rms_norm": _PROJECT_DIR | ||
| / "src" | ||
| / "ninetoothed" | ||
| / "ops" | ||
| / "rms_norm" | ||
| / "codegen.py", | ||
| } | ||
|
|
||
|
|
||
| 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 = _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, | ||
| dtypes=_DEFAULT_DTYPES, | ||
| rms_norm_ndims=_DEFAULT_RMS_NORM_NDIMS, | ||
| ): | ||
| 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.generate( | ||
| ninetoothed, | ||
| output_dir, | ||
| dtypes=dtypes, | ||
| rms_norm_ndims=rms_norm_ndims, | ||
| ) | ||
|
|
||
| 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(_OP_MODULES)) | ||
| parser.add_argument("--dtypes", nargs="+", default=_DEFAULT_DTYPES) | ||
| parser.add_argument("--rms-norm-ndims", nargs="+", default=_DEFAULT_RMS_NORM_NDIMS) | ||
|
|
||
| return parser.parse_args() | ||
|
|
||
|
|
||
| def main(): | ||
| args = _parse_args() | ||
| generate( | ||
| args.ops, | ||
| output_dir=args.output_dir, | ||
| dtypes=tuple(args.dtypes), | ||
| rms_norm_ndims=tuple(args.rms_norm_ndims), | ||
| ) | ||
|
|
||
|
|
||
| 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,73 @@ | ||
| _BLOCK_SIZE = 256 | ||
| _DEFAULT_NDIMS = (2, 3) | ||
|
|
||
|
|
||
| def _premake( | ||
| ndim, | ||
| num_normalized_dims, | ||
| input_dtype, | ||
| weight_dtype, | ||
| output_dtype, | ||
| ): | ||
| import ntops | ||
|
|
||
| return ntops.kernels.rms_norm.premake( | ||
| ndim, | ||
| num_normalized_dims, | ||
| input_dtype=input_dtype, | ||
| weight_dtype=weight_dtype, | ||
| output_dtype=output_dtype, | ||
| block_size=_BLOCK_SIZE, | ||
| ) | ||
|
|
||
|
|
||
| def _normalize_ndims(values): | ||
| ndims = [] | ||
|
|
||
| for value in values: | ||
| ndim = int(value) | ||
|
|
||
| if ndim not in _DEFAULT_NDIMS: | ||
| raise ValueError(f"`RmsNorm` currently supports rank 2 and 3: {value!r}") | ||
|
|
||
| if ndim not in ndims: | ||
| ndims.append(ndim) | ||
|
|
||
| return tuple(ndims) | ||
|
|
||
|
|
||
| def _configs(ninetoothed, dtypes, ndims): | ||
| configs = [] | ||
|
|
||
| for ndim in _normalize_ndims(ndims): | ||
| for dtype_name in dtypes: | ||
| dtype = getattr(ninetoothed, dtype_name) | ||
| configs.append( | ||
| ( | ||
| (), | ||
| { | ||
| "ndim": ndim, | ||
| "num_normalized_dims": 1, | ||
| "input_dtype": dtype, | ||
| "weight_dtype": dtype, | ||
| "output_dtype": dtype, | ||
| }, | ||
| {}, | ||
| ) | ||
| ) | ||
|
|
||
| return tuple(configs) | ||
|
|
||
|
|
||
| def generate(ninetoothed, output_dir, *, dtypes, rms_norm_ndims): | ||
| variant_dir = output_dir / "rms_norm" | ||
| variant_dir.mkdir(parents=True, exist_ok=True) | ||
| ninetoothed.build( | ||
| _premake, | ||
| _configs(ninetoothed, dtypes, rms_norm_ndims), | ||
| meta_parameters=None, | ||
| caller="cuda", | ||
| kernel_name="infiniops_ninetoothed_rms_norm", | ||
| output_dir=variant_dir, | ||
| lazy=False, | ||
| ) |
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,70 @@ | ||
| #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/infiniops_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) && | ||
| "ninetoothed `RmsNorm` currently supports rank-2 and rank-3 " | ||
| "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"); | ||
|
|
||
| auto result = launch_infiniops_ninetoothed_rms_norm( | ||
| static_cast<NineToothedStream>(stream_), ninetoothed::Tensor(input), | ||
| ninetoothed::Tensor(const_cast<void*>(weight.data()), | ||
| weight_sizes.data(), weight_strides.data()), | ||
| ninetoothed::Tensor(eps_value, empty_shape, empty_strides), | ||
| ninetoothed::Tensor(out), | ||
| ninetoothed::Tensor(num_normalized_elements, empty_shape, | ||
| empty_strides), | ||
| static_cast<int>(out.ndim()), 1, dtype_index, dtype_index, dtype_index); | ||
|
|
||
| assert(result == 0 && "ninetoothed `RmsNorm` launch failed"); | ||
| } | ||
| }; | ||
|
|
||
| } // namespace infini::ops | ||
|
|
||
| #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.