{"repo_id":"Fuser","entity_id":"py:tests.python.conftest","uri":"program://Fuser/module/tests.python.conftest#L1-L25","kind":"module","name":"tests.python.conftest","path":"tests/python/conftest.py","language":"python","start_line":1,"end_line":25,"context_start_line":1,"context_end_line":25,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\n\n\ndef pytest_configure(config):\n \"\"\"\n Hook called after command line options have been parsed and all plugins\n and initial conftest files have been loaded.\n \"\"\"\n # Append to NVFUSER_ENABLE environment variable for all tests in this directory\n # Note: id_model is now enabled by default, so we only need extra validation\n existing = os.environ.get(\"NVFUSER_ENABLE\", \"\")\n new_options = \"id_model_extra_validation\"\n\n if existing:\n os.environ[\"NVFUSER_ENABLE\"] = f\"{existing},{new_options}\"\n else:\n os.environ[\"NVFUSER_ENABLE\"] = new_options\n\n\ndef pytest_make_parametrize_id(config, val, argname):\n return f\"{argname}={val}\"","source_hash":"fb6a76db3dcad75f3f199cc3f99d6b9add747b31de3244244b40d07d1ed36a89","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.conftest.pytest_configure","uri":"program://Fuser/function/tests.python.conftest.pytest_configure#L8-L21","kind":"function","name":"pytest_configure","path":"tests/python/conftest.py","language":"python","start_line":8,"end_line":21,"context_start_line":1,"context_end_line":25,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\n\n\ndef pytest_configure(config):\n \"\"\"\n Hook called after command line options have been parsed and all plugins\n and initial conftest files have been loaded.\n \"\"\"\n # Append to NVFUSER_ENABLE environment variable for all tests in this directory\n # Note: id_model is now enabled by default, so we only need extra validation\n existing = os.environ.get(\"NVFUSER_ENABLE\", \"\")\n new_options = \"id_model_extra_validation\"\n\n if existing:\n os.environ[\"NVFUSER_ENABLE\"] = f\"{existing},{new_options}\"\n else:\n os.environ[\"NVFUSER_ENABLE\"] = new_options\n\n\ndef pytest_make_parametrize_id(config, val, argname):\n return f\"{argname}={val}\"","source_hash":"fb6a76db3dcad75f3f199cc3f99d6b9add747b31de3244244b40d07d1ed36a89","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.conftest.pytest_make_parametrize_id","uri":"program://Fuser/function/tests.python.conftest.pytest_make_parametrize_id#L24-L25","kind":"function","name":"pytest_make_parametrize_id","path":"tests/python/conftest.py","language":"python","start_line":24,"end_line":25,"context_start_line":4,"context_end_line":25,"code":"\nimport os\n\n\ndef pytest_configure(config):\n \"\"\"\n Hook called after command line options have been parsed and all plugins\n and initial conftest files have been loaded.\n \"\"\"\n # Append to NVFUSER_ENABLE environment variable for all tests in this directory\n # Note: id_model is now enabled by default, so we only need extra validation\n existing = os.environ.get(\"NVFUSER_ENABLE\", \"\")\n new_options = \"id_model_extra_validation\"\n\n if existing:\n os.environ[\"NVFUSER_ENABLE\"] = f\"{existing},{new_options}\"\n else:\n os.environ[\"NVFUSER_ENABLE\"] = new_options\n\n\ndef pytest_make_parametrize_id(config, val, argname):\n return f\"{argname}={val}\"","source_hash":"fb6a76db3dcad75f3f199cc3f99d6b9add747b31de3244244b40d07d1ed36a89","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe","uri":"program://Fuser/module/tests.python.test_moe#L1-L201","kind":"module","name":"tests.python.test_moe","path":"tests/python/test_moe.py","language":"python","start_line":1,"end_line":201,"context_start_line":1,"context_end_line":201,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport math\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom thunder.dynamo import thunderfx\n\n\n# Sizes used in Llama 4 Maverick\n@dataclass\nclass Config:\n hidden_size: int = 5120\n intermediate_size: int = 8192\n num_routed_experts: int = 128\n num_shared_experts: int = 1\n\n\nclass SwiGLU(nn.Module):\n def __init__(self, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)\n self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)\n self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)\n )\n\n\ndef _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n for offset in offsets:\n group_sizes.append(offset - prev)\n prev = offset\n return group_sizes\n\n\n# Required otherwise, there is a graph-break.\n_grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\n\n\n# This function should be replaced with torch._grouped_mm. However,\n# torch._grouped_mm is yet to be usable because it requires offsets being\n# multiples of 16.\ndef grouped_mm(a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n if torch.compiler.is_compiling():\n return _grouped_mm(a, b, offsets)\n\n group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for group_a, group_b in zip(a.split(group_sizes), b.unbind()):\n group_outs.append(group_a @ group_b)\n return torch.cat(group_outs)\n\n\nclass GroupedLinear(nn.Module):\n def __init__(self, groups: int, in_features: int, out_features: int):\n super().__init__()\n self.weight = nn.Parameter(torch.empty(groups, in_features, out_features))\n # Initialize the weight in the same way as nn.Linear\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n\n def forward(\n self, hidden_states: torch.Tensor, offsets: torch.Tensor\n ) -> torch.Tensor:\n return grouped_mm(hidden_states, self.weight, offsets)\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size)\n\n def forward(\n self, hidden_states: torch.Tensor, offsets: torch.Tensor\n ) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states, offsets))\n * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass Llama4MoE(nn.Module):\n def __init__(self, config: Config):\n super().__init__()\n self.config = config\n self.gate = nn.Linear(config.hidden_size, config.num_routed_experts, bias=False)\n self.shared_experts = SwiGLU(\n config.hidden_size, config.intermediate_size * config.num_shared_experts\n )\n self.routed_experts = GroupedSwiGLU(\n config.num_routed_experts, config.hidden_size, config.intermediate_size\n )\n\n def run_routed_experts(self, hidden_states: torch.Tensor) -> torch.Tensor:\n batch_size, seq_len, _ = hidden_states.size()\n hidden_states = hidden_states.view(-1, hidden_states.size(-1)) # [s, h]\n\n router_logits = self.gate(hidden_states) # [s, n]\n topk_weight, topk_ids = router_logits.topk(1) # [s, 1]\n router_scores = topk_weight.sigmoid() # [s, 1]\n hidden_states = hidden_states * router_scores # [s, h]\n\n counts = torch.zeros(\n topk_ids.size(0),\n self.config.num_routed_experts,\n device=topk_ids.device,\n dtype=torch.int32,\n ) # [s, n]\n counts = counts.scatter(1, topk_ids, 1) # [s, n]\n tokens_per_expert = counts.sum(0) # [n]\n\n token_ids_sorted_by_expert_id = topk_ids.view(-1).argsort() # [s]\n tokens_sorted_by_expert_id = hidden_states[\n token_ids_sorted_by_expert_id\n ] # [s, h]\n\n # Without `torch.int32`, we see `RuntimeError: Offsets tensor must be integer (int32) tensor, but got torch.int64.`\n # from PyTorch when calling _grouped_mm.\n offsets = torch.cumsum(tokens_per_expert, 0, dtype=torch.int32) # [n]\n outs_sorted_by_expert_id = self.routed_experts(\n tokens_sorted_by_expert_id, offsets\n ) # [s, h]\n\n token_ids_sorted_by_expert_inverse_id = torch.argsort(\n token_ids_sorted_by_expert_id\n )\n outs_sorted_by_token_id = outs_sorted_by_expert_id[\n token_ids_sorted_by_expert_inverse_id\n ]\n\n return outs_sorted_by_token_id\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.shared_experts(hidden_states) + self.run_routed_experts(\n hidden_states\n )\n\n\n@contextmanager\ndef default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore\n torch.set_default_dtype(prev_dtype)\n torch.set_default_device(prev_device)\n\n\ndef test_llama4_moe_thunderfx():\n config = Config()\n\n # This is much faster than creating the module with CPU float parameters\n # and then doing `.to(\"cuda\").to(torch.bfloat16)`.\n with default_tensor_type(dtype=torch.bfloat16, device=\"cuda\"):\n model = Llama4MoE(config)\n\n # Without this, `thunderfx` falls back to `inductor` for `_grouped_mm`\n # as it doesn't have a grad-rule for the same.\n model.requires_grad_(False)\n\n batch_size, seq_len = 1, 2048\n inp = torch.randn(\n batch_size, seq_len, config.hidden_size, dtype=torch.bfloat16, device=\"cuda\"\n )\n expected = model(inp)\n\n assert expected.size() == (batch_size, seq_len, config.hidden_size)\n assert expected.dtype == torch.bfloat16\n assert expected.is_cuda\n\n tmodel = thunderfx(model, nv_enable_linear=True, nv_enable_scatter=True)\n\n with torch.no_grad():\n actual = tmodel(inp)\n\n assert len(tmodel._backend.subgraph_infos) == 1\n assert len(tmodel._backend.subgraph_infos[0].split_reasons) == 0\n # Uncomment to view thunder traces\n # print(tmodel.last_traces)\n\n torch.testing.assert_close(actual, expected, atol=1e-2, rtol=1e-2)","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.Config","uri":"program://Fuser/class/tests.python.test_moe.Config#L18-L22","kind":"class","name":"Config","path":"tests/python/test_moe.py","language":"python","start_line":18,"end_line":22,"context_start_line":1,"context_end_line":42,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport math\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom thunder.dynamo import thunderfx\n\n\n# Sizes used in Llama 4 Maverick\n@dataclass\nclass Config:\n hidden_size: int = 5120\n intermediate_size: int = 8192\n num_routed_experts: int = 128\n num_shared_experts: int = 1\n\n\nclass SwiGLU(nn.Module):\n def __init__(self, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)\n self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)\n self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)\n )\n\n\ndef _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n for offset in offsets:\n group_sizes.append(offset - prev)","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.SwiGLU","uri":"program://Fuser/class/tests.python.test_moe.SwiGLU#L25-L35","kind":"class","name":"SwiGLU","path":"tests/python/test_moe.py","language":"python","start_line":25,"end_line":35,"context_start_line":5,"context_end_line":55,"code":"import math\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom thunder.dynamo import thunderfx\n\n\n# Sizes used in Llama 4 Maverick\n@dataclass\nclass Config:\n hidden_size: int = 5120\n intermediate_size: int = 8192\n num_routed_experts: int = 128\n num_shared_experts: int = 1\n\n\nclass SwiGLU(nn.Module):\n def __init__(self, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)\n self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)\n self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)\n )\n\n\ndef _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n for offset in offsets:\n group_sizes.append(offset - prev)\n prev = offset\n return group_sizes\n\n\n# Required otherwise, there is a graph-break.\n_grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\n\n\n# This function should be replaced with torch._grouped_mm. However,\n# torch._grouped_mm is yet to be usable because it requires offsets being\n# multiples of 16.\ndef grouped_mm(a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n if torch.compiler.is_compiling():","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe._group_sizes_from_offsets","uri":"program://Fuser/function/tests.python.test_moe._group_sizes_from_offsets#L38-L44","kind":"function","name":"_group_sizes_from_offsets","path":"tests/python/test_moe.py","language":"python","start_line":38,"end_line":44,"context_start_line":18,"context_end_line":64,"code":"class Config:\n hidden_size: int = 5120\n intermediate_size: int = 8192\n num_routed_experts: int = 128\n num_shared_experts: int = 1\n\n\nclass SwiGLU(nn.Module):\n def __init__(self, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)\n self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)\n self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)\n )\n\n\ndef _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n for offset in offsets:\n group_sizes.append(offset - prev)\n prev = offset\n return group_sizes\n\n\n# Required otherwise, there is a graph-break.\n_grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\n\n\n# This function should be replaced with torch._grouped_mm. However,\n# torch._grouped_mm is yet to be usable because it requires offsets being\n# multiples of 16.\ndef grouped_mm(a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n if torch.compiler.is_compiling():\n return _grouped_mm(a, b, offsets)\n\n group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for group_a, group_b in zip(a.split(group_sizes), b.unbind()):\n group_outs.append(group_a @ group_b)\n return torch.cat(group_outs)\n\n","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.grouped_mm","uri":"program://Fuser/function/tests.python.test_moe.grouped_mm#L54-L62","kind":"function","name":"grouped_mm","path":"tests/python/test_moe.py","language":"python","start_line":54,"end_line":62,"context_start_line":34,"context_end_line":82,"code":" F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)\n )\n\n\ndef _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n for offset in offsets:\n group_sizes.append(offset - prev)\n prev = offset\n return group_sizes\n\n\n# Required otherwise, there is a graph-break.\n_grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\n\n\n# This function should be replaced with torch._grouped_mm. However,\n# torch._grouped_mm is yet to be usable because it requires offsets being\n# multiples of 16.\ndef grouped_mm(a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n if torch.compiler.is_compiling():\n return _grouped_mm(a, b, offsets)\n\n group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for group_a, group_b in zip(a.split(group_sizes), b.unbind()):\n group_outs.append(group_a @ group_b)\n return torch.cat(group_outs)\n\n\nclass GroupedLinear(nn.Module):\n def __init__(self, groups: int, in_features: int, out_features: int):\n super().__init__()\n self.weight = nn.Parameter(torch.empty(groups, in_features, out_features))\n # Initialize the weight in the same way as nn.Linear\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n\n def forward(\n self, hidden_states: torch.Tensor, offsets: torch.Tensor\n ) -> torch.Tensor:\n return grouped_mm(hidden_states, self.weight, offsets)\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size)","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.GroupedLinear","uri":"program://Fuser/class/tests.python.test_moe.GroupedLinear#L65-L75","kind":"class","name":"GroupedLinear","path":"tests/python/test_moe.py","language":"python","start_line":65,"end_line":75,"context_start_line":45,"context_end_line":95,"code":"\n\n# Required otherwise, there is a graph-break.\n_grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\n\n\n# This function should be replaced with torch._grouped_mm. However,\n# torch._grouped_mm is yet to be usable because it requires offsets being\n# multiples of 16.\ndef grouped_mm(a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n if torch.compiler.is_compiling():\n return _grouped_mm(a, b, offsets)\n\n group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for group_a, group_b in zip(a.split(group_sizes), b.unbind()):\n group_outs.append(group_a @ group_b)\n return torch.cat(group_outs)\n\n\nclass GroupedLinear(nn.Module):\n def __init__(self, groups: int, in_features: int, out_features: int):\n super().__init__()\n self.weight = nn.Parameter(torch.empty(groups, in_features, out_features))\n # Initialize the weight in the same way as nn.Linear\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n\n def forward(\n self, hidden_states: torch.Tensor, offsets: torch.Tensor\n ) -> torch.Tensor:\n return grouped_mm(hidden_states, self.weight, offsets)\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size)\n\n def forward(\n self, hidden_states: torch.Tensor, offsets: torch.Tensor\n ) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states, offsets))\n * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass Llama4MoE(nn.Module):","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.GroupedSwiGLU","uri":"program://Fuser/class/tests.python.test_moe.GroupedSwiGLU#L78-L92","kind":"class","name":"GroupedSwiGLU","path":"tests/python/test_moe.py","language":"python","start_line":78,"end_line":92,"context_start_line":58,"context_end_line":112,"code":" group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for group_a, group_b in zip(a.split(group_sizes), b.unbind()):\n group_outs.append(group_a @ group_b)\n return torch.cat(group_outs)\n\n\nclass GroupedLinear(nn.Module):\n def __init__(self, groups: int, in_features: int, out_features: int):\n super().__init__()\n self.weight = nn.Parameter(torch.empty(groups, in_features, out_features))\n # Initialize the weight in the same way as nn.Linear\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n\n def forward(\n self, hidden_states: torch.Tensor, offsets: torch.Tensor\n ) -> torch.Tensor:\n return grouped_mm(hidden_states, self.weight, offsets)\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size)\n\n def forward(\n self, hidden_states: torch.Tensor, offsets: torch.Tensor\n ) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states, offsets))\n * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass Llama4MoE(nn.Module):\n def __init__(self, config: Config):\n super().__init__()\n self.config = config\n self.gate = nn.Linear(config.hidden_size, config.num_routed_experts, bias=False)\n self.shared_experts = SwiGLU(\n config.hidden_size, config.intermediate_size * config.num_shared_experts\n )\n self.routed_experts = GroupedSwiGLU(\n config.num_routed_experts, config.hidden_size, config.intermediate_size\n )\n\n def run_routed_experts(self, hidden_states: torch.Tensor) -> torch.Tensor:\n batch_size, seq_len, _ = hidden_states.size()\n hidden_states = hidden_states.view(-1, hidden_states.size(-1)) # [s, h]\n\n router_logits = self.gate(hidden_states) # [s, n]\n topk_weight, topk_ids = router_logits.topk(1) # [s, 1]","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.Llama4MoE","uri":"program://Fuser/class/tests.python.test_moe.Llama4MoE#L95-L149","kind":"class","name":"Llama4MoE","path":"tests/python/test_moe.py","language":"python","start_line":95,"end_line":149,"context_start_line":75,"context_end_line":169,"code":" return grouped_mm(hidden_states, self.weight, offsets)\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size)\n\n def forward(\n self, hidden_states: torch.Tensor, offsets: torch.Tensor\n ) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states, offsets))\n * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass Llama4MoE(nn.Module):\n def __init__(self, config: Config):\n super().__init__()\n self.config = config\n self.gate = nn.Linear(config.hidden_size, config.num_routed_experts, bias=False)\n self.shared_experts = SwiGLU(\n config.hidden_size, config.intermediate_size * config.num_shared_experts\n )\n self.routed_experts = GroupedSwiGLU(\n config.num_routed_experts, config.hidden_size, config.intermediate_size\n )\n\n def run_routed_experts(self, hidden_states: torch.Tensor) -> torch.Tensor:\n batch_size, seq_len, _ = hidden_states.size()\n hidden_states = hidden_states.view(-1, hidden_states.size(-1)) # [s, h]\n\n router_logits = self.gate(hidden_states) # [s, n]\n topk_weight, topk_ids = router_logits.topk(1) # [s, 1]\n router_scores = topk_weight.sigmoid() # [s, 1]\n hidden_states = hidden_states * router_scores # [s, h]\n\n counts = torch.zeros(\n topk_ids.size(0),\n self.config.num_routed_experts,\n device=topk_ids.device,\n dtype=torch.int32,\n ) # [s, n]\n counts = counts.scatter(1, topk_ids, 1) # [s, n]\n tokens_per_expert = counts.sum(0) # [n]\n\n token_ids_sorted_by_expert_id = topk_ids.view(-1).argsort() # [s]\n tokens_sorted_by_expert_id = hidden_states[\n token_ids_sorted_by_expert_id\n ] # [s, h]\n\n # Without `torch.int32`, we see `RuntimeError: Offsets tensor must be integer (int32) tensor, but got torch.int64.`\n # from PyTorch when calling _grouped_mm.\n offsets = torch.cumsum(tokens_per_expert, 0, dtype=torch.int32) # [n]\n outs_sorted_by_expert_id = self.routed_experts(\n tokens_sorted_by_expert_id, offsets\n ) # [s, h]\n\n token_ids_sorted_by_expert_inverse_id = torch.argsort(\n token_ids_sorted_by_expert_id\n )\n outs_sorted_by_token_id = outs_sorted_by_expert_id[\n token_ids_sorted_by_expert_inverse_id\n ]\n\n return outs_sorted_by_token_id\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.shared_experts(hidden_states) + self.run_routed_experts(\n hidden_states\n )\n\n\n@contextmanager\ndef default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore\n torch.set_default_dtype(prev_dtype)\n torch.set_default_device(prev_device)\n\n\ndef test_llama4_moe_thunderfx():","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.default_tensor_type","uri":"program://Fuser/function/tests.python.test_moe.default_tensor_type#L153-L166","kind":"function","name":"default_tensor_type","path":"tests/python/test_moe.py","language":"python","start_line":153,"end_line":166,"context_start_line":133,"context_end_line":186,"code":" outs_sorted_by_expert_id = self.routed_experts(\n tokens_sorted_by_expert_id, offsets\n ) # [s, h]\n\n token_ids_sorted_by_expert_inverse_id = torch.argsort(\n token_ids_sorted_by_expert_id\n )\n outs_sorted_by_token_id = outs_sorted_by_expert_id[\n token_ids_sorted_by_expert_inverse_id\n ]\n\n return outs_sorted_by_token_id\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.shared_experts(hidden_states) + self.run_routed_experts(\n hidden_states\n )\n\n\n@contextmanager\ndef default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore\n torch.set_default_dtype(prev_dtype)\n torch.set_default_device(prev_device)\n\n\ndef test_llama4_moe_thunderfx():\n config = Config()\n\n # This is much faster than creating the module with CPU float parameters\n # and then doing `.to(\"cuda\").to(torch.bfloat16)`.\n with default_tensor_type(dtype=torch.bfloat16, device=\"cuda\"):\n model = Llama4MoE(config)\n\n # Without this, `thunderfx` falls back to `inductor` for `_grouped_mm`\n # as it doesn't have a grad-rule for the same.\n model.requires_grad_(False)\n\n batch_size, seq_len = 1, 2048\n inp = torch.randn(\n batch_size, seq_len, config.hidden_size, dtype=torch.bfloat16, device=\"cuda\"\n )\n expected = model(inp)\n","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.test_llama4_moe_thunderfx","uri":"program://Fuser/function/tests.python.test_moe.test_llama4_moe_thunderfx#L169-L201","kind":"function","name":"test_llama4_moe_thunderfx","path":"tests/python/test_moe.py","language":"python","start_line":169,"end_line":201,"context_start_line":149,"context_end_line":201,"code":" )\n\n\n@contextmanager\ndef default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore\n torch.set_default_dtype(prev_dtype)\n torch.set_default_device(prev_device)\n\n\ndef test_llama4_moe_thunderfx():\n config = Config()\n\n # This is much faster than creating the module with CPU float parameters\n # and then doing `.to(\"cuda\").to(torch.bfloat16)`.\n with default_tensor_type(dtype=torch.bfloat16, device=\"cuda\"):\n model = Llama4MoE(config)\n\n # Without this, `thunderfx` falls back to `inductor` for `_grouped_mm`\n # as it doesn't have a grad-rule for the same.\n model.requires_grad_(False)\n\n batch_size, seq_len = 1, 2048\n inp = torch.randn(\n batch_size, seq_len, config.hidden_size, dtype=torch.bfloat16, device=\"cuda\"\n )\n expected = model(inp)\n\n assert expected.size() == (batch_size, seq_len, config.hidden_size)\n assert expected.dtype == torch.bfloat16\n assert expected.is_cuda\n\n tmodel = thunderfx(model, nv_enable_linear=True, nv_enable_scatter=True)\n\n with torch.no_grad():\n actual = tmodel(inp)\n\n assert len(tmodel._backend.subgraph_infos) == 1\n assert len(tmodel._backend.subgraph_infos[0].split_reasons) == 0\n # Uncomment to view thunder traces\n # print(tmodel.last_traces)\n\n torch.testing.assert_close(actual, expected, atol=1e-2, rtol=1e-2)","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.__init__","uri":"program://Fuser/function/tests.python.test_moe.__init__#L96-L105","kind":"function","name":"__init__","path":"tests/python/test_moe.py","language":"python","start_line":96,"end_line":105,"context_start_line":76,"context_end_line":125,"code":"\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size)\n\n def forward(\n self, hidden_states: torch.Tensor, offsets: torch.Tensor\n ) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states, offsets))\n * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass Llama4MoE(nn.Module):\n def __init__(self, config: Config):\n super().__init__()\n self.config = config\n self.gate = nn.Linear(config.hidden_size, config.num_routed_experts, bias=False)\n self.shared_experts = SwiGLU(\n config.hidden_size, config.intermediate_size * config.num_shared_experts\n )\n self.routed_experts = GroupedSwiGLU(\n config.num_routed_experts, config.hidden_size, config.intermediate_size\n )\n\n def run_routed_experts(self, hidden_states: torch.Tensor) -> torch.Tensor:\n batch_size, seq_len, _ = hidden_states.size()\n hidden_states = hidden_states.view(-1, hidden_states.size(-1)) # [s, h]\n\n router_logits = self.gate(hidden_states) # [s, n]\n topk_weight, topk_ids = router_logits.topk(1) # [s, 1]\n router_scores = topk_weight.sigmoid() # [s, 1]\n hidden_states = hidden_states * router_scores # [s, h]\n\n counts = torch.zeros(\n topk_ids.size(0),\n self.config.num_routed_experts,\n device=topk_ids.device,\n dtype=torch.int32,\n ) # [s, n]\n counts = counts.scatter(1, topk_ids, 1) # [s, n]\n tokens_per_expert = counts.sum(0) # [n]\n\n token_ids_sorted_by_expert_id = topk_ids.view(-1).argsort() # [s]","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.forward","uri":"program://Fuser/function/tests.python.test_moe.forward#L146-L149","kind":"function","name":"forward","path":"tests/python/test_moe.py","language":"python","start_line":146,"end_line":149,"context_start_line":126,"context_end_line":169,"code":" tokens_sorted_by_expert_id = hidden_states[\n token_ids_sorted_by_expert_id\n ] # [s, h]\n\n # Without `torch.int32`, we see `RuntimeError: Offsets tensor must be integer (int32) tensor, but got torch.int64.`\n # from PyTorch when calling _grouped_mm.\n offsets = torch.cumsum(tokens_per_expert, 0, dtype=torch.int32) # [n]\n outs_sorted_by_expert_id = self.routed_experts(\n tokens_sorted_by_expert_id, offsets\n ) # [s, h]\n\n token_ids_sorted_by_expert_inverse_id = torch.argsort(\n token_ids_sorted_by_expert_id\n )\n outs_sorted_by_token_id = outs_sorted_by_expert_id[\n token_ids_sorted_by_expert_inverse_id\n ]\n\n return outs_sorted_by_token_id\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.shared_experts(hidden_states) + self.run_routed_experts(\n hidden_states\n )\n\n\n@contextmanager\ndef default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore\n torch.set_default_dtype(prev_dtype)\n torch.set_default_device(prev_device)\n\n\ndef test_llama4_moe_thunderfx():","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.test_moe.run_routed_experts","uri":"program://Fuser/function/tests.python.test_moe.run_routed_experts#L107-L144","kind":"function","name":"run_routed_experts","path":"tests/python/test_moe.py","language":"python","start_line":107,"end_line":144,"context_start_line":87,"context_end_line":164,"code":" ) -> torch.Tensor:\n return self.down_proj(\n F.silu(self.gate_proj(hidden_states, offsets))\n * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass Llama4MoE(nn.Module):\n def __init__(self, config: Config):\n super().__init__()\n self.config = config\n self.gate = nn.Linear(config.hidden_size, config.num_routed_experts, bias=False)\n self.shared_experts = SwiGLU(\n config.hidden_size, config.intermediate_size * config.num_shared_experts\n )\n self.routed_experts = GroupedSwiGLU(\n config.num_routed_experts, config.hidden_size, config.intermediate_size\n )\n\n def run_routed_experts(self, hidden_states: torch.Tensor) -> torch.Tensor:\n batch_size, seq_len, _ = hidden_states.size()\n hidden_states = hidden_states.view(-1, hidden_states.size(-1)) # [s, h]\n\n router_logits = self.gate(hidden_states) # [s, n]\n topk_weight, topk_ids = router_logits.topk(1) # [s, 1]\n router_scores = topk_weight.sigmoid() # [s, 1]\n hidden_states = hidden_states * router_scores # [s, h]\n\n counts = torch.zeros(\n topk_ids.size(0),\n self.config.num_routed_experts,\n device=topk_ids.device,\n dtype=torch.int32,\n ) # [s, n]\n counts = counts.scatter(1, topk_ids, 1) # [s, n]\n tokens_per_expert = counts.sum(0) # [n]\n\n token_ids_sorted_by_expert_id = topk_ids.view(-1).argsort() # [s]\n tokens_sorted_by_expert_id = hidden_states[\n token_ids_sorted_by_expert_id\n ] # [s, h]\n\n # Without `torch.int32`, we see `RuntimeError: Offsets tensor must be integer (int32) tensor, but got torch.int64.`\n # from PyTorch when calling _grouped_mm.\n offsets = torch.cumsum(tokens_per_expert, 0, dtype=torch.int32) # [n]\n outs_sorted_by_expert_id = self.routed_experts(\n tokens_sorted_by_expert_id, offsets\n ) # [s, h]\n\n token_ids_sorted_by_expert_inverse_id = torch.argsort(\n token_ids_sorted_by_expert_id\n )\n outs_sorted_by_token_id = outs_sorted_by_expert_id[\n token_ids_sorted_by_expert_inverse_id\n ]\n\n return outs_sorted_by_token_id\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.shared_experts(hidden_states) + self.run_routed_experts(\n hidden_states\n )\n\n\n@contextmanager\ndef default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_fusion_definitions","uri":"program://Fuser/module/tests.python.opinfo.opinfo_fusion_definitions#L1-L102","kind":"module","name":"tests.python.opinfo.opinfo_fusion_definitions","path":"tests/python/opinfo/opinfo_fusion_definitions.py","language":"python","start_line":1,"end_line":102,"context_start_line":1,"context_end_line":102,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\n\nfrom opinfo_core import OpInfo\nfrom opinfo_utils import ArgumentType, is_tensor\n\nimport sys\n\nif \"nvfuser\" in sys.modules:\n from nvfuser import FusionDefinition\n from nvfuser.pytorch_utils import (\n python_scalar_to_nvfuser_dtype,\n torch_dtype_to_nvfuser_dtype,\n )\nelse:\n from nvfuser_direct import FusionDefinition\n from nvfuser_direct.pytorch_utils import (\n python_scalar_to_nvfuser_dtype,\n torch_dtype_to_nvfuser_dtype,\n )\n\n\ndef parse_inputs_fusion_definition(fd: FusionDefinition, opinfo: OpInfo, *args):\n if len(args) == 0:\n return []\n\n nvf_args = []\n\n symbolic_parameter_list = (\n opinfo.symbolic_parameter_list\n if opinfo.symbolic_parameter_list is not None\n else [ArgumentType.Symbolic] * len(args)\n )\n\n num_symbolic_parameters = len(symbolic_parameter_list)\n assert num_symbolic_parameters >= len(\n args\n ), f\"{num_symbolic_parameters} vs {len(args)}\"\n\n for arg_type, a in zip(symbolic_parameter_list, args):\n if arg_type == ArgumentType.Symbolic:\n if isinstance(a, torch.Tensor):\n nvf_args.append(fd.from_pytorch(a))\n elif isinstance(a, list) and all(map(is_tensor, a)):\n nvf_args.append([fd.from_pytorch(inner_a) for inner_a in a])\n elif isinstance(a, list) or isinstance(a, tuple):\n nvf_args.append(fd.define_vector(a))\n else:\n # For symbolic scalars, we do not define with constant value.\n # Otherwise, it becomes a constant and is not a fusion input.\n nvf_args.append(fd.define_scalar(python_scalar_to_nvfuser_dtype(a)))\n elif arg_type == ArgumentType.ConstantScalar:\n assert not isinstance(a, torch.Tensor)\n nvf_args.append(fd.define_scalar(a))\n elif isinstance(a, torch.dtype):\n nvf_args.append(torch_dtype_to_nvfuser_dtype(a))\n else:\n assert not isinstance(a, torch.Tensor)\n assert arg_type == ArgumentType.Constant\n nvf_args.append(a)\n return nvf_args\n\n\n# This function will purposely not generate a functional FusionDefintion as\n# it lacks defining an output. It is only meant to test the error checking\n# of an operation.\ndef api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n\n\ndef default_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n result = opinfo.op(fd)(*nvf_inputs, **kwargs)\n if isinstance(result, tuple):\n for a in result:\n if a is not None:\n fd.add_output(a)\n else:\n fd.add_output(result)\n\n\ndef tensor_input_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n t1 = fd.ops.add(nvf_inputs[0], this_inputs)\n fd.add_output(t1)\n\n\ndef tensor_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n out = opinfo.op(fd)(nvf_inputs[0], **kwargs)\n\n\ndef vector_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n v0 = nvf_inputs[0].shape()\n out = opinfo.op(fd)(v0, **kwargs)","source_hash":"1d767ab9c58a75685d55748d43ba65fb10de10ccb53f16865deebbc0fa72a2af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_fusion_definitions.parse_inputs_fusion_definition","uri":"program://Fuser/function/tests.python.opinfo.opinfo_fusion_definitions.parse_inputs_fusion_definition#L27-L65","kind":"function","name":"parse_inputs_fusion_definition","path":"tests/python/opinfo/opinfo_fusion_definitions.py","language":"python","start_line":27,"end_line":65,"context_start_line":7,"context_end_line":85,"code":"\nfrom opinfo_core import OpInfo\nfrom opinfo_utils import ArgumentType, is_tensor\n\nimport sys\n\nif \"nvfuser\" in sys.modules:\n from nvfuser import FusionDefinition\n from nvfuser.pytorch_utils import (\n python_scalar_to_nvfuser_dtype,\n torch_dtype_to_nvfuser_dtype,\n )\nelse:\n from nvfuser_direct import FusionDefinition\n from nvfuser_direct.pytorch_utils import (\n python_scalar_to_nvfuser_dtype,\n torch_dtype_to_nvfuser_dtype,\n )\n\n\ndef parse_inputs_fusion_definition(fd: FusionDefinition, opinfo: OpInfo, *args):\n if len(args) == 0:\n return []\n\n nvf_args = []\n\n symbolic_parameter_list = (\n opinfo.symbolic_parameter_list\n if opinfo.symbolic_parameter_list is not None\n else [ArgumentType.Symbolic] * len(args)\n )\n\n num_symbolic_parameters = len(symbolic_parameter_list)\n assert num_symbolic_parameters >= len(\n args\n ), f\"{num_symbolic_parameters} vs {len(args)}\"\n\n for arg_type, a in zip(symbolic_parameter_list, args):\n if arg_type == ArgumentType.Symbolic:\n if isinstance(a, torch.Tensor):\n nvf_args.append(fd.from_pytorch(a))\n elif isinstance(a, list) and all(map(is_tensor, a)):\n nvf_args.append([fd.from_pytorch(inner_a) for inner_a in a])\n elif isinstance(a, list) or isinstance(a, tuple):\n nvf_args.append(fd.define_vector(a))\n else:\n # For symbolic scalars, we do not define with constant value.\n # Otherwise, it becomes a constant and is not a fusion input.\n nvf_args.append(fd.define_scalar(python_scalar_to_nvfuser_dtype(a)))\n elif arg_type == ArgumentType.ConstantScalar:\n assert not isinstance(a, torch.Tensor)\n nvf_args.append(fd.define_scalar(a))\n elif isinstance(a, torch.dtype):\n nvf_args.append(torch_dtype_to_nvfuser_dtype(a))\n else:\n assert not isinstance(a, torch.Tensor)\n assert arg_type == ArgumentType.Constant\n nvf_args.append(a)\n return nvf_args\n\n\n# This function will purposely not generate a functional FusionDefintion as\n# it lacks defining an output. It is only meant to test the error checking\n# of an operation.\ndef api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n\n\ndef default_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n result = opinfo.op(fd)(*nvf_inputs, **kwargs)\n if isinstance(result, tuple):\n for a in result:\n if a is not None:\n fd.add_output(a)\n else:\n fd.add_output(result)\n","source_hash":"1d767ab9c58a75685d55748d43ba65fb10de10ccb53f16865deebbc0fa72a2af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_fusion_definitions.api_test_fd_fn","uri":"program://Fuser/function/tests.python.opinfo.opinfo_fusion_definitions.api_test_fd_fn#L71-L73","kind":"function","name":"api_test_fd_fn","path":"tests/python/opinfo/opinfo_fusion_definitions.py","language":"python","start_line":71,"end_line":73,"context_start_line":51,"context_end_line":93,"code":" nvf_args.append(fd.define_vector(a))\n else:\n # For symbolic scalars, we do not define with constant value.\n # Otherwise, it becomes a constant and is not a fusion input.\n nvf_args.append(fd.define_scalar(python_scalar_to_nvfuser_dtype(a)))\n elif arg_type == ArgumentType.ConstantScalar:\n assert not isinstance(a, torch.Tensor)\n nvf_args.append(fd.define_scalar(a))\n elif isinstance(a, torch.dtype):\n nvf_args.append(torch_dtype_to_nvfuser_dtype(a))\n else:\n assert not isinstance(a, torch.Tensor)\n assert arg_type == ArgumentType.Constant\n nvf_args.append(a)\n return nvf_args\n\n\n# This function will purposely not generate a functional FusionDefintion as\n# it lacks defining an output. It is only meant to test the error checking\n# of an operation.\ndef api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n\n\ndef default_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n result = opinfo.op(fd)(*nvf_inputs, **kwargs)\n if isinstance(result, tuple):\n for a in result:\n if a is not None:\n fd.add_output(a)\n else:\n fd.add_output(result)\n\n\ndef tensor_input_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n t1 = fd.ops.add(nvf_inputs[0], this_inputs)\n fd.add_output(t1)\n\n","source_hash":"1d767ab9c58a75685d55748d43ba65fb10de10ccb53f16865deebbc0fa72a2af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_fusion_definitions.default_fd_fn","uri":"program://Fuser/function/tests.python.opinfo.opinfo_fusion_definitions.default_fd_fn#L76-L84","kind":"function","name":"default_fd_fn","path":"tests/python/opinfo/opinfo_fusion_definitions.py","language":"python","start_line":76,"end_line":84,"context_start_line":56,"context_end_line":102,"code":" elif arg_type == ArgumentType.ConstantScalar:\n assert not isinstance(a, torch.Tensor)\n nvf_args.append(fd.define_scalar(a))\n elif isinstance(a, torch.dtype):\n nvf_args.append(torch_dtype_to_nvfuser_dtype(a))\n else:\n assert not isinstance(a, torch.Tensor)\n assert arg_type == ArgumentType.Constant\n nvf_args.append(a)\n return nvf_args\n\n\n# This function will purposely not generate a functional FusionDefintion as\n# it lacks defining an output. It is only meant to test the error checking\n# of an operation.\ndef api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n\n\ndef default_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n result = opinfo.op(fd)(*nvf_inputs, **kwargs)\n if isinstance(result, tuple):\n for a in result:\n if a is not None:\n fd.add_output(a)\n else:\n fd.add_output(result)\n\n\ndef tensor_input_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n t1 = fd.ops.add(nvf_inputs[0], this_inputs)\n fd.add_output(t1)\n\n\ndef tensor_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n out = opinfo.op(fd)(nvf_inputs[0], **kwargs)\n\n\ndef vector_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n v0 = nvf_inputs[0].shape()\n out = opinfo.op(fd)(v0, **kwargs)","source_hash":"1d767ab9c58a75685d55748d43ba65fb10de10ccb53f16865deebbc0fa72a2af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_fusion_definitions.tensor_input_fd_fn","uri":"program://Fuser/function/tests.python.opinfo.opinfo_fusion_definitions.tensor_input_fd_fn#L87-L91","kind":"function","name":"tensor_input_fd_fn","path":"tests/python/opinfo/opinfo_fusion_definitions.py","language":"python","start_line":87,"end_line":91,"context_start_line":67,"context_end_line":102,"code":"\n# This function will purposely not generate a functional FusionDefintion as\n# it lacks defining an output. It is only meant to test the error checking\n# of an operation.\ndef api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n\n\ndef default_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n result = opinfo.op(fd)(*nvf_inputs, **kwargs)\n if isinstance(result, tuple):\n for a in result:\n if a is not None:\n fd.add_output(a)\n else:\n fd.add_output(result)\n\n\ndef tensor_input_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n t1 = fd.ops.add(nvf_inputs[0], this_inputs)\n fd.add_output(t1)\n\n\ndef tensor_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n out = opinfo.op(fd)(nvf_inputs[0], **kwargs)\n\n\ndef vector_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n v0 = nvf_inputs[0].shape()\n out = opinfo.op(fd)(v0, **kwargs)","source_hash":"1d767ab9c58a75685d55748d43ba65fb10de10ccb53f16865deebbc0fa72a2af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_fusion_definitions.tensor_api_test_fd_fn","uri":"program://Fuser/function/tests.python.opinfo.opinfo_fusion_definitions.tensor_api_test_fd_fn#L94-L96","kind":"function","name":"tensor_api_test_fd_fn","path":"tests/python/opinfo/opinfo_fusion_definitions.py","language":"python","start_line":94,"end_line":96,"context_start_line":74,"context_end_line":102,"code":"\n\ndef default_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n result = opinfo.op(fd)(*nvf_inputs, **kwargs)\n if isinstance(result, tuple):\n for a in result:\n if a is not None:\n fd.add_output(a)\n else:\n fd.add_output(result)\n\n\ndef tensor_input_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n t1 = fd.ops.add(nvf_inputs[0], this_inputs)\n fd.add_output(t1)\n\n\ndef tensor_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n out = opinfo.op(fd)(nvf_inputs[0], **kwargs)\n\n\ndef vector_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n v0 = nvf_inputs[0].shape()\n out = opinfo.op(fd)(v0, **kwargs)","source_hash":"1d767ab9c58a75685d55748d43ba65fb10de10ccb53f16865deebbc0fa72a2af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_fusion_definitions.vector_api_test_fd_fn","uri":"program://Fuser/function/tests.python.opinfo.opinfo_fusion_definitions.vector_api_test_fd_fn#L99-L102","kind":"function","name":"vector_api_test_fd_fn","path":"tests/python/opinfo/opinfo_fusion_definitions.py","language":"python","start_line":99,"end_line":102,"context_start_line":79,"context_end_line":102,"code":" if isinstance(result, tuple):\n for a in result:\n if a is not None:\n fd.add_output(a)\n else:\n fd.add_output(result)\n\n\ndef tensor_input_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n this_inputs = opinfo.op(fd)(**kwargs)\n t1 = fd.ops.add(nvf_inputs[0], this_inputs)\n fd.add_output(t1)\n\n\ndef tensor_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n out = opinfo.op(fd)(nvf_inputs[0], **kwargs)\n\n\ndef vector_api_test_fd_fn(fd: FusionDefinition, opinfo: OpInfo, *args, **kwargs):\n nvf_inputs = parse_inputs_fusion_definition(fd, opinfo, *args)\n v0 = nvf_inputs[0].shape()\n out = opinfo.op(fd)(v0, **kwargs)","source_hash":"1d767ab9c58a75685d55748d43ba65fb10de10ccb53f16865deebbc0fa72a2af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core","uri":"program://Fuser/module/tests.python.opinfo.opinfo_core#L1-L130","kind":"module","name":"tests.python.opinfo.opinfo_core","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":1,"end_line":130,"context_start_line":1,"context_end_line":130,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nfrom opinfo_utils import (\n all_dtypes_except_reduced,\n ArgumentType,\n torch_to_python_dtype_map,\n)\nfrom typing import Callable, Optional\nimport torch\nfrom enum import Enum\nfrom dataclasses import dataclass, field\n\n\nclass ReferenceType(Enum):\n Pytorch = 0\n Jax = 1\n Numpy = 2\n Python = 3\n\n\n@dataclass\nclass ErrorSample:\n kwargs: dict\n ex_str: str\n ex_type: Exception = RuntimeError\n\n\n@dataclass\nclass Domain:\n low: int\n high: int\n\n\nclass SampleInput:\n \"\"\"Represents sample inputs to a function.\"\"\"\n\n __slots__ = [\n \"args\",\n \"kwargs\",\n ]\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def __repr__(self):\n return f\"[SampleInput args={self.args} kwargs={self.kwargs}]\"\n\n def jax(self):\n from opinfo_utils import JAX_AVAILABLE\n\n assert JAX_AVAILABLE\n\n import jax.numpy as jnp\n from opinfo_utils import torch_to_jax_dtype_map\n\n def to_jax(t):\n if isinstance(t, torch.Tensor):\n return jnp.array(t.cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_jax_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_jax, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n def python(self):\n # Flatten Pytorch Tensors into Python Lists\n def to_python(t):\n if isinstance(t, torch.Tensor):\n return list(t.flatten().cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_python_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_python, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n\n@dataclass\nclass OpInfo:\n \"\"\"Operator information and helper functions for acquiring it.\"\"\"\n\n op: Callable\n\n name: str\n\n # Set of valid inputs for this operation\n domain: Domain = field(default_factory=lambda: Domain(None, None))\n\n # Set of valid dtypes for this operation\n dtypes: tuple = all_dtypes_except_reduced\n\n # Generates valid inputs\n sample_input_generator: Callable = None\n\n # Generates error inputs\n error_input_generator: Callable = None\n\n # Function of FusionDefintion operations for valid inputs\n fd_correctness_fn: Callable = None\n\n # Function of FusionDefintion operations for error inputs\n fd_error_input_fn: Callable = None\n\n # Reference function for operation\n reference: Callable = None\n\n # Designate which framework defines the reference\n reference_type: ReferenceType = ReferenceType.Pytorch\n\n # Nvfuser requires reduction axes to be constant values.\n # symbolic_parameter_list specifies whether an operation's parameters are symbolic.\n # All keyword arguments are considered constant.\n # If symbolic_parameter_list is None, then we assume all parameters to be symbolic.\n symbolic_parameter_list: Optional[list[ArgumentType]] = None\n\n # Enable check_cpp_translation test\n # Tests that translation from CPP Fusion back to Python FusionDefinition is correct.\n is_clonable: bool = False\n\n # Test operation using direct bindings python API\n supports_direct_bindings: bool = True","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.ReferenceType","uri":"program://Fuser/class/tests.python.opinfo.opinfo_core.ReferenceType#L17-L21","kind":"class","name":"ReferenceType","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":17,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nfrom opinfo_utils import (\n all_dtypes_except_reduced,\n ArgumentType,\n torch_to_python_dtype_map,\n)\nfrom typing import Callable, Optional\nimport torch\nfrom enum import Enum\nfrom dataclasses import dataclass, field\n\n\nclass ReferenceType(Enum):\n Pytorch = 0\n Jax = 1\n Numpy = 2\n Python = 3\n\n\n@dataclass\nclass ErrorSample:\n kwargs: dict\n ex_str: str\n ex_type: Exception = RuntimeError\n\n\n@dataclass\nclass Domain:\n low: int\n high: int\n\n\nclass SampleInput:\n \"\"\"Represents sample inputs to a function.\"\"\"\n\n __slots__ = [\n \"args\",","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.ErrorSample","uri":"program://Fuser/class/tests.python.opinfo.opinfo_core.ErrorSample#L25-L28","kind":"class","name":"ErrorSample","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":25,"end_line":28,"context_start_line":5,"context_end_line":48,"code":"\nfrom opinfo_utils import (\n all_dtypes_except_reduced,\n ArgumentType,\n torch_to_python_dtype_map,\n)\nfrom typing import Callable, Optional\nimport torch\nfrom enum import Enum\nfrom dataclasses import dataclass, field\n\n\nclass ReferenceType(Enum):\n Pytorch = 0\n Jax = 1\n Numpy = 2\n Python = 3\n\n\n@dataclass\nclass ErrorSample:\n kwargs: dict\n ex_str: str\n ex_type: Exception = RuntimeError\n\n\n@dataclass\nclass Domain:\n low: int\n high: int\n\n\nclass SampleInput:\n \"\"\"Represents sample inputs to a function.\"\"\"\n\n __slots__ = [\n \"args\",\n \"kwargs\",\n ]\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.Domain","uri":"program://Fuser/class/tests.python.opinfo.opinfo_core.Domain#L32-L34","kind":"class","name":"Domain","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":32,"end_line":34,"context_start_line":12,"context_end_line":54,"code":"import torch\nfrom enum import Enum\nfrom dataclasses import dataclass, field\n\n\nclass ReferenceType(Enum):\n Pytorch = 0\n Jax = 1\n Numpy = 2\n Python = 3\n\n\n@dataclass\nclass ErrorSample:\n kwargs: dict\n ex_str: str\n ex_type: Exception = RuntimeError\n\n\n@dataclass\nclass Domain:\n low: int\n high: int\n\n\nclass SampleInput:\n \"\"\"Represents sample inputs to a function.\"\"\"\n\n __slots__ = [\n \"args\",\n \"kwargs\",\n ]\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def __repr__(self):\n return f\"[SampleInput args={self.args} kwargs={self.kwargs}]\"\n\n def jax(self):\n from opinfo_utils import JAX_AVAILABLE\n","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.SampleInput","uri":"program://Fuser/class/tests.python.opinfo.opinfo_core.SampleInput#L37-L84","kind":"class","name":"SampleInput","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":37,"end_line":84,"context_start_line":17,"context_end_line":104,"code":"class ReferenceType(Enum):\n Pytorch = 0\n Jax = 1\n Numpy = 2\n Python = 3\n\n\n@dataclass\nclass ErrorSample:\n kwargs: dict\n ex_str: str\n ex_type: Exception = RuntimeError\n\n\n@dataclass\nclass Domain:\n low: int\n high: int\n\n\nclass SampleInput:\n \"\"\"Represents sample inputs to a function.\"\"\"\n\n __slots__ = [\n \"args\",\n \"kwargs\",\n ]\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def __repr__(self):\n return f\"[SampleInput args={self.args} kwargs={self.kwargs}]\"\n\n def jax(self):\n from opinfo_utils import JAX_AVAILABLE\n\n assert JAX_AVAILABLE\n\n import jax.numpy as jnp\n from opinfo_utils import torch_to_jax_dtype_map\n\n def to_jax(t):\n if isinstance(t, torch.Tensor):\n return jnp.array(t.cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_jax_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_jax, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n def python(self):\n # Flatten Pytorch Tensors into Python Lists\n def to_python(t):\n if isinstance(t, torch.Tensor):\n return list(t.flatten().cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_python_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_python, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n\n@dataclass\nclass OpInfo:\n \"\"\"Operator information and helper functions for acquiring it.\"\"\"\n\n op: Callable\n\n name: str\n\n # Set of valid inputs for this operation\n domain: Domain = field(default_factory=lambda: Domain(None, None))\n\n # Set of valid dtypes for this operation\n dtypes: tuple = all_dtypes_except_reduced\n\n # Generates valid inputs\n sample_input_generator: Callable = None\n\n # Generates error inputs","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.OpInfo","uri":"program://Fuser/class/tests.python.opinfo.opinfo_core.OpInfo#L88-L130","kind":"class","name":"OpInfo","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":88,"end_line":130,"context_start_line":68,"context_end_line":130,"code":" # TODO Add support for kwargs\n args = map(to_jax, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n def python(self):\n # Flatten Pytorch Tensors into Python Lists\n def to_python(t):\n if isinstance(t, torch.Tensor):\n return list(t.flatten().cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_python_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_python, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n\n@dataclass\nclass OpInfo:\n \"\"\"Operator information and helper functions for acquiring it.\"\"\"\n\n op: Callable\n\n name: str\n\n # Set of valid inputs for this operation\n domain: Domain = field(default_factory=lambda: Domain(None, None))\n\n # Set of valid dtypes for this operation\n dtypes: tuple = all_dtypes_except_reduced\n\n # Generates valid inputs\n sample_input_generator: Callable = None\n\n # Generates error inputs\n error_input_generator: Callable = None\n\n # Function of FusionDefintion operations for valid inputs\n fd_correctness_fn: Callable = None\n\n # Function of FusionDefintion operations for error inputs\n fd_error_input_fn: Callable = None\n\n # Reference function for operation\n reference: Callable = None\n\n # Designate which framework defines the reference\n reference_type: ReferenceType = ReferenceType.Pytorch\n\n # Nvfuser requires reduction axes to be constant values.\n # symbolic_parameter_list specifies whether an operation's parameters are symbolic.\n # All keyword arguments are considered constant.\n # If symbolic_parameter_list is None, then we assume all parameters to be symbolic.\n symbolic_parameter_list: Optional[list[ArgumentType]] = None\n\n # Enable check_cpp_translation test\n # Tests that translation from CPP Fusion back to Python FusionDefinition is correct.\n is_clonable: bool = False\n\n # Test operation using direct bindings python API\n supports_direct_bindings: bool = True","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.__init__","uri":"program://Fuser/function/tests.python.opinfo.opinfo_core.__init__#L45-L47","kind":"function","name":"__init__","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":45,"end_line":47,"context_start_line":25,"context_end_line":67,"code":"class ErrorSample:\n kwargs: dict\n ex_str: str\n ex_type: Exception = RuntimeError\n\n\n@dataclass\nclass Domain:\n low: int\n high: int\n\n\nclass SampleInput:\n \"\"\"Represents sample inputs to a function.\"\"\"\n\n __slots__ = [\n \"args\",\n \"kwargs\",\n ]\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def __repr__(self):\n return f\"[SampleInput args={self.args} kwargs={self.kwargs}]\"\n\n def jax(self):\n from opinfo_utils import JAX_AVAILABLE\n\n assert JAX_AVAILABLE\n\n import jax.numpy as jnp\n from opinfo_utils import torch_to_jax_dtype_map\n\n def to_jax(t):\n if isinstance(t, torch.Tensor):\n return jnp.array(t.cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_jax_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.__repr__","uri":"program://Fuser/function/tests.python.opinfo.opinfo_core.__repr__#L49-L50","kind":"function","name":"__repr__","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":49,"end_line":50,"context_start_line":29,"context_end_line":70,"code":"\n\n@dataclass\nclass Domain:\n low: int\n high: int\n\n\nclass SampleInput:\n \"\"\"Represents sample inputs to a function.\"\"\"\n\n __slots__ = [\n \"args\",\n \"kwargs\",\n ]\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def __repr__(self):\n return f\"[SampleInput args={self.args} kwargs={self.kwargs}]\"\n\n def jax(self):\n from opinfo_utils import JAX_AVAILABLE\n\n assert JAX_AVAILABLE\n\n import jax.numpy as jnp\n from opinfo_utils import torch_to_jax_dtype_map\n\n def to_jax(t):\n if isinstance(t, torch.Tensor):\n return jnp.array(t.cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_jax_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_jax, self.args)\n return SampleInput(*args, *self.kwargs.values())","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.jax","uri":"program://Fuser/function/tests.python.opinfo.opinfo_core.jax#L52-L70","kind":"function","name":"jax","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":52,"end_line":70,"context_start_line":32,"context_end_line":90,"code":"class Domain:\n low: int\n high: int\n\n\nclass SampleInput:\n \"\"\"Represents sample inputs to a function.\"\"\"\n\n __slots__ = [\n \"args\",\n \"kwargs\",\n ]\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def __repr__(self):\n return f\"[SampleInput args={self.args} kwargs={self.kwargs}]\"\n\n def jax(self):\n from opinfo_utils import JAX_AVAILABLE\n\n assert JAX_AVAILABLE\n\n import jax.numpy as jnp\n from opinfo_utils import torch_to_jax_dtype_map\n\n def to_jax(t):\n if isinstance(t, torch.Tensor):\n return jnp.array(t.cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_jax_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_jax, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n def python(self):\n # Flatten Pytorch Tensors into Python Lists\n def to_python(t):\n if isinstance(t, torch.Tensor):\n return list(t.flatten().cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_python_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_python, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n\n@dataclass\nclass OpInfo:\n \"\"\"Operator information and helper functions for acquiring it.\"\"\"\n","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.python","uri":"program://Fuser/function/tests.python.opinfo.opinfo_core.python#L72-L84","kind":"function","name":"python","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":72,"end_line":84,"context_start_line":52,"context_end_line":104,"code":" def jax(self):\n from opinfo_utils import JAX_AVAILABLE\n\n assert JAX_AVAILABLE\n\n import jax.numpy as jnp\n from opinfo_utils import torch_to_jax_dtype_map\n\n def to_jax(t):\n if isinstance(t, torch.Tensor):\n return jnp.array(t.cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_jax_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_jax, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n def python(self):\n # Flatten Pytorch Tensors into Python Lists\n def to_python(t):\n if isinstance(t, torch.Tensor):\n return list(t.flatten().cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_python_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_python, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n\n@dataclass\nclass OpInfo:\n \"\"\"Operator information and helper functions for acquiring it.\"\"\"\n\n op: Callable\n\n name: str\n\n # Set of valid inputs for this operation\n domain: Domain = field(default_factory=lambda: Domain(None, None))\n\n # Set of valid dtypes for this operation\n dtypes: tuple = all_dtypes_except_reduced\n\n # Generates valid inputs\n sample_input_generator: Callable = None\n\n # Generates error inputs","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.to_jax","uri":"program://Fuser/function/tests.python.opinfo.opinfo_core.to_jax#L60-L65","kind":"function","name":"to_jax","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":60,"end_line":65,"context_start_line":40,"context_end_line":85,"code":" __slots__ = [\n \"args\",\n \"kwargs\",\n ]\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def __repr__(self):\n return f\"[SampleInput args={self.args} kwargs={self.kwargs}]\"\n\n def jax(self):\n from opinfo_utils import JAX_AVAILABLE\n\n assert JAX_AVAILABLE\n\n import jax.numpy as jnp\n from opinfo_utils import torch_to_jax_dtype_map\n\n def to_jax(t):\n if isinstance(t, torch.Tensor):\n return jnp.array(t.cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_jax_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_jax, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n def python(self):\n # Flatten Pytorch Tensors into Python Lists\n def to_python(t):\n if isinstance(t, torch.Tensor):\n return list(t.flatten().cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_python_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_python, self.args)\n return SampleInput(*args, *self.kwargs.values())\n","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_core.to_python","uri":"program://Fuser/function/tests.python.opinfo.opinfo_core.to_python#L74-L79","kind":"function","name":"to_python","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":74,"end_line":79,"context_start_line":54,"context_end_line":99,"code":"\n assert JAX_AVAILABLE\n\n import jax.numpy as jnp\n from opinfo_utils import torch_to_jax_dtype_map\n\n def to_jax(t):\n if isinstance(t, torch.Tensor):\n return jnp.array(t.cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_jax_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_jax, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n def python(self):\n # Flatten Pytorch Tensors into Python Lists\n def to_python(t):\n if isinstance(t, torch.Tensor):\n return list(t.flatten().cpu().numpy())\n if isinstance(t, torch.dtype):\n return torch_to_python_dtype_map[t]\n return t\n\n # Note: We assume arguments have flat hierarchy.\n # TODO Add support for kwargs\n args = map(to_python, self.args)\n return SampleInput(*args, *self.kwargs.values())\n\n\n@dataclass\nclass OpInfo:\n \"\"\"Operator information and helper functions for acquiring it.\"\"\"\n\n op: Callable\n\n name: str\n\n # Set of valid inputs for this operation\n domain: Domain = field(default_factory=lambda: Domain(None, None))\n\n # Set of valid dtypes for this operation\n dtypes: tuple = all_dtypes_except_reduced","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators","uri":"program://Fuser/module/tests.python.opinfo.opinfo_input_generators#L1-L2108","kind":"module","name":"tests.python.opinfo.opinfo_input_generators","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1,"end_line":2108,"context_start_line":1,"context_end_line":2108,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport itertools\nfrom functools import partial, wraps\n\nimport math\nimport torch\nfrom torch.testing import make_tensor\nimport random\nfrom numbers import Number\n\nfrom opinfo_core import OpInfo, SampleInput, ErrorSample, Domain\nfrom opinfo_utils import (\n make_number,\n find_nonmatching_dtype,\n is_floating_dtype,\n float_complex_dtypes,\n complex_dtypes,\n)\nimport sys\n\nif \"nvfuser\" in sys.modules:\n from nvfuser import DataType\n from nvfuser.pytorch_utils import torch_dtype_to_nvfuser_dtype\nelse:\n from nvfuser_direct import DataType\n from nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\n\nMINIMUM_SYMBOLIC_SIZE = -1\nINT64_MAX = 2**63 - 1\nMAX_TENSOR_DIMS = 8\n\n\n# Determine if a number is with desired Domain [low, high)\n# The domain is half-open. The lower limit is inclusive while the upper limit is exclusive.\ndef is_within_domain(domain: Domain, a: Number, exclude_zero: bool = False):\n # comparison operators are not defined for complex numbers\n if isinstance(a, complex):\n return True\n\n if domain.low is not None and domain.low > a:\n return False\n\n if domain.high is not None and a >= domain.high:\n return False\n\n if exclude_zero and a == 0:\n return False\n\n return True\n\n\ndef _extremal_values(dtype: torch.dtype):\n _float_vals = (float(\"inf\"), float(\"-inf\"), float(\"nan\"))\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n _int16_vals = (-32768, 32767)\n _int32_vals = (-2147483648, 2147483647)\n _int64_vals = (-9223372036854775808, 9223372036854775807)\n\n if dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n return _complex_vals\n elif dtype is torch.int16:\n return _int16_vals\n elif dtype is torch.int32:\n return _int32_vals\n elif dtype is torch.int64:\n return _int64_vals\n else:\n raise ValueError(f\"Unsupported dtype --- {dtype}\")\n\n\ndef _large_values(dtype: torch.dtype):\n _int_vals = (-1113, 1113, -10701, 10701)\n _float16_vals = (-501, 501, -1001.2, 1001.2, -13437.7, 13437.7)\n _float_vals = _float16_vals + (-4988429.2, 4988429.2, -1e20, 1e20)\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n\n if dtype == torch.float16:\n return _float16_vals\n elif dtype in (torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n print(_complex_vals)\n return _complex_vals\n elif dtype in (torch.int16, torch.int32, torch.int64):\n return _int_vals\n else:\n raise ValueError(f\"Unsupported dtype --- {dtype}\")\n\n\ndef _small_values(dtype: torch.dtype):\n eps = 1e-5\n _int_vals = (0, -1, 1, -55, 55, -127, 127, -128)\n _float_vals = (\n 0.0,\n -0.0,\n -1e-3,\n 1e-3,\n -0.25,\n 0.25,\n -1.0,\n 1.0,\n -math.e / 2.0,\n math.e / 2.0,\n -math.e + eps,\n math.e - eps,\n -math.e,\n math.e,\n -math.e - eps,\n math.e + eps,\n )\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n\n if dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n return _complex_vals\n elif dtype in (torch.int16, torch.int32, torch.int64):\n return _int_vals\n else:\n raise ValueError(f\"Unsupported dtype --- {dtype}\")\n\n\ndef broadcast_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # jax.lax.broadcast(operand, sizes)\n # add new dimensions to left-hand-side of tensor\n # dims = tuple(range(len(sizes), len(sizes) + np.ndim(operand)))\n # return broadcast_in_dim(operand, tuple(sizes) + np.shape(operand), dims)\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n fewer_original_axes = (\n ([2, 3], [True, False]),\n RuntimeError,\n \"Invalid broadcast, number of false entries in is_broadcast_dim expected to be\",\n )\n\n greater_original_axes = (\n ([2, 3], [True, False, False, False]),\n RuntimeError,\n \"Invalid broadcast, number of false entries in is_broadcast_dim expected to be\",\n )\n\n error_cases = [\n fewer_original_axes,\n greater_original_axes,\n ]\n for es in error_cases:\n ex_case, ex_type, ex_str = es\n input_shape, bcast_dims = ex_case\n input_tensor = make_arg(input_shape)\n yield SampleInput(input_tensor, bcast_dims), ex_type, ex_str\n\n\ndef broadcast_in_dim_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # The first 5 test cases below are taken from JAX's broadcast_in_dim tests\n # https://github.com/google/jax/blob/main/tests/lax_test.py#L1171\n # input shape, output shape, bcast_dims\n cases = (\n ([2], [2, 2], [0]),\n ([2], [2, 2], [1]),\n ([2], [2, 3], [0]),\n ([], [2, 3], []),\n ([1], [2, 3], [1]),\n ((4, 6, 3, 1), (5, 4, 7, 6, 3, 6, 6), (1, 3, 4, 5)),\n )\n\n for input_shape, output_shape, bcast_dims in cases:\n input_tensor = make_arg(input_shape)\n if op.name == \"broadcast_in_dim_symbolic\":\n bcast_shaped_tensor = make_arg(output_shape)\n yield SampleInput(input_tensor, bcast_shaped_tensor, bcast_dims)\n else:\n yield SampleInput(input_tensor, output_shape, bcast_dims)\n\n\ndef broadcast_in_dim_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # jax.lax.broadcast_in_dim(operand, shape, broadcast_dimensions)\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # 1. Every dimension in the input tensor must be used in broadcast_dimensions.\n missing_axis_in_bcast_dims = (\n ([2, 2], [2, 2, 3], [0]),\n RuntimeError,\n \"The broadcast dimensions should match the input dimensions.\",\n )\n\n # 2. New shape has weakly more dimentions than the original tensor.\n fewer_dims_in_output_shape = (\n ([2, 2], [2], [0]),\n RuntimeError,\n \"The new shape is expected to be greater-then-or-equal to the input\",\n )\n\n # 3. Each broadcast dimension is within the new shape.\n out_of_bounds_broadcast_dimensions = (\n ([2, 2], [2, 2], [0, 2]),\n RuntimeError,\n \"Invalid broadcast_dims value.\",\n )\n\n # 4. The original tensor is not broadcastable to desired shape.\n # tensor.shape[idx] == 1 or tensor.shape[idx] == output_shape[new_idx]\n #\n # Jax Exception:\n # TypeError: broadcast_in_dim operand dimension sizes must either be 1,\n # or be equal to their corresponding dimensions in the target broadcast shape;\n # got operand of shape (2, 3), target broadcast shape (2, 3, 4), broadcast_dimensions (0, 2)\n not_broadcastable = (\n ([2, 3], [2, 3, 4], [0, 2]),\n RuntimeError,\n \"Invalid broadcast_dims value.\",\n )\n\n # 5. TypeError: broadcast_in_dim shape must have every element be nonnegative, got (-1, 2, 3).\n negative_shape = (\n ([2, 3], [2, 3, -1], [0, 1]),\n RuntimeError,\n \"Invalid broadcast_dims value.\",\n )\n\n # TODO add exceptions for not_broadcastable, negative output shape\n error_cases = [\n missing_axis_in_bcast_dims,\n fewer_dims_in_output_shape,\n out_of_bounds_broadcast_dimensions,\n # not_broadcastable,\n # negative_shape,\n ]\n for es in error_cases:\n ex_case, ex_type, ex_str = es\n input_shape, output_shape, bcast_dims = ex_case\n input_tensor = make_arg(input_shape)\n if op.name == \"broadcast_in_dim_symbolic\":\n bcast_shaped_tensor = make_arg(output_shape)\n yield SampleInput(\n input_tensor, bcast_shaped_tensor, bcast_dims\n ), ex_type, ex_str\n else:\n yield SampleInput(input_tensor, output_shape, bcast_dims), ex_type, ex_str\n\n\ndef cat_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # concatenating tensors along singleton, broadcast dimensions is unsupported by nvFuser.\n # https://github.com/NVIDIA/Fuser/issues/224\n # shapes, dim\n cases = [\n ([(3,)], 0), # single tensor provided\n # 1D\n ([(2,), (3,)], 0),\n ([(2,), (4,)], 0),\n ([(0,), (2,)], 0),\n ([(0,), (2,)], -1),\n ([(2, 3), (2, 4)], 1),\n ([(2, 3), (2, 4), (2, 5)], 1),\n ]\n\n for shapes, dim in cases:\n yield SampleInput([make_arg(s) for s in shapes], dim)\n\n\ndef cat_error_generator(op, dtype=torch.float32, requires_grad: bool = False, **kwargs):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n # shapes, dim, exception type, exception string\n empty_input_tensors = (\n ([], 0),\n RuntimeError,\n \"Attempting to concatenate empty list of tensors\",\n )\n positive_dim = (([(1,), (2,)], 1), RuntimeError, \"Invalid dimension to cat\")\n negative_dim = (([(2,), (2,)], -2), RuntimeError, \"Invalid dimension to cat\")\n # All tensors must have same number of dimension\"\n ndims_mismatch = (\n ([(2,), (2, 3)], 0),\n RuntimeError,\n \"Unexpected number of dimensions\",\n )\n # All tensors must have same shape except for the cat dimension\n shape_mismatch = (\n ([(2, 3), (4, 5)], 0),\n RuntimeError,\n \"a conflict was found with 2 different sizes\",\n )\n\n error_cases = [\n empty_input_tensors,\n positive_dim,\n negative_dim,\n ndims_mismatch,\n shape_mismatch,\n ]\n\n for case, ex_type, ex_str in error_cases:\n shapes, dim = case\n yield SampleInput([make_arg(s) for s in shapes], dim), ex_type, ex_str\n\n\ndef define_tensor_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n \"define_tensor\",\n [](FusionDefinition& self,\n std::vector& sizes,\n std::vector& strides,\n PrimDataType dtype = DataType::Float,\n bool static_sizes = false,\n bool is_cpu = false) -> Tensor {\n ---\n \"define_tensor\",\n [](FusionDefinition& self,\n std::vector& shape,\n std::vector>& contiguity,\n PrimDataType dtype = DataType::Float,\n bool is_cpu = false) -> Tensor {\n \"\"\"\n\n check_size_contiguity_match = ErrorSample(\n {\n \"shape\": [-1, -1],\n \"contiguity\": [True, True, True],\n \"dtype\": DataType.Float,\n },\n \"Length of contiguity argument (3) must match that of shape argument (2)\",\n )\n\n check_empty_tensor_size = ErrorSample(\n {\"shape\": [], \"contiguity\": []},\n \"Empty tensor is unsupported.\",\n )\n\n check_max_tensor_size = ErrorSample(\n {\n \"shape\": [-1 for _ in range(MAX_TENSOR_DIMS + 1)],\n \"contiguity\": [True for _ in range(MAX_TENSOR_DIMS + 1)],\n },\n \"The specified tensor dimensionality exceeds the max tensor size for nvfuser.\",\n )\n\n check_above_size_range = ErrorSample(\n {\"shape\": [INT64_MAX + 1], \"contiguity\": [True]},\n \"define_tensor(): incompatible function arguments\",\n TypeError,\n )\n\n check_below_size_range = ErrorSample(\n {\"shape\": [MINIMUM_SYMBOLIC_SIZE - 1], \"contiguity\": [True]},\n \"The value -2 at index 0 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1)\",\n )\n\n check_contiguity_unknown_values = ErrorSample(\n {\"shape\": [10], \"contiguity\": [-1]},\n \"define_tensor(): incompatible function arguments.\",\n TypeError,\n )\n\n check_shape_unknown_dtypes = ErrorSample(\n {\"shape\": [10.0], \"contiguity\": [True]},\n \"define_tensor(): incompatible function arguments.\",\n TypeError,\n )\n\n check_stride_order_duplicate = ErrorSample(\n {\n \"shape\": [-1, -1, -1],\n \"contiguity\": [True, True, True],\n \"stride_order\": [0, 1, 1],\n },\n \"duplicated stride_order entries\",\n RuntimeError,\n )\n\n check_stride_order_out_of_range = ErrorSample(\n {\n \"shape\": [-1, -1, -1],\n \"contiguity\": [True, True, True],\n \"stride_order\": [0, 1, 5],\n },\n \"stride_order argument is out of range\",\n RuntimeError,\n )\n\n check_stride_order_out_of_negative_range = ErrorSample(\n {\n \"shape\": [-1, -1, -1],\n \"contiguity\": [True, True, True],\n \"stride_order\": [0, 1, -4],\n },\n \"stride_order argument is out of range\",\n RuntimeError,\n )\n\n # TODO: Fix empty and maximum tensor dimensionality error checks.\n # TODO: Add invalid argument checks for contiguity.\n error_cases = [\n check_size_contiguity_match,\n # check_empty_tensor_size,\n # check_max_tensor_size,\n check_above_size_range,\n check_below_size_range,\n # check_contiguity_unknown_values,\n check_shape_unknown_dtypes,\n ]\n\n input_tensor = make_tensor(\n (10, 10), device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n for es in error_cases:\n yield SampleInput(input_tensor, **es.kwargs), es.ex_type, es.ex_str\n\n\ndef define_vector_constant_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n \"define_vector\",\n [](FusionDefinition& self, py::list& values) -> Vector {\n \"\"\"\n\n check_above_size_range = ErrorSample(\n {\"values\": [INT64_MAX + 1]},\n \"define_vector(): incompatible function arguments\",\n TypeError,\n )\n\n check_below_size_range = ErrorSample(\n {\"values\": [MINIMUM_SYMBOLIC_SIZE - 1]},\n \"The value -2 at index 0 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1)\",\n )\n\n error_cases = [\n # FIXME: The above_size_range case gives a non-sensical error message.\n # \"Unable to cast Python instance to C++ type (#define PYBIND11_DETAILED_ER\"\n # check_above_size_range,\n check_below_size_range,\n ]\n\n for es in error_cases:\n yield SampleInput(**es.kwargs), es.ex_type, es.ex_str\n\n\ndef _special_value_binary_generator(\n lhs_generator_fn, rhs_generator_fn, dtype, requires_grad\n):\n lhs_vals, rhs_vals = zip(*itertools.product(lhs_generator_fn, rhs_generator_fn))\n lhs = torch.tensor(\n lhs_vals, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n rhs = torch.tensor(\n rhs_vals, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n return SampleInput(lhs, rhs)\n\n\ndef elementwise_binary_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n *,\n supports_numbers: bool = True,\n enable_broadcast_testing: bool = True,\n enable_extremal_value_testing: bool = True,\n enable_large_value_testing: bool = True,\n enable_small_value_testing: bool = True,\n **kwargs,\n):\n low = None if op.domain.low is None else max(-9, op.domain.low)\n high = None if op.domain.high is None else min(9, op.domain.high)\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n low=low,\n high=high,\n requires_grad=requires_grad,\n **kwargs,\n )\n\n shapes = (\n (0, 2, 1),\n (5, 0, 3),\n (),\n (11,),\n (4, 4),\n (1024, 1024),\n (64, 64, 64),\n )\n\n # Typical inputs\n for shape in shapes:\n yield SampleInput(make_arg(shape), make_arg(shape))\n yield SampleInput(\n make_arg(shape, noncontiguous=True), make_arg(shape, noncontiguous=True)\n )\n\n if enable_broadcast_testing:\n broadcast_shapes = (\n ((1,), ()),\n ((2,), ()),\n ((1,), (2,)),\n ((2, 1), (2,)),\n ((1, 2), (2,)),\n ((3, 2), (2,)),\n ((1, 3, 2), (2,)),\n ((1, 3, 2), (3, 2)),\n ((3, 1, 2), (3, 2)),\n ((2, 3, 2), ()),\n ((3, 1, 2), (1, 3, 2)),\n )\n for lhs_shape, rhs_shape in broadcast_shapes:\n yield SampleInput(make_arg(lhs_shape), make_arg(rhs_shape))\n yield SampleInput(\n make_arg(lhs_shape, noncontiguous=True),\n make_arg(rhs_shape, noncontiguous=True),\n )\n\n # Create filtered special inputs for this operation's domain\n def _filter_lhs_domain(values):\n return [v for v in values if is_within_domain(op.domain, v)]\n\n def _filter_rhs_domain(values):\n # NOTE: Check exclude_zero flag to avoid undefined behavior such as ZeroDivisionError: division by zero\n exclude_zero = kwargs.get(\"exclude_zero\", False)\n return [v for v in values if is_within_domain(op.domain, v, exclude_zero)]\n\n if (\n enable_large_value_testing\n and dtype != torch.bool\n and dtype not in complex_dtypes\n ):\n lhs_large_values = _filter_lhs_domain(_large_values(dtype))\n rhs_large_values = _filter_rhs_domain(_large_values(dtype))\n yield _special_value_binary_generator(\n lhs_large_values, rhs_large_values, dtype, requires_grad\n )\n\n if enable_small_value_testing and dtype != torch.bool:\n lhs_small_values = _filter_lhs_domain(_small_values(dtype))\n rhs_small_values = _filter_rhs_domain(_small_values(dtype))\n yield _special_value_binary_generator(\n lhs_small_values, rhs_small_values, dtype, requires_grad\n )\n\n if enable_extremal_value_testing and dtype in float_complex_dtypes:\n lhs_extremal_values = _filter_lhs_domain(_extremal_values(dtype))\n rhs_extremal_values = _filter_rhs_domain(_extremal_values(dtype))\n yield _special_value_binary_generator(\n lhs_extremal_values, rhs_extremal_values, dtype, requires_grad\n )\n\n # Test interactions between extreme and normal values\n make_cuda_tensor = partial(\n torch.tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n rhs_normal = [random.uniform(-10, 10) for _ in range(len(lhs_extremal_values))]\n lhs_normal = [random.uniform(-10, 10) for _ in range(len(rhs_extremal_values))]\n yield SampleInput(\n make_cuda_tensor(lhs_extremal_values), make_cuda_tensor(rhs_normal)\n )\n yield SampleInput(\n make_cuda_tensor(lhs_normal), make_cuda_tensor(rhs_extremal_values)\n )\n\n\ndef _elementwise_binary_torch(op):\n @wraps(op)\n def _fn(x, y):\n if isinstance(x, torch.Tensor) or isinstance(y, torch.Tensor):\n return op(x, y)\n return op(torch.tensor(x), torch.tensor(y)).item()\n\n return _fn\n\n\ndef elementwise_unary_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n *,\n supports_numbers: bool = True,\n enable_extremal_value_testing: bool = True,\n enable_large_value_testing: bool = True,\n enable_small_value_testing: bool = True,\n **kwargs,\n):\n low = None if op.domain.low is None else max(-9, op.domain.low)\n high = None if op.domain.high is None else min(9, op.domain.high)\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n# ... truncated ...","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.is_within_domain","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.is_within_domain#L39-L53","kind":"function","name":"is_within_domain","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":39,"end_line":53,"context_start_line":19,"context_end_line":73,"code":" is_floating_dtype,\n float_complex_dtypes,\n complex_dtypes,\n)\nimport sys\n\nif \"nvfuser\" in sys.modules:\n from nvfuser import DataType\n from nvfuser.pytorch_utils import torch_dtype_to_nvfuser_dtype\nelse:\n from nvfuser_direct import DataType\n from nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\n\nMINIMUM_SYMBOLIC_SIZE = -1\nINT64_MAX = 2**63 - 1\nMAX_TENSOR_DIMS = 8\n\n\n# Determine if a number is with desired Domain [low, high)\n# The domain is half-open. The lower limit is inclusive while the upper limit is exclusive.\ndef is_within_domain(domain: Domain, a: Number, exclude_zero: bool = False):\n # comparison operators are not defined for complex numbers\n if isinstance(a, complex):\n return True\n\n if domain.low is not None and domain.low > a:\n return False\n\n if domain.high is not None and a >= domain.high:\n return False\n\n if exclude_zero and a == 0:\n return False\n\n return True\n\n\ndef _extremal_values(dtype: torch.dtype):\n _float_vals = (float(\"inf\"), float(\"-inf\"), float(\"nan\"))\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n _int16_vals = (-32768, 32767)\n _int32_vals = (-2147483648, 2147483647)\n _int64_vals = (-9223372036854775808, 9223372036854775807)\n\n if dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n return _complex_vals\n elif dtype is torch.int16:\n return _int16_vals\n elif dtype is torch.int32:\n return _int32_vals\n elif dtype is torch.int64:","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._extremal_values","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._extremal_values#L56-L76","kind":"function","name":"_extremal_values","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":56,"end_line":76,"context_start_line":36,"context_end_line":96,"code":"\n# Determine if a number is with desired Domain [low, high)\n# The domain is half-open. The lower limit is inclusive while the upper limit is exclusive.\ndef is_within_domain(domain: Domain, a: Number, exclude_zero: bool = False):\n # comparison operators are not defined for complex numbers\n if isinstance(a, complex):\n return True\n\n if domain.low is not None and domain.low > a:\n return False\n\n if domain.high is not None and a >= domain.high:\n return False\n\n if exclude_zero and a == 0:\n return False\n\n return True\n\n\ndef _extremal_values(dtype: torch.dtype):\n _float_vals = (float(\"inf\"), float(\"-inf\"), float(\"nan\"))\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n _int16_vals = (-32768, 32767)\n _int32_vals = (-2147483648, 2147483647)\n _int64_vals = (-9223372036854775808, 9223372036854775807)\n\n if dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n return _complex_vals\n elif dtype is torch.int16:\n return _int16_vals\n elif dtype is torch.int32:\n return _int32_vals\n elif dtype is torch.int64:\n return _int64_vals\n else:\n raise ValueError(f\"Unsupported dtype --- {dtype}\")\n\n\ndef _large_values(dtype: torch.dtype):\n _int_vals = (-1113, 1113, -10701, 10701)\n _float16_vals = (-501, 501, -1001.2, 1001.2, -13437.7, 13437.7)\n _float_vals = _float16_vals + (-4988429.2, 4988429.2, -1e20, 1e20)\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n\n if dtype == torch.float16:\n return _float16_vals\n elif dtype in (torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n print(_complex_vals)\n return _complex_vals\n elif dtype in (torch.int16, torch.int32, torch.int64):\n return _int_vals\n else:","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._large_values","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._large_values#L79-L97","kind":"function","name":"_large_values","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":79,"end_line":97,"context_start_line":59,"context_end_line":117,"code":" complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n _int16_vals = (-32768, 32767)\n _int32_vals = (-2147483648, 2147483647)\n _int64_vals = (-9223372036854775808, 9223372036854775807)\n\n if dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n return _complex_vals\n elif dtype is torch.int16:\n return _int16_vals\n elif dtype is torch.int32:\n return _int32_vals\n elif dtype is torch.int64:\n return _int64_vals\n else:\n raise ValueError(f\"Unsupported dtype --- {dtype}\")\n\n\ndef _large_values(dtype: torch.dtype):\n _int_vals = (-1113, 1113, -10701, 10701)\n _float16_vals = (-501, 501, -1001.2, 1001.2, -13437.7, 13437.7)\n _float_vals = _float16_vals + (-4988429.2, 4988429.2, -1e20, 1e20)\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n\n if dtype == torch.float16:\n return _float16_vals\n elif dtype in (torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n print(_complex_vals)\n return _complex_vals\n elif dtype in (torch.int16, torch.int32, torch.int64):\n return _int_vals\n else:\n raise ValueError(f\"Unsupported dtype --- {dtype}\")\n\n\ndef _small_values(dtype: torch.dtype):\n eps = 1e-5\n _int_vals = (0, -1, 1, -55, 55, -127, 127, -128)\n _float_vals = (\n 0.0,\n -0.0,\n -1e-3,\n 1e-3,\n -0.25,\n 0.25,\n -1.0,\n 1.0,\n -math.e / 2.0,\n math.e / 2.0,\n -math.e + eps,\n math.e - eps,\n -math.e,\n math.e,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._small_values","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._small_values#L100-L132","kind":"function","name":"_small_values","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":100,"end_line":132,"context_start_line":80,"context_end_line":152,"code":" _int_vals = (-1113, 1113, -10701, 10701)\n _float16_vals = (-501, 501, -1001.2, 1001.2, -13437.7, 13437.7)\n _float_vals = _float16_vals + (-4988429.2, 4988429.2, -1e20, 1e20)\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n\n if dtype == torch.float16:\n return _float16_vals\n elif dtype in (torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n print(_complex_vals)\n return _complex_vals\n elif dtype in (torch.int16, torch.int32, torch.int64):\n return _int_vals\n else:\n raise ValueError(f\"Unsupported dtype --- {dtype}\")\n\n\ndef _small_values(dtype: torch.dtype):\n eps = 1e-5\n _int_vals = (0, -1, 1, -55, 55, -127, 127, -128)\n _float_vals = (\n 0.0,\n -0.0,\n -1e-3,\n 1e-3,\n -0.25,\n 0.25,\n -1.0,\n 1.0,\n -math.e / 2.0,\n math.e / 2.0,\n -math.e + eps,\n math.e - eps,\n -math.e,\n math.e,\n -math.e - eps,\n math.e + eps,\n )\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n\n if dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n return _complex_vals\n elif dtype in (torch.int16, torch.int32, torch.int64):\n return _int_vals\n else:\n raise ValueError(f\"Unsupported dtype --- {dtype}\")\n\n\ndef broadcast_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # jax.lax.broadcast(operand, sizes)\n # add new dimensions to left-hand-side of tensor\n # dims = tuple(range(len(sizes), len(sizes) + np.ndim(operand)))\n # return broadcast_in_dim(operand, tuple(sizes) + np.shape(operand), dims)\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n fewer_original_axes = (\n ([2, 3], [True, False]),\n RuntimeError,\n \"Invalid broadcast, number of false entries in is_broadcast_dim expected to be\",\n )\n","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.broadcast_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.broadcast_error_generator#L135-L167","kind":"function","name":"broadcast_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":135,"end_line":167,"context_start_line":115,"context_end_line":187,"code":" math.e - eps,\n -math.e,\n math.e,\n -math.e - eps,\n math.e + eps,\n )\n _complex_vals = tuple(\n complex(*x) for x in itertools.product(_float_vals, _float_vals)\n )\n\n if dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):\n return _float_vals\n elif dtype in (torch.complex64, torch.complex128):\n return _complex_vals\n elif dtype in (torch.int16, torch.int32, torch.int64):\n return _int_vals\n else:\n raise ValueError(f\"Unsupported dtype --- {dtype}\")\n\n\ndef broadcast_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # jax.lax.broadcast(operand, sizes)\n # add new dimensions to left-hand-side of tensor\n # dims = tuple(range(len(sizes), len(sizes) + np.ndim(operand)))\n # return broadcast_in_dim(operand, tuple(sizes) + np.shape(operand), dims)\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n fewer_original_axes = (\n ([2, 3], [True, False]),\n RuntimeError,\n \"Invalid broadcast, number of false entries in is_broadcast_dim expected to be\",\n )\n\n greater_original_axes = (\n ([2, 3], [True, False, False, False]),\n RuntimeError,\n \"Invalid broadcast, number of false entries in is_broadcast_dim expected to be\",\n )\n\n error_cases = [\n fewer_original_axes,\n greater_original_axes,\n ]\n for es in error_cases:\n ex_case, ex_type, ex_str = es\n input_shape, bcast_dims = ex_case\n input_tensor = make_arg(input_shape)\n yield SampleInput(input_tensor, bcast_dims), ex_type, ex_str\n\n\ndef broadcast_in_dim_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # The first 5 test cases below are taken from JAX's broadcast_in_dim tests\n # https://github.com/google/jax/blob/main/tests/lax_test.py#L1171\n # input shape, output shape, bcast_dims\n cases = (\n ([2], [2, 2], [0]),\n ([2], [2, 2], [1]),\n ([2], [2, 3], [0]),\n ([], [2, 3], []),\n ([1], [2, 3], [1]),\n ((4, 6, 3, 1), (5, 4, 7, 6, 3, 6, 6), (1, 3, 4, 5)),\n )","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.broadcast_in_dim_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.broadcast_in_dim_generator#L170-L195","kind":"function","name":"broadcast_in_dim_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":170,"end_line":195,"context_start_line":150,"context_end_line":215,"code":" \"Invalid broadcast, number of false entries in is_broadcast_dim expected to be\",\n )\n\n greater_original_axes = (\n ([2, 3], [True, False, False, False]),\n RuntimeError,\n \"Invalid broadcast, number of false entries in is_broadcast_dim expected to be\",\n )\n\n error_cases = [\n fewer_original_axes,\n greater_original_axes,\n ]\n for es in error_cases:\n ex_case, ex_type, ex_str = es\n input_shape, bcast_dims = ex_case\n input_tensor = make_arg(input_shape)\n yield SampleInput(input_tensor, bcast_dims), ex_type, ex_str\n\n\ndef broadcast_in_dim_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # The first 5 test cases below are taken from JAX's broadcast_in_dim tests\n # https://github.com/google/jax/blob/main/tests/lax_test.py#L1171\n # input shape, output shape, bcast_dims\n cases = (\n ([2], [2, 2], [0]),\n ([2], [2, 2], [1]),\n ([2], [2, 3], [0]),\n ([], [2, 3], []),\n ([1], [2, 3], [1]),\n ((4, 6, 3, 1), (5, 4, 7, 6, 3, 6, 6), (1, 3, 4, 5)),\n )\n\n for input_shape, output_shape, bcast_dims in cases:\n input_tensor = make_arg(input_shape)\n if op.name == \"broadcast_in_dim_symbolic\":\n bcast_shaped_tensor = make_arg(output_shape)\n yield SampleInput(input_tensor, bcast_shaped_tensor, bcast_dims)\n else:\n yield SampleInput(input_tensor, output_shape, bcast_dims)\n\n\ndef broadcast_in_dim_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # jax.lax.broadcast_in_dim(operand, shape, broadcast_dimensions)\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # 1. Every dimension in the input tensor must be used in broadcast_dimensions.\n missing_axis_in_bcast_dims = (\n ([2, 2], [2, 2, 3], [0]),\n RuntimeError,\n \"The broadcast dimensions should match the input dimensions.\",\n )\n\n # 2. New shape has weakly more dimentions than the original tensor.\n fewer_dims_in_output_shape = (\n ([2, 2], [2], [0]),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.broadcast_in_dim_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.broadcast_in_dim_error_generator#L198-L265","kind":"function","name":"broadcast_in_dim_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":198,"end_line":265,"context_start_line":178,"context_end_line":285,"code":" # https://github.com/google/jax/blob/main/tests/lax_test.py#L1171\n # input shape, output shape, bcast_dims\n cases = (\n ([2], [2, 2], [0]),\n ([2], [2, 2], [1]),\n ([2], [2, 3], [0]),\n ([], [2, 3], []),\n ([1], [2, 3], [1]),\n ((4, 6, 3, 1), (5, 4, 7, 6, 3, 6, 6), (1, 3, 4, 5)),\n )\n\n for input_shape, output_shape, bcast_dims in cases:\n input_tensor = make_arg(input_shape)\n if op.name == \"broadcast_in_dim_symbolic\":\n bcast_shaped_tensor = make_arg(output_shape)\n yield SampleInput(input_tensor, bcast_shaped_tensor, bcast_dims)\n else:\n yield SampleInput(input_tensor, output_shape, bcast_dims)\n\n\ndef broadcast_in_dim_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # jax.lax.broadcast_in_dim(operand, shape, broadcast_dimensions)\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # 1. Every dimension in the input tensor must be used in broadcast_dimensions.\n missing_axis_in_bcast_dims = (\n ([2, 2], [2, 2, 3], [0]),\n RuntimeError,\n \"The broadcast dimensions should match the input dimensions.\",\n )\n\n # 2. New shape has weakly more dimentions than the original tensor.\n fewer_dims_in_output_shape = (\n ([2, 2], [2], [0]),\n RuntimeError,\n \"The new shape is expected to be greater-then-or-equal to the input\",\n )\n\n # 3. Each broadcast dimension is within the new shape.\n out_of_bounds_broadcast_dimensions = (\n ([2, 2], [2, 2], [0, 2]),\n RuntimeError,\n \"Invalid broadcast_dims value.\",\n )\n\n # 4. The original tensor is not broadcastable to desired shape.\n # tensor.shape[idx] == 1 or tensor.shape[idx] == output_shape[new_idx]\n #\n # Jax Exception:\n # TypeError: broadcast_in_dim operand dimension sizes must either be 1,\n # or be equal to their corresponding dimensions in the target broadcast shape;\n # got operand of shape (2, 3), target broadcast shape (2, 3, 4), broadcast_dimensions (0, 2)\n not_broadcastable = (\n ([2, 3], [2, 3, 4], [0, 2]),\n RuntimeError,\n \"Invalid broadcast_dims value.\",\n )\n\n # 5. TypeError: broadcast_in_dim shape must have every element be nonnegative, got (-1, 2, 3).\n negative_shape = (\n ([2, 3], [2, 3, -1], [0, 1]),\n RuntimeError,\n \"Invalid broadcast_dims value.\",\n )\n\n # TODO add exceptions for not_broadcastable, negative output shape\n error_cases = [\n missing_axis_in_bcast_dims,\n fewer_dims_in_output_shape,\n out_of_bounds_broadcast_dimensions,\n # not_broadcastable,\n # negative_shape,\n ]\n for es in error_cases:\n ex_case, ex_type, ex_str = es\n input_shape, output_shape, bcast_dims = ex_case\n input_tensor = make_arg(input_shape)\n if op.name == \"broadcast_in_dim_symbolic\":\n bcast_shaped_tensor = make_arg(output_shape)\n yield SampleInput(\n input_tensor, bcast_shaped_tensor, bcast_dims\n ), ex_type, ex_str\n else:\n yield SampleInput(input_tensor, output_shape, bcast_dims), ex_type, ex_str\n\n\ndef cat_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # concatenating tensors along singleton, broadcast dimensions is unsupported by nvFuser.\n # https://github.com/NVIDIA/Fuser/issues/224\n # shapes, dim\n cases = [\n ([(3,)], 0), # single tensor provided\n # 1D\n ([(2,), (3,)], 0),\n ([(2,), (4,)], 0),\n ([(0,), (2,)], 0),\n ([(0,), (2,)], -1),\n ([(2, 3), (2, 4)], 1),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.cat_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.cat_generator#L268-L290","kind":"function","name":"cat_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":268,"end_line":290,"context_start_line":248,"context_end_line":310,"code":" error_cases = [\n missing_axis_in_bcast_dims,\n fewer_dims_in_output_shape,\n out_of_bounds_broadcast_dimensions,\n # not_broadcastable,\n # negative_shape,\n ]\n for es in error_cases:\n ex_case, ex_type, ex_str = es\n input_shape, output_shape, bcast_dims = ex_case\n input_tensor = make_arg(input_shape)\n if op.name == \"broadcast_in_dim_symbolic\":\n bcast_shaped_tensor = make_arg(output_shape)\n yield SampleInput(\n input_tensor, bcast_shaped_tensor, bcast_dims\n ), ex_type, ex_str\n else:\n yield SampleInput(input_tensor, output_shape, bcast_dims), ex_type, ex_str\n\n\ndef cat_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # concatenating tensors along singleton, broadcast dimensions is unsupported by nvFuser.\n # https://github.com/NVIDIA/Fuser/issues/224\n # shapes, dim\n cases = [\n ([(3,)], 0), # single tensor provided\n # 1D\n ([(2,), (3,)], 0),\n ([(2,), (4,)], 0),\n ([(0,), (2,)], 0),\n ([(0,), (2,)], -1),\n ([(2, 3), (2, 4)], 1),\n ([(2, 3), (2, 4), (2, 5)], 1),\n ]\n\n for shapes, dim in cases:\n yield SampleInput([make_arg(s) for s in shapes], dim)\n\n\ndef cat_error_generator(op, dtype=torch.float32, requires_grad: bool = False, **kwargs):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n # shapes, dim, exception type, exception string\n empty_input_tensors = (\n ([], 0),\n RuntimeError,\n \"Attempting to concatenate empty list of tensors\",\n )\n positive_dim = (([(1,), (2,)], 1), RuntimeError, \"Invalid dimension to cat\")\n negative_dim = (([(2,), (2,)], -2), RuntimeError, \"Invalid dimension to cat\")\n # All tensors must have same number of dimension\"\n ndims_mismatch = (\n ([(2,), (2, 3)], 0),\n RuntimeError,\n \"Unexpected number of dimensions\",\n )","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.cat_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.cat_error_generator#L293-L328","kind":"function","name":"cat_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":293,"end_line":328,"context_start_line":273,"context_end_line":348,"code":" )\n\n # concatenating tensors along singleton, broadcast dimensions is unsupported by nvFuser.\n # https://github.com/NVIDIA/Fuser/issues/224\n # shapes, dim\n cases = [\n ([(3,)], 0), # single tensor provided\n # 1D\n ([(2,), (3,)], 0),\n ([(2,), (4,)], 0),\n ([(0,), (2,)], 0),\n ([(0,), (2,)], -1),\n ([(2, 3), (2, 4)], 1),\n ([(2, 3), (2, 4), (2, 5)], 1),\n ]\n\n for shapes, dim in cases:\n yield SampleInput([make_arg(s) for s in shapes], dim)\n\n\ndef cat_error_generator(op, dtype=torch.float32, requires_grad: bool = False, **kwargs):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n # shapes, dim, exception type, exception string\n empty_input_tensors = (\n ([], 0),\n RuntimeError,\n \"Attempting to concatenate empty list of tensors\",\n )\n positive_dim = (([(1,), (2,)], 1), RuntimeError, \"Invalid dimension to cat\")\n negative_dim = (([(2,), (2,)], -2), RuntimeError, \"Invalid dimension to cat\")\n # All tensors must have same number of dimension\"\n ndims_mismatch = (\n ([(2,), (2, 3)], 0),\n RuntimeError,\n \"Unexpected number of dimensions\",\n )\n # All tensors must have same shape except for the cat dimension\n shape_mismatch = (\n ([(2, 3), (4, 5)], 0),\n RuntimeError,\n \"a conflict was found with 2 different sizes\",\n )\n\n error_cases = [\n empty_input_tensors,\n positive_dim,\n negative_dim,\n ndims_mismatch,\n shape_mismatch,\n ]\n\n for case, ex_type, ex_str in error_cases:\n shapes, dim = case\n yield SampleInput([make_arg(s) for s in shapes], dim), ex_type, ex_str\n\n\ndef define_tensor_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n \"define_tensor\",\n [](FusionDefinition& self,\n std::vector& sizes,\n std::vector& strides,\n PrimDataType dtype = DataType::Float,\n bool static_sizes = false,\n bool is_cpu = false) -> Tensor {\n ---\n \"define_tensor\",\n [](FusionDefinition& self,\n std::vector& shape,\n std::vector>& contiguity,\n PrimDataType dtype = DataType::Float,\n bool is_cpu = false) -> Tensor {","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.define_tensor_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.define_tensor_error_generator#L331-L442","kind":"function","name":"define_tensor_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":331,"end_line":442,"context_start_line":311,"context_end_line":462,"code":" # All tensors must have same shape except for the cat dimension\n shape_mismatch = (\n ([(2, 3), (4, 5)], 0),\n RuntimeError,\n \"a conflict was found with 2 different sizes\",\n )\n\n error_cases = [\n empty_input_tensors,\n positive_dim,\n negative_dim,\n ndims_mismatch,\n shape_mismatch,\n ]\n\n for case, ex_type, ex_str in error_cases:\n shapes, dim = case\n yield SampleInput([make_arg(s) for s in shapes], dim), ex_type, ex_str\n\n\ndef define_tensor_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n \"define_tensor\",\n [](FusionDefinition& self,\n std::vector& sizes,\n std::vector& strides,\n PrimDataType dtype = DataType::Float,\n bool static_sizes = false,\n bool is_cpu = false) -> Tensor {\n ---\n \"define_tensor\",\n [](FusionDefinition& self,\n std::vector& shape,\n std::vector>& contiguity,\n PrimDataType dtype = DataType::Float,\n bool is_cpu = false) -> Tensor {\n \"\"\"\n\n check_size_contiguity_match = ErrorSample(\n {\n \"shape\": [-1, -1],\n \"contiguity\": [True, True, True],\n \"dtype\": DataType.Float,\n },\n \"Length of contiguity argument (3) must match that of shape argument (2)\",\n )\n\n check_empty_tensor_size = ErrorSample(\n {\"shape\": [], \"contiguity\": []},\n \"Empty tensor is unsupported.\",\n )\n\n check_max_tensor_size = ErrorSample(\n {\n \"shape\": [-1 for _ in range(MAX_TENSOR_DIMS + 1)],\n \"contiguity\": [True for _ in range(MAX_TENSOR_DIMS + 1)],\n },\n \"The specified tensor dimensionality exceeds the max tensor size for nvfuser.\",\n )\n\n check_above_size_range = ErrorSample(\n {\"shape\": [INT64_MAX + 1], \"contiguity\": [True]},\n \"define_tensor(): incompatible function arguments\",\n TypeError,\n )\n\n check_below_size_range = ErrorSample(\n {\"shape\": [MINIMUM_SYMBOLIC_SIZE - 1], \"contiguity\": [True]},\n \"The value -2 at index 0 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1)\",\n )\n\n check_contiguity_unknown_values = ErrorSample(\n {\"shape\": [10], \"contiguity\": [-1]},\n \"define_tensor(): incompatible function arguments.\",\n TypeError,\n )\n\n check_shape_unknown_dtypes = ErrorSample(\n {\"shape\": [10.0], \"contiguity\": [True]},\n \"define_tensor(): incompatible function arguments.\",\n TypeError,\n )\n\n check_stride_order_duplicate = ErrorSample(\n {\n \"shape\": [-1, -1, -1],\n \"contiguity\": [True, True, True],\n \"stride_order\": [0, 1, 1],\n },\n \"duplicated stride_order entries\",\n RuntimeError,\n )\n\n check_stride_order_out_of_range = ErrorSample(\n {\n \"shape\": [-1, -1, -1],\n \"contiguity\": [True, True, True],\n \"stride_order\": [0, 1, 5],\n },\n \"stride_order argument is out of range\",\n RuntimeError,\n )\n\n check_stride_order_out_of_negative_range = ErrorSample(\n {\n \"shape\": [-1, -1, -1],\n \"contiguity\": [True, True, True],\n \"stride_order\": [0, 1, -4],\n },\n \"stride_order argument is out of range\",\n RuntimeError,\n )\n\n # TODO: Fix empty and maximum tensor dimensionality error checks.\n # TODO: Add invalid argument checks for contiguity.\n error_cases = [\n check_size_contiguity_match,\n # check_empty_tensor_size,\n # check_max_tensor_size,\n check_above_size_range,\n check_below_size_range,\n # check_contiguity_unknown_values,\n check_shape_unknown_dtypes,\n ]\n\n input_tensor = make_tensor(\n (10, 10), device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n for es in error_cases:\n yield SampleInput(input_tensor, **es.kwargs), es.ex_type, es.ex_str\n\n\ndef define_vector_constant_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n \"define_vector\",\n [](FusionDefinition& self, py::list& values) -> Vector {\n \"\"\"\n\n check_above_size_range = ErrorSample(\n {\"values\": [INT64_MAX + 1]},\n \"define_vector(): incompatible function arguments\",\n TypeError,\n )\n\n check_below_size_range = ErrorSample(\n {\"values\": [MINIMUM_SYMBOLIC_SIZE - 1]},\n \"The value -2 at index 0 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1)\",\n )","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.define_vector_constant_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.define_vector_constant_error_generator#L445-L472","kind":"function","name":"define_vector_constant_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":445,"end_line":472,"context_start_line":425,"context_end_line":492,"code":"\n # TODO: Fix empty and maximum tensor dimensionality error checks.\n # TODO: Add invalid argument checks for contiguity.\n error_cases = [\n check_size_contiguity_match,\n # check_empty_tensor_size,\n # check_max_tensor_size,\n check_above_size_range,\n check_below_size_range,\n # check_contiguity_unknown_values,\n check_shape_unknown_dtypes,\n ]\n\n input_tensor = make_tensor(\n (10, 10), device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n for es in error_cases:\n yield SampleInput(input_tensor, **es.kwargs), es.ex_type, es.ex_str\n\n\ndef define_vector_constant_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n \"define_vector\",\n [](FusionDefinition& self, py::list& values) -> Vector {\n \"\"\"\n\n check_above_size_range = ErrorSample(\n {\"values\": [INT64_MAX + 1]},\n \"define_vector(): incompatible function arguments\",\n TypeError,\n )\n\n check_below_size_range = ErrorSample(\n {\"values\": [MINIMUM_SYMBOLIC_SIZE - 1]},\n \"The value -2 at index 0 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1)\",\n )\n\n error_cases = [\n # FIXME: The above_size_range case gives a non-sensical error message.\n # \"Unable to cast Python instance to C++ type (#define PYBIND11_DETAILED_ER\"\n # check_above_size_range,\n check_below_size_range,\n ]\n\n for es in error_cases:\n yield SampleInput(**es.kwargs), es.ex_type, es.ex_str\n\n\ndef _special_value_binary_generator(\n lhs_generator_fn, rhs_generator_fn, dtype, requires_grad\n):\n lhs_vals, rhs_vals = zip(*itertools.product(lhs_generator_fn, rhs_generator_fn))\n lhs = torch.tensor(\n lhs_vals, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n rhs = torch.tensor(\n rhs_vals, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n return SampleInput(lhs, rhs)\n\n\ndef elementwise_binary_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n *,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._special_value_binary_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._special_value_binary_generator#L475-L485","kind":"function","name":"_special_value_binary_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":475,"end_line":485,"context_start_line":455,"context_end_line":505,"code":" \"define_vector(): incompatible function arguments\",\n TypeError,\n )\n\n check_below_size_range = ErrorSample(\n {\"values\": [MINIMUM_SYMBOLIC_SIZE - 1]},\n \"The value -2 at index 0 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1)\",\n )\n\n error_cases = [\n # FIXME: The above_size_range case gives a non-sensical error message.\n # \"Unable to cast Python instance to C++ type (#define PYBIND11_DETAILED_ER\"\n # check_above_size_range,\n check_below_size_range,\n ]\n\n for es in error_cases:\n yield SampleInput(**es.kwargs), es.ex_type, es.ex_str\n\n\ndef _special_value_binary_generator(\n lhs_generator_fn, rhs_generator_fn, dtype, requires_grad\n):\n lhs_vals, rhs_vals = zip(*itertools.product(lhs_generator_fn, rhs_generator_fn))\n lhs = torch.tensor(\n lhs_vals, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n rhs = torch.tensor(\n rhs_vals, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n return SampleInput(lhs, rhs)\n\n\ndef elementwise_binary_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n *,\n supports_numbers: bool = True,\n enable_broadcast_testing: bool = True,\n enable_extremal_value_testing: bool = True,\n enable_large_value_testing: bool = True,\n enable_small_value_testing: bool = True,\n **kwargs,\n):\n low = None if op.domain.low is None else max(-9, op.domain.low)\n high = None if op.domain.high is None else min(9, op.domain.high)\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.elementwise_binary_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.elementwise_binary_generator#L488-L595","kind":"function","name":"elementwise_binary_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":488,"end_line":595,"context_start_line":468,"context_end_line":615,"code":" check_below_size_range,\n ]\n\n for es in error_cases:\n yield SampleInput(**es.kwargs), es.ex_type, es.ex_str\n\n\ndef _special_value_binary_generator(\n lhs_generator_fn, rhs_generator_fn, dtype, requires_grad\n):\n lhs_vals, rhs_vals = zip(*itertools.product(lhs_generator_fn, rhs_generator_fn))\n lhs = torch.tensor(\n lhs_vals, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n rhs = torch.tensor(\n rhs_vals, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n return SampleInput(lhs, rhs)\n\n\ndef elementwise_binary_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n *,\n supports_numbers: bool = True,\n enable_broadcast_testing: bool = True,\n enable_extremal_value_testing: bool = True,\n enable_large_value_testing: bool = True,\n enable_small_value_testing: bool = True,\n **kwargs,\n):\n low = None if op.domain.low is None else max(-9, op.domain.low)\n high = None if op.domain.high is None else min(9, op.domain.high)\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n low=low,\n high=high,\n requires_grad=requires_grad,\n **kwargs,\n )\n\n shapes = (\n (0, 2, 1),\n (5, 0, 3),\n (),\n (11,),\n (4, 4),\n (1024, 1024),\n (64, 64, 64),\n )\n\n # Typical inputs\n for shape in shapes:\n yield SampleInput(make_arg(shape), make_arg(shape))\n yield SampleInput(\n make_arg(shape, noncontiguous=True), make_arg(shape, noncontiguous=True)\n )\n\n if enable_broadcast_testing:\n broadcast_shapes = (\n ((1,), ()),\n ((2,), ()),\n ((1,), (2,)),\n ((2, 1), (2,)),\n ((1, 2), (2,)),\n ((3, 2), (2,)),\n ((1, 3, 2), (2,)),\n ((1, 3, 2), (3, 2)),\n ((3, 1, 2), (3, 2)),\n ((2, 3, 2), ()),\n ((3, 1, 2), (1, 3, 2)),\n )\n for lhs_shape, rhs_shape in broadcast_shapes:\n yield SampleInput(make_arg(lhs_shape), make_arg(rhs_shape))\n yield SampleInput(\n make_arg(lhs_shape, noncontiguous=True),\n make_arg(rhs_shape, noncontiguous=True),\n )\n\n # Create filtered special inputs for this operation's domain\n def _filter_lhs_domain(values):\n return [v for v in values if is_within_domain(op.domain, v)]\n\n def _filter_rhs_domain(values):\n # NOTE: Check exclude_zero flag to avoid undefined behavior such as ZeroDivisionError: division by zero\n exclude_zero = kwargs.get(\"exclude_zero\", False)\n return [v for v in values if is_within_domain(op.domain, v, exclude_zero)]\n\n if (\n enable_large_value_testing\n and dtype != torch.bool\n and dtype not in complex_dtypes\n ):\n lhs_large_values = _filter_lhs_domain(_large_values(dtype))\n rhs_large_values = _filter_rhs_domain(_large_values(dtype))\n yield _special_value_binary_generator(\n lhs_large_values, rhs_large_values, dtype, requires_grad\n )\n\n if enable_small_value_testing and dtype != torch.bool:\n lhs_small_values = _filter_lhs_domain(_small_values(dtype))\n rhs_small_values = _filter_rhs_domain(_small_values(dtype))\n yield _special_value_binary_generator(\n lhs_small_values, rhs_small_values, dtype, requires_grad\n )\n\n if enable_extremal_value_testing and dtype in float_complex_dtypes:\n lhs_extremal_values = _filter_lhs_domain(_extremal_values(dtype))\n rhs_extremal_values = _filter_rhs_domain(_extremal_values(dtype))\n yield _special_value_binary_generator(\n lhs_extremal_values, rhs_extremal_values, dtype, requires_grad\n )\n\n # Test interactions between extreme and normal values\n make_cuda_tensor = partial(\n torch.tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n rhs_normal = [random.uniform(-10, 10) for _ in range(len(lhs_extremal_values))]\n lhs_normal = [random.uniform(-10, 10) for _ in range(len(rhs_extremal_values))]\n yield SampleInput(\n make_cuda_tensor(lhs_extremal_values), make_cuda_tensor(rhs_normal)\n )\n yield SampleInput(\n make_cuda_tensor(lhs_normal), make_cuda_tensor(rhs_extremal_values)\n )\n\n\ndef _elementwise_binary_torch(op):\n @wraps(op)\n def _fn(x, y):\n if isinstance(x, torch.Tensor) or isinstance(y, torch.Tensor):\n return op(x, y)\n return op(torch.tensor(x), torch.tensor(y)).item()\n\n return _fn\n\n\ndef elementwise_unary_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n *,\n supports_numbers: bool = True,\n enable_extremal_value_testing: bool = True,\n enable_large_value_testing: bool = True,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._elementwise_binary_torch","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._elementwise_binary_torch#L598-L605","kind":"function","name":"_elementwise_binary_torch","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":598,"end_line":605,"context_start_line":578,"context_end_line":625,"code":" lhs_extremal_values = _filter_lhs_domain(_extremal_values(dtype))\n rhs_extremal_values = _filter_rhs_domain(_extremal_values(dtype))\n yield _special_value_binary_generator(\n lhs_extremal_values, rhs_extremal_values, dtype, requires_grad\n )\n\n # Test interactions between extreme and normal values\n make_cuda_tensor = partial(\n torch.tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n rhs_normal = [random.uniform(-10, 10) for _ in range(len(lhs_extremal_values))]\n lhs_normal = [random.uniform(-10, 10) for _ in range(len(rhs_extremal_values))]\n yield SampleInput(\n make_cuda_tensor(lhs_extremal_values), make_cuda_tensor(rhs_normal)\n )\n yield SampleInput(\n make_cuda_tensor(lhs_normal), make_cuda_tensor(rhs_extremal_values)\n )\n\n\ndef _elementwise_binary_torch(op):\n @wraps(op)\n def _fn(x, y):\n if isinstance(x, torch.Tensor) or isinstance(y, torch.Tensor):\n return op(x, y)\n return op(torch.tensor(x), torch.tensor(y)).item()\n\n return _fn\n\n\ndef elementwise_unary_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n *,\n supports_numbers: bool = True,\n enable_extremal_value_testing: bool = True,\n enable_large_value_testing: bool = True,\n enable_small_value_testing: bool = True,\n **kwargs,\n):\n low = None if op.domain.low is None else max(-9, op.domain.low)\n high = None if op.domain.high is None else min(9, op.domain.high)\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n low=low,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.elementwise_unary_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.elementwise_unary_generator#L608-L685","kind":"function","name":"elementwise_unary_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":608,"end_line":685,"context_start_line":588,"context_end_line":705,"code":" rhs_normal = [random.uniform(-10, 10) for _ in range(len(lhs_extremal_values))]\n lhs_normal = [random.uniform(-10, 10) for _ in range(len(rhs_extremal_values))]\n yield SampleInput(\n make_cuda_tensor(lhs_extremal_values), make_cuda_tensor(rhs_normal)\n )\n yield SampleInput(\n make_cuda_tensor(lhs_normal), make_cuda_tensor(rhs_extremal_values)\n )\n\n\ndef _elementwise_binary_torch(op):\n @wraps(op)\n def _fn(x, y):\n if isinstance(x, torch.Tensor) or isinstance(y, torch.Tensor):\n return op(x, y)\n return op(torch.tensor(x), torch.tensor(y)).item()\n\n return _fn\n\n\ndef elementwise_unary_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n *,\n supports_numbers: bool = True,\n enable_extremal_value_testing: bool = True,\n enable_large_value_testing: bool = True,\n enable_small_value_testing: bool = True,\n **kwargs,\n):\n low = None if op.domain.low is None else max(-9, op.domain.low)\n high = None if op.domain.high is None else min(9, op.domain.high)\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n low=low,\n high=high,\n requires_grad=requires_grad,\n **kwargs,\n )\n\n shapes = (\n (0, 2, 1),\n (5, 0, 3),\n (),\n (11,),\n (4, 4),\n (1024, 1024),\n (64, 64, 64),\n )\n\n # Typical inputs\n for shape in shapes:\n yield SampleInput(make_arg(shape))\n yield SampleInput(make_arg(shape, noncontiguous=True))\n\n # Create filtered special inputs for this operation's domain\n def _filter_domain(values):\n return [v for v in values if is_within_domain(op.domain, v)]\n\n if (\n enable_large_value_testing\n and dtype != torch.bool\n and dtype not in complex_dtypes\n ):\n filtered_large_values = _filter_domain(_large_values(dtype))\n yield SampleInput(\n torch.tensor(\n filtered_large_values,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n )\n )\n\n if enable_small_value_testing and dtype != torch.bool:\n filtered_small_values = _filter_domain(_small_values(dtype))\n yield SampleInput(\n torch.tensor(\n filtered_small_values,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n )\n )\n\n if enable_extremal_value_testing and dtype in float_complex_dtypes:\n filtered_extremal_values = _filter_domain(_extremal_values(dtype))\n yield SampleInput(\n torch.tensor(\n filtered_extremal_values,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n )\n )\n\n\ndef _elementwise_unary_torch(op):\n @wraps(op)\n def _fn(x):\n if isinstance(x, torch.Tensor):\n return op(x)\n return op(torch.tensor(x)).item()\n\n return _fn\n\n\ndef full_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.full(size, fill_value, dtype=None)\n # Error: Trying to create tensor with negative dimension\n negative_input_shape = [2, -2]\n yield SampleInput(\n negative_input_shape, make_number(dtype), dtype","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._elementwise_unary_torch","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._elementwise_unary_torch#L688-L695","kind":"function","name":"_elementwise_unary_torch","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":688,"end_line":695,"context_start_line":668,"context_end_line":715,"code":" torch.tensor(\n filtered_small_values,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n )\n )\n\n if enable_extremal_value_testing and dtype in float_complex_dtypes:\n filtered_extremal_values = _filter_domain(_extremal_values(dtype))\n yield SampleInput(\n torch.tensor(\n filtered_extremal_values,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n )\n )\n\n\ndef _elementwise_unary_torch(op):\n @wraps(op)\n def _fn(x):\n if isinstance(x, torch.Tensor):\n return op(x)\n return op(torch.tensor(x)).item()\n\n return _fn\n\n\ndef full_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.full(size, fill_value, dtype=None)\n # Error: Trying to create tensor with negative dimension\n negative_input_shape = [2, -2]\n yield SampleInput(\n negative_input_shape, make_number(dtype), dtype\n ), RuntimeError, \"The value -2 at index 1 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1).\"\n\n\ndef scatter_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.scatter(input: Tensor, dim: int, index: LongTensor, src: LongTensor)\n # * input, index and src tensors have same ndims.\n # * index tensors must be <= input tensor along all dims.\n # * index tensors must be == src tensor along all dims.","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.full_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.full_error_generator#L698-L706","kind":"function","name":"full_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":698,"end_line":706,"context_start_line":678,"context_end_line":726,"code":" yield SampleInput(\n torch.tensor(\n filtered_extremal_values,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n )\n )\n\n\ndef _elementwise_unary_torch(op):\n @wraps(op)\n def _fn(x):\n if isinstance(x, torch.Tensor):\n return op(x)\n return op(torch.tensor(x)).item()\n\n return _fn\n\n\ndef full_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.full(size, fill_value, dtype=None)\n # Error: Trying to create tensor with negative dimension\n negative_input_shape = [2, -2]\n yield SampleInput(\n negative_input_shape, make_number(dtype), dtype\n ), RuntimeError, \"The value -2 at index 1 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1).\"\n\n\ndef scatter_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.scatter(input: Tensor, dim: int, index: LongTensor, src: LongTensor)\n # * input, index and src tensors have same ndims.\n # * index tensors must be <= input tensor along all dims.\n # * index tensors must be == src tensor along all dims.\n # * index tensors must have unique value across specified axis.\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n def make_unique_index(shape_b, dim, extent):\n logits_shape = list(shape_b)\n logits_shape[dim] = extent\n logits = make_tensor(logits_shape, device=\"cuda\", dtype=torch.float)\n # return index tensor with unique entry","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.scatter_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.scatter_generator#L709-L771","kind":"function","name":"scatter_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":709,"end_line":771,"context_start_line":689,"context_end_line":791,"code":" @wraps(op)\n def _fn(x):\n if isinstance(x, torch.Tensor):\n return op(x)\n return op(torch.tensor(x)).item()\n\n return _fn\n\n\ndef full_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.full(size, fill_value, dtype=None)\n # Error: Trying to create tensor with negative dimension\n negative_input_shape = [2, -2]\n yield SampleInput(\n negative_input_shape, make_number(dtype), dtype\n ), RuntimeError, \"The value -2 at index 1 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1).\"\n\n\ndef scatter_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.scatter(input: Tensor, dim: int, index: LongTensor, src: LongTensor)\n # * input, index and src tensors have same ndims.\n # * index tensors must be <= input tensor along all dims.\n # * index tensors must be == src tensor along all dims.\n # * index tensors must have unique value across specified axis.\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n def make_unique_index(shape_b, dim, extent):\n logits_shape = list(shape_b)\n logits_shape[dim] = extent\n logits = make_tensor(logits_shape, device=\"cuda\", dtype=torch.float)\n # return index tensor with unique entry\n return logits.argsort(dim).narrow(dim, 0, shape_b[dim])\n\n make_index = partial(\n make_tensor, device=\"cuda\", dtype=torch.long, requires_grad=False\n )\n\n # a.shape, dim, b.shape\n cases = (\n ((8, 2, 3), 0, (8, 2, 3)),\n ((8, 2, 3), 1, (8, 2, 3)),\n ((8, 2, 3), 2, (8, 2, 3)),\n # TODO: enable the test below when we fix mapping for scatter.\n # scatter supporting unmatched scatter dim\n # ((8, 2, 3), 0, (4, 2, 3)),\n # ((8, 2, 3), 1, (8, 1, 3)),\n # ((8, 2, 3), 2, (8, 2, 2)),\n # ((8,), 0, (8)),\n # ((8,), 0, (4)),\n # ((8,), 0, (1)),\n # ((8, 2, 3), -3, (4, 2, 3)),\n # ((8, 2, 3), -2, (8, 1, 3)),\n # ((8, 2, 3), -1, (8, 2, 2)),\n # TODO: should we support mismatching dims?\n # scatter supporting unmatched all dims\n # ((8, 2, 3), 0, (4, 2, 3)),\n # ((4, 2, 3), 1, (4, 2, 3)),\n # ((4, 2, 3), 2, (4, 2, 2)),\n # ((8,), 0, (8)),\n # ((8,), 0, (4)),\n # ((8,), 0, (1)),\n # ((4, 1), 0, (1, 1)),\n # ((4, 5), 1, (4, 1)),\n # ((8, 2, 3), 0, (4, 1, 2)),\n # ((8, 2, 3), 1, (4, 1, 2)),\n # ((8, 2, 3), 2, (4, 1, 2)),\n # ((8, 2, 3), -3, (4, 2, 3)),\n # ((4, 2, 3), -2, (4, 2, 3)),\n # ((4, 2, 3), -1, (4, 2, 2)),\n )\n\n for shape_a, dim, shape_b in cases:\n a = make_arg(shape_a)\n b = make_unique_index(shape_b, dim, shape_a[dim])\n c = make_arg(shape_b)\n yield SampleInput(a, b, c, dim)\n\n\ndef gather_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.gather(input: Tensor, dim: int, index: LongTensor)\n # * input and index tensors have same ndims.\n # * index tensors must be smaller than input tensor along all dims except specified axis.\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(\n make_tensor, device=\"cuda\", dtype=torch.long, requires_grad=False\n )\n\n # a.shape, dim, b.shape\n cases = (\n ((4, 2, 3), 0, (8, 2, 3)),\n ((4, 2, 3), 1, (4, 1, 3)),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.gather_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.gather_generator#L774-L811","kind":"function","name":"gather_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":774,"end_line":811,"context_start_line":754,"context_end_line":831,"code":" # ((8,), 0, (8)),\n # ((8,), 0, (4)),\n # ((8,), 0, (1)),\n # ((4, 1), 0, (1, 1)),\n # ((4, 5), 1, (4, 1)),\n # ((8, 2, 3), 0, (4, 1, 2)),\n # ((8, 2, 3), 1, (4, 1, 2)),\n # ((8, 2, 3), 2, (4, 1, 2)),\n # ((8, 2, 3), -3, (4, 2, 3)),\n # ((4, 2, 3), -2, (4, 2, 3)),\n # ((4, 2, 3), -1, (4, 2, 2)),\n )\n\n for shape_a, dim, shape_b in cases:\n a = make_arg(shape_a)\n b = make_unique_index(shape_b, dim, shape_a[dim])\n c = make_arg(shape_b)\n yield SampleInput(a, b, c, dim)\n\n\ndef gather_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.gather(input: Tensor, dim: int, index: LongTensor)\n # * input and index tensors have same ndims.\n # * index tensors must be smaller than input tensor along all dims except specified axis.\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(\n make_tensor, device=\"cuda\", dtype=torch.long, requires_grad=False\n )\n\n # a.shape, dim, b.shape\n cases = (\n ((4, 2, 3), 0, (8, 2, 3)),\n ((4, 2, 3), 1, (4, 1, 3)),\n ((4, 2, 3), 2, (4, 2, 5)),\n ((4,), 0, (8)),\n ((4,), 0, (1)),\n ((4, 1), 0, (3, 1)),\n ((4, 1), 1, (4, 5)),\n # negative dim\n ((4, 2, 3), -3, (8, 2, 3)),\n ((4, 2, 3), -2, (4, 1, 3)),\n ((4, 2, 3), -1, (4, 2, 5)),\n ((4,), -1, (8)),\n ((4,), -1, (1)),\n ((4, 1), -2, (3, 1)),\n ((4, 1), -1, (4, 5)),\n # nvfuser gather does not support broadcast non-axis dimensions\n )\n\n for shape_a, dim, shape_b in cases:\n a = make_arg(shape_a)\n b = make_index(shape_b, low=0, high=shape_a[dim])\n yield SampleInput(a, b, dim)\n\n\ndef argsort_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # a.shape, dim\n cases = (\n (list(), 0),\n ((128,), 0),\n ((128, 7, 32), 0),\n ((128, 7, 32), 1),\n ((128, 7, 32), 2),\n ((128, 7, 32), -1),\n ((128, 7, 32), -2),\n ((128, 7, 32), -3),\n )","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.argsort_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.argsort_generator#L814-L836","kind":"function","name":"argsort_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":814,"end_line":836,"context_start_line":794,"context_end_line":856,"code":" ((4,), 0, (1)),\n ((4, 1), 0, (3, 1)),\n ((4, 1), 1, (4, 5)),\n # negative dim\n ((4, 2, 3), -3, (8, 2, 3)),\n ((4, 2, 3), -2, (4, 1, 3)),\n ((4, 2, 3), -1, (4, 2, 5)),\n ((4,), -1, (8)),\n ((4,), -1, (1)),\n ((4, 1), -2, (3, 1)),\n ((4, 1), -1, (4, 5)),\n # nvfuser gather does not support broadcast non-axis dimensions\n )\n\n for shape_a, dim, shape_b in cases:\n a = make_arg(shape_a)\n b = make_index(shape_b, low=0, high=shape_a[dim])\n yield SampleInput(a, b, dim)\n\n\ndef argsort_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # a.shape, dim\n cases = (\n (list(), 0),\n ((128,), 0),\n ((128, 7, 32), 0),\n ((128, 7, 32), 1),\n ((128, 7, 32), 2),\n ((128, 7, 32), -1),\n ((128, 7, 32), -2),\n ((128, 7, 32), -3),\n )\n\n for shape, dim in cases:\n a = make_arg(shape)\n for descending, stable in itertools.product([True, False], repeat=2):\n yield SampleInput(a, dim, descending, stable)\n\n\ndef topk_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate valid test cases for topk operation.\n\n Creates test tensors of various shapes and tests different combinations of:\n - k values (ensuring k <= dimension size)\n - largest/smallest selection\n - sorted/unsorted output\n\n Args:\n op: OpInfo object for the topk operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n\n Yields:\n SampleInput objects with valid topk parameters","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.topk_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.topk_generator#L839-L880","kind":"function","name":"topk_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":839,"end_line":880,"context_start_line":819,"context_end_line":900,"code":" )\n\n # a.shape, dim\n cases = (\n (list(), 0),\n ((128,), 0),\n ((128, 7, 32), 0),\n ((128, 7, 32), 1),\n ((128, 7, 32), 2),\n ((128, 7, 32), -1),\n ((128, 7, 32), -2),\n ((128, 7, 32), -3),\n )\n\n for shape, dim in cases:\n a = make_arg(shape)\n for descending, stable in itertools.product([True, False], repeat=2):\n yield SampleInput(a, dim, descending, stable)\n\n\ndef topk_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate valid test cases for topk operation.\n\n Creates test tensors of various shapes and tests different combinations of:\n - k values (ensuring k <= dimension size)\n - largest/smallest selection\n - sorted/unsorted output\n\n Args:\n op: OpInfo object for the topk operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n\n Yields:\n SampleInput objects with valid topk parameters\n \"\"\"\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # a.shape, dim, k_values\n cases = (\n # NOTE: aten supports topk on scalar tensor. Not sure if we would want to support this.\n # (list(), 0, [0, 1]),\n ((128,), 0, [5, 10, 64]),\n ((128, 7, 32), 0, [5, 1, 128]),\n ((128, 7, 32), 1, [5, 1, 7]),\n ((128, 7, 32), 2, [5, 1, 32]),\n ((128, 7, 32), -1, [5, 1, 32]),\n ((128, 7, 32), -2, [5, 1, 7]),\n ((128, 7, 32), -3, [5, 1, 128]),\n )\n\n for shape, dim, k_values in cases:\n a = make_arg(shape)\n for k in k_values:\n for largest in [True, False]:\n # NOTE: we do not test unsorted result, because reference implementation is not stable.\n yield SampleInput(a, k, dim, largest, True)\n\n\ndef topk_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate test cases that should produce errors for topk operation.\n\n Args:\n op: OpInfo object for the topk operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n\n Yields:\n Tuples of (SampleInput, expected_exception_type, error_message_pattern)\n \"\"\"\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.topk_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.topk_error_generator#L883-L917","kind":"function","name":"topk_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":883,"end_line":917,"context_start_line":863,"context_end_line":937,"code":" cases = (\n # NOTE: aten supports topk on scalar tensor. Not sure if we would want to support this.\n # (list(), 0, [0, 1]),\n ((128,), 0, [5, 10, 64]),\n ((128, 7, 32), 0, [5, 1, 128]),\n ((128, 7, 32), 1, [5, 1, 7]),\n ((128, 7, 32), 2, [5, 1, 32]),\n ((128, 7, 32), -1, [5, 1, 32]),\n ((128, 7, 32), -2, [5, 1, 7]),\n ((128, 7, 32), -3, [5, 1, 128]),\n )\n\n for shape, dim, k_values in cases:\n a = make_arg(shape)\n for k in k_values:\n for largest in [True, False]:\n # NOTE: we do not test unsorted result, because reference implementation is not stable.\n yield SampleInput(a, k, dim, largest, True)\n\n\ndef topk_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate test cases that should produce errors for topk operation.\n\n Args:\n op: OpInfo object for the topk operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n\n Yields:\n Tuples of (SampleInput, expected_exception_type, error_message_pattern)\n \"\"\"\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n a = make_arg((128, 7, 32))\n\n # Out of bounds dimension access\n yield SampleInput(\n a, 3, 3, True, False\n ), RuntimeError, \"Tried to access out of boundary index\"\n yield SampleInput(\n a, 3, -4, True, False\n ), RuntimeError, \"Tried to access out of boundary index\"\n\n # Concretization should detect the negative K as an error\n yield SampleInput(\n a, -5, 1, True, False\n ), RuntimeError, \"Invalid resized domain extent\"\n\n # error coming from aten fallback.\n yield SampleInput(a, 16, 1, True, False), RuntimeError, \"k .* range\"\n\n\ndef index_select_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(make_tensor, device=\"cuda\", requires_grad=False)\n\n # a.shape, dim, b.shape\n cases = (\n ((4, 2, 3), 0, (8)),\n ((4, 2, 3), 1, (7)),\n ((4, 2, 3), 2, (2)),\n ((4,), 0, (8)),\n ((4,), 0, (1)),\n ((4, 1), 0, (3)),\n ((4, 1), 1, (5)),\n ((1, 0, 3), 0, (8)),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.index_select_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.index_select_generator#L920-L944","kind":"function","name":"index_select_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":920,"end_line":944,"context_start_line":900,"context_end_line":964,"code":"\n a = make_arg((128, 7, 32))\n\n # Out of bounds dimension access\n yield SampleInput(\n a, 3, 3, True, False\n ), RuntimeError, \"Tried to access out of boundary index\"\n yield SampleInput(\n a, 3, -4, True, False\n ), RuntimeError, \"Tried to access out of boundary index\"\n\n # Concretization should detect the negative K as an error\n yield SampleInput(\n a, -5, 1, True, False\n ), RuntimeError, \"Invalid resized domain extent\"\n\n # error coming from aten fallback.\n yield SampleInput(a, 16, 1, True, False), RuntimeError, \"k .* range\"\n\n\ndef index_select_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(make_tensor, device=\"cuda\", requires_grad=False)\n\n # a.shape, dim, b.shape\n cases = (\n ((4, 2, 3), 0, (8)),\n ((4, 2, 3), 1, (7)),\n ((4, 2, 3), 2, (2)),\n ((4,), 0, (8)),\n ((4,), 0, (1)),\n ((4, 1), 0, (3)),\n ((4, 1), 1, (5)),\n ((1, 0, 3), 0, (8)),\n )\n\n for shape_a, dim, shape_b in cases:\n for index_dtype in [torch.int, torch.long]:\n a = make_arg(shape_a)\n b = make_index(shape_b, low=0, high=shape_a[dim], dtype=index_dtype)\n yield SampleInput(a, b, dim)\n\n\ndef index_select_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.index_select(input: Tensor, dim: int, index: LongTensor)\n # * dim is within bounds\n # * index is a 1D vector\n # * index array can't have zero elements\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(make_tensor, device=\"cuda\", requires_grad=False)\n\n input_shape = (4, 2)\n index_shape = (8,)\n\n a = make_arg(input_shape)\n\n # dim, exception type, exception string","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.index_select_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.index_select_error_generator#L947-L983","kind":"function","name":"index_select_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":947,"end_line":983,"context_start_line":927,"context_end_line":1003,"code":"\n # a.shape, dim, b.shape\n cases = (\n ((4, 2, 3), 0, (8)),\n ((4, 2, 3), 1, (7)),\n ((4, 2, 3), 2, (2)),\n ((4,), 0, (8)),\n ((4,), 0, (1)),\n ((4, 1), 0, (3)),\n ((4, 1), 1, (5)),\n ((1, 0, 3), 0, (8)),\n )\n\n for shape_a, dim, shape_b in cases:\n for index_dtype in [torch.int, torch.long]:\n a = make_arg(shape_a)\n b = make_index(shape_b, low=0, high=shape_a[dim], dtype=index_dtype)\n yield SampleInput(a, b, dim)\n\n\ndef index_select_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.index_select(input: Tensor, dim: int, index: LongTensor)\n # * dim is within bounds\n # * index is a 1D vector\n # * index array can't have zero elements\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(make_tensor, device=\"cuda\", requires_grad=False)\n\n input_shape = (4, 2)\n index_shape = (8,)\n\n a = make_arg(input_shape)\n\n # dim, exception type, exception string\n positive_axis = (\n 2,\n RuntimeError,\n \"Tried to access out of boundary index 2. total index: 2\",\n )\n negative_axis = (\n -3,\n RuntimeError,\n \"Tried to access out of boundary index -1. total index: 2\",\n )\n\n error_cases = [\n positive_axis,\n negative_axis,\n ]\n\n for dim, ex_type, ex_str in error_cases:\n b = make_index(index_shape, low=0, high=10, dtype=torch.long)\n yield SampleInput(a, b, dim), ex_type, ex_str\n\n # TODO add index dtype check\n # b = make_index(index_shape, low=0, high=input_shape[0], dtype=torch.float)\n # yield SampleInput(a, b, 0), RuntimeError, \"index tensor can only be int or long dtype.\"\n\n # TODO add index out-of-bounds check\n # b = make_index(index_shape, low=10, high=100, dtype=torch.long)\n # yield SampleInput(a, b, 0), RuntimeError, \"out of bounds index value.\"\n\n\ndef index_put_accumulate_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(make_tensor, device=\"cuda\", requires_grad=False)\n\n # vocab_size, hidden_size, seq_size\n cases = ((1024, 12, 300),)","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.index_put_accumulate_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.index_put_accumulate_generator#L994-L1010","kind":"function","name":"index_put_accumulate_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":994,"end_line":1010,"context_start_line":974,"context_end_line":1030,"code":" )\n\n error_cases = [\n positive_axis,\n negative_axis,\n ]\n\n for dim, ex_type, ex_str in error_cases:\n b = make_index(index_shape, low=0, high=10, dtype=torch.long)\n yield SampleInput(a, b, dim), ex_type, ex_str\n\n # TODO add index dtype check\n # b = make_index(index_shape, low=0, high=input_shape[0], dtype=torch.float)\n # yield SampleInput(a, b, 0), RuntimeError, \"index tensor can only be int or long dtype.\"\n\n # TODO add index out-of-bounds check\n # b = make_index(index_shape, low=10, high=100, dtype=torch.long)\n # yield SampleInput(a, b, 0), RuntimeError, \"out of bounds index value.\"\n\n\ndef index_put_accumulate_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(make_tensor, device=\"cuda\", requires_grad=False)\n\n # vocab_size, hidden_size, seq_size\n cases = ((1024, 12, 300),)\n\n for vocab, hidden, seq in cases:\n for index_dtype in [torch.int, torch.long]:\n acc = make_arg((vocab, hidden))\n index = make_index((seq,), low=0, high=vocab, dtype=index_dtype)\n value = make_arg((seq, hidden))\n yield SampleInput(acc, index, value)\n\n\ndef iota_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.arange(start=0, end, step=1, dtype=None)\n # nvfuser.iota(length, start, step, dtype)\n #\n # length, start, step are not complex numbers and are finite numbers.\n # step cannot be 0\n\n yield SampleInput(\n make_number(torch.complex64, low=1),\n make_number(dtype, low=0),\n make_number(dtype, low=0),\n dtype,\n ), RuntimeError, \"length must be integer\"\n\n yield SampleInput(\n make_number(torch.int64, low=1),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.iota_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.iota_error_generator#L1013-L1054","kind":"function","name":"iota_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1013,"end_line":1054,"context_start_line":993,"context_end_line":1074,"code":"\ndef index_put_accumulate_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(make_tensor, device=\"cuda\", requires_grad=False)\n\n # vocab_size, hidden_size, seq_size\n cases = ((1024, 12, 300),)\n\n for vocab, hidden, seq in cases:\n for index_dtype in [torch.int, torch.long]:\n acc = make_arg((vocab, hidden))\n index = make_index((seq,), low=0, high=vocab, dtype=index_dtype)\n value = make_arg((seq, hidden))\n yield SampleInput(acc, index, value)\n\n\ndef iota_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.arange(start=0, end, step=1, dtype=None)\n # nvfuser.iota(length, start, step, dtype)\n #\n # length, start, step are not complex numbers and are finite numbers.\n # step cannot be 0\n\n yield SampleInput(\n make_number(torch.complex64, low=1),\n make_number(dtype, low=0),\n make_number(dtype, low=0),\n dtype,\n ), RuntimeError, \"length must be integer\"\n\n yield SampleInput(\n make_number(torch.int64, low=1),\n make_number(torch.complex64),\n make_number(dtype, low=0),\n dtype,\n ), RuntimeError, \"iota: start dtype does not match specified dtype argument\"\n\n yield SampleInput(\n make_number(torch.int64, low=1),\n make_number(dtype, low=0),\n make_number(torch.complex64),\n dtype,\n ), RuntimeError, \"iota: step dtype does not match specified dtype argument\"\n\n if is_floating_dtype(dtype):\n yield SampleInput(\n make_number(torch.int64, low=1),\n float(\"inf\"),\n float(\"inf\"),\n dtype,\n ), RuntimeError, \"iota: length, start, step must be finite numbers.\"\n\n zero_step = torch.tensor([0], dtype=dtype).item()\n yield SampleInput(\n 10, make_number(dtype), zero_step, dtype\n ), RuntimeError, \"iota: step value must not equal zero.\"\n\n\ndef pad_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # Nvfuser - fd.ops.pad(Tensor arg, std::vector& pad_widths, std::optional value)\n # Jax ----- jax.lax.pad(operand, padding_value, padding_config)\n # PyTorch - torch.nn.functional.pad(input, pad, mode='constant', value=None)\n #\n # Note: Nvfuser does not support interior (between-element) padding.\n #\n # Nvfuser errors\n # 1) Tensor arg and pad value must have the same dtype\n # 2) Number of pad widths must be at most twice the input dimension - NvFuser\n # 3) Dimension size after padding is not at least 0\n #\n # Jax and PyTorch errors\n # 1) Interior padding is non-negative\n # 2) Length of pad_widths is equal to number of operands\n","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.pad_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.pad_error_generator#L1057-L1103","kind":"function","name":"pad_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1057,"end_line":1103,"context_start_line":1037,"context_end_line":1123,"code":" make_number(torch.int64, low=1),\n make_number(dtype, low=0),\n make_number(torch.complex64),\n dtype,\n ), RuntimeError, \"iota: step dtype does not match specified dtype argument\"\n\n if is_floating_dtype(dtype):\n yield SampleInput(\n make_number(torch.int64, low=1),\n float(\"inf\"),\n float(\"inf\"),\n dtype,\n ), RuntimeError, \"iota: length, start, step must be finite numbers.\"\n\n zero_step = torch.tensor([0], dtype=dtype).item()\n yield SampleInput(\n 10, make_number(dtype), zero_step, dtype\n ), RuntimeError, \"iota: step value must not equal zero.\"\n\n\ndef pad_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # Nvfuser - fd.ops.pad(Tensor arg, std::vector& pad_widths, std::optional value)\n # Jax ----- jax.lax.pad(operand, padding_value, padding_config)\n # PyTorch - torch.nn.functional.pad(input, pad, mode='constant', value=None)\n #\n # Note: Nvfuser does not support interior (between-element) padding.\n #\n # Nvfuser errors\n # 1) Tensor arg and pad value must have the same dtype\n # 2) Number of pad widths must be at most twice the input dimension - NvFuser\n # 3) Dimension size after padding is not at least 0\n #\n # Jax and PyTorch errors\n # 1) Interior padding is non-negative\n # 2) Length of pad_widths is equal to number of operands\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n input_shape = (2, 2)\n valid_pad_width = [1, 1, -1, 2]\n\n yield SampleInput(\n make_arg(input_shape),\n valid_pad_width,\n make_number(find_nonmatching_dtype(dtype)),\n ), RuntimeError, \"Tensor arg and pad value must have the same dtype.\"\n\n # TODO Add better error message.\n # Dimension size after padding is not at least 0\n delete_all_pad_width = [-3, 0, 0, 0]\n yield SampleInput(\n make_arg(input_shape), delete_all_pad_width, make_number(dtype)\n ), RuntimeError, \"Invalid resized domain extent\"\n\n too_many_pad_width = [1, 1, 1, 1, 1, 1]\n yield SampleInput(\n make_arg(input_shape), too_many_pad_width, make_number(dtype)\n ), RuntimeError, \"Number of pad widths must be at most twice the input dimension\"\n\n uneven_pad_width = [1, 1, 0]\n yield SampleInput(\n make_arg(input_shape), uneven_pad_width, make_number(dtype)\n ), RuntimeError, \"Invalid number of padding widths\"\n\n\ndef permute_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n cases = (\n ((4, 3, 7, 8), (0, 1, 2, 3)),\n ((4, 3, 7, 8), (1, -2, 0, 3)),\n ((4, 3, 7, 8), (-2, 1, 0, -1)),\n ((4, 3, 7, 8), (0, 3, 1, 2)),\n ((4, 3, 7, 8), (0, -1, 1, 2)),\n ((4, 7), (1, 0)),\n )\n\n for shape, dims in cases:\n yield SampleInput(make_arg(shape), dims)","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.permute_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.permute_generator#L1106-L1123","kind":"function","name":"permute_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1106,"end_line":1123,"context_start_line":1086,"context_end_line":1143,"code":" ), RuntimeError, \"Tensor arg and pad value must have the same dtype.\"\n\n # TODO Add better error message.\n # Dimension size after padding is not at least 0\n delete_all_pad_width = [-3, 0, 0, 0]\n yield SampleInput(\n make_arg(input_shape), delete_all_pad_width, make_number(dtype)\n ), RuntimeError, \"Invalid resized domain extent\"\n\n too_many_pad_width = [1, 1, 1, 1, 1, 1]\n yield SampleInput(\n make_arg(input_shape), too_many_pad_width, make_number(dtype)\n ), RuntimeError, \"Number of pad widths must be at most twice the input dimension\"\n\n uneven_pad_width = [1, 1, 0]\n yield SampleInput(\n make_arg(input_shape), uneven_pad_width, make_number(dtype)\n ), RuntimeError, \"Invalid number of padding widths\"\n\n\ndef permute_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n cases = (\n ((4, 3, 7, 8), (0, 1, 2, 3)),\n ((4, 3, 7, 8), (1, -2, 0, 3)),\n ((4, 3, 7, 8), (-2, 1, 0, -1)),\n ((4, 3, 7, 8), (0, 3, 1, 2)),\n ((4, 3, 7, 8), (0, -1, 1, 2)),\n ((4, 7), (1, 0)),\n )\n\n for shape, dims in cases:\n yield SampleInput(make_arg(shape), dims)\n\n\ndef permute_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.permute(input: torch.Tensor, dims: List[int])\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n input_shape = (10, 3, 4, 4)\n # dims = dtype, duplicate, in-range\n\n # TODO Add dtype check.\n yield SampleInput(\n make_arg(input_shape), [0.0, 1.0, 2.0, 3.0]\n ), TypeError, \"permute(): incompatible function arguments\"\n\n # TODO Add duplicate axis check.","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.permute_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.permute_error_generator#L1126-L1167","kind":"function","name":"permute_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1126,"end_line":1167,"context_start_line":1106,"context_end_line":1187,"code":"def permute_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n cases = (\n ((4, 3, 7, 8), (0, 1, 2, 3)),\n ((4, 3, 7, 8), (1, -2, 0, 3)),\n ((4, 3, 7, 8), (-2, 1, 0, -1)),\n ((4, 3, 7, 8), (0, 3, 1, 2)),\n ((4, 3, 7, 8), (0, -1, 1, 2)),\n ((4, 7), (1, 0)),\n )\n\n for shape, dims in cases:\n yield SampleInput(make_arg(shape), dims)\n\n\ndef permute_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.permute(input: torch.Tensor, dims: List[int])\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n input_shape = (10, 3, 4, 4)\n # dims = dtype, duplicate, in-range\n\n # TODO Add dtype check.\n yield SampleInput(\n make_arg(input_shape), [0.0, 1.0, 2.0, 3.0]\n ), TypeError, \"permute(): incompatible function arguments\"\n\n # TODO Add duplicate axis check.\n yield SampleInput(\n make_arg(input_shape), [0, 1, 1, 3]\n ), RuntimeError, \"duplicated dimension entries\"\n\n # TODO Add in-range axis check.\n yield SampleInput(\n make_arg(input_shape), [0, 1, 2, 4]\n ), RuntimeError, \"dims argument is out of range, expects\"\n\n # TODO Add in-range axis check.\n yield SampleInput(\n make_arg(input_shape), [0, 1, 2, -5]\n ), RuntimeError, \"dims argument is out of range, expects\"\n\n # TODO Add missing axes check.\n # If dims list is empty, NvFuser ignores the permute operation.\n yield SampleInput(\n make_arg(input_shape), [0]\n ), RuntimeError, \"argument to have the same length as input\"\n\n # TODO Add out-of-bounds axes check.\n yield SampleInput(\n make_arg(input_shape), [0, 1, 2, 3, 4]\n ), RuntimeError, \"argument to have the same length as input\"\n\n\ndef random_dist_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # Checking that non-supported dtypes fail\n yield SampleInput(\n make_number(torch.float),\n make_number(torch.float),\n [2, 2],\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n ), RuntimeError, \"Random distributions only create floating point types\"\n\n\ndef reduction_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor,\n device=\"cuda\",","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.random_dist_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.random_dist_error_generator#L1170-L1179","kind":"function","name":"random_dist_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1170,"end_line":1179,"context_start_line":1150,"context_end_line":1199,"code":" make_arg(input_shape), [0, 1, 2, 4]\n ), RuntimeError, \"dims argument is out of range, expects\"\n\n # TODO Add in-range axis check.\n yield SampleInput(\n make_arg(input_shape), [0, 1, 2, -5]\n ), RuntimeError, \"dims argument is out of range, expects\"\n\n # TODO Add missing axes check.\n # If dims list is empty, NvFuser ignores the permute operation.\n yield SampleInput(\n make_arg(input_shape), [0]\n ), RuntimeError, \"argument to have the same length as input\"\n\n # TODO Add out-of-bounds axes check.\n yield SampleInput(\n make_arg(input_shape), [0, 1, 2, 3, 4]\n ), RuntimeError, \"argument to have the same length as input\"\n\n\ndef random_dist_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # Checking that non-supported dtypes fail\n yield SampleInput(\n make_number(torch.float),\n make_number(torch.float),\n [2, 2],\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n ), RuntimeError, \"Random distributions only create floating point types\"\n\n\ndef reduction_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n # We set low (inclusive) and high (exclusive) here to avoid values\n # whose products can otherwise become extremely large\n low=-2,\n high=3,\n )\n\n # shape, dim, keepdim, dtype\n cases = (\n ((4, 4), None, False, None),\n ((5,), None, True, None),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.reduction_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.reduction_generator#L1182-L1208","kind":"function","name":"reduction_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1182,"end_line":1208,"context_start_line":1162,"context_end_line":1228,"code":" ), RuntimeError, \"argument to have the same length as input\"\n\n # TODO Add out-of-bounds axes check.\n yield SampleInput(\n make_arg(input_shape), [0, 1, 2, 3, 4]\n ), RuntimeError, \"argument to have the same length as input\"\n\n\ndef random_dist_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # Checking that non-supported dtypes fail\n yield SampleInput(\n make_number(torch.float),\n make_number(torch.float),\n [2, 2],\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n ), RuntimeError, \"Random distributions only create floating point types\"\n\n\ndef reduction_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n # We set low (inclusive) and high (exclusive) here to avoid values\n # whose products can otherwise become extremely large\n low=-2,\n high=3,\n )\n\n # shape, dim, keepdim, dtype\n cases = (\n ((4, 4), None, False, None),\n ((5,), None, True, None),\n ((5,), (0,), False, None),\n ((8, 1, 6), (1,), True, None),\n ((8, 7, 5, 1), (0, 1), True, None),\n ((8, 7, 5, 1), (1, 3), False, None),\n )\n\n for c in cases:\n shape, dim, keepdim, dtype = c\n yield (SampleInput(make_arg(shape), dim, keepdim, dtype=dtype))\n\n\ndef reduction_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n # We set low (inclusive) and high (exclusive) here to avoid values\n # whose products can otherwise become extremely large\n low=-2,\n high=3,\n )\n\n # shape\n cases = (\n (8, 1, 6),\n (8, 7, 5, 1),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.reduction_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.reduction_error_generator#L1211-L1255","kind":"function","name":"reduction_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1211,"end_line":1255,"context_start_line":1191,"context_end_line":1275,"code":" # whose products can otherwise become extremely large\n low=-2,\n high=3,\n )\n\n # shape, dim, keepdim, dtype\n cases = (\n ((4, 4), None, False, None),\n ((5,), None, True, None),\n ((5,), (0,), False, None),\n ((8, 1, 6), (1,), True, None),\n ((8, 7, 5, 1), (0, 1), True, None),\n ((8, 7, 5, 1), (1, 3), False, None),\n )\n\n for c in cases:\n shape, dim, keepdim, dtype = c\n yield (SampleInput(make_arg(shape), dim, keepdim, dtype=dtype))\n\n\ndef reduction_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n # We set low (inclusive) and high (exclusive) here to avoid values\n # whose products can otherwise become extremely large\n low=-2,\n high=3,\n )\n\n # shape\n cases = (\n (8, 1, 6),\n (8, 7, 5, 1),\n )\n\n # axes : List[int]\n # 1) all axis are int --- use float dtype\n # 2) all axes are unique --- duplicates\n # 3) after normalization, 0 <= axis[i] <= len(size)\n # 4) If empty tensor, then axis == 0\n\n int_dtype_axis = (\n lambda dims: float(dims),\n TypeError,\n \"var_mean(): incompatible function arguments.\",\n )\n duplicate_axis = (\n lambda dims: (0, 0, 0),\n RuntimeError,\n \"Reduction axes are not unique\",\n )\n lower_bound = (lambda dims: (-dims - 1,), RuntimeError, \"Reduction on invalid axis\")\n upper_bound = (lambda dims: (dims,), RuntimeError, \"Reduction on invalid axis\")\n # TODO Fix duplicate_axis, lower_bound, upper_bound\n error_cases = [int_dtype_axis]\n\n for shape, es in itertools.product(cases, error_cases):\n input_tensor = make_arg(shape)\n axis_fn, ex_type, ex_str = es\n yield SampleInput(input_tensor, axis_fn(len(shape))), ex_type, ex_str\n\n\ndef reshape_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # TODO Add examples with negative index\n # TODO: Add zero-dim cases\n # TODO: Add strided tensor cases\n cases = (\n ((1, 19, 1, 12, 7, 1, 99), (1, 19, 1, 3, 2772)),\n ((3, 17, 80, 1), (51, 1, 2, 4, 10)),\n ((3, 17, 80, 1, 9), (51, 1, 2, 4, 10, 9)),\n ((2, 3, 4, 5), (1, 6, 1, 2, 2, 5)),\n ((22, 22, 2), (22, 11, 1, 1, 4)),\n ((37, 9, 7, 6, 10), (333, 2, 2, 3, 35)),\n ((8, 1, 1, 8, 1, 8), (8, 2, 4, 1, 8)),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.reshape_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.reshape_generator#L1258-L1288","kind":"function","name":"reshape_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1258,"end_line":1288,"context_start_line":1238,"context_end_line":1308,"code":" lambda dims: float(dims),\n TypeError,\n \"var_mean(): incompatible function arguments.\",\n )\n duplicate_axis = (\n lambda dims: (0, 0, 0),\n RuntimeError,\n \"Reduction axes are not unique\",\n )\n lower_bound = (lambda dims: (-dims - 1,), RuntimeError, \"Reduction on invalid axis\")\n upper_bound = (lambda dims: (dims,), RuntimeError, \"Reduction on invalid axis\")\n # TODO Fix duplicate_axis, lower_bound, upper_bound\n error_cases = [int_dtype_axis]\n\n for shape, es in itertools.product(cases, error_cases):\n input_tensor = make_arg(shape)\n axis_fn, ex_type, ex_str = es\n yield SampleInput(input_tensor, axis_fn(len(shape))), ex_type, ex_str\n\n\ndef reshape_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # TODO Add examples with negative index\n # TODO: Add zero-dim cases\n # TODO: Add strided tensor cases\n cases = (\n ((1, 19, 1, 12, 7, 1, 99), (1, 19, 1, 3, 2772)),\n ((3, 17, 80, 1), (51, 1, 2, 4, 10)),\n ((3, 17, 80, 1, 9), (51, 1, 2, 4, 10, 9)),\n ((2, 3, 4, 5), (1, 6, 1, 2, 2, 5)),\n ((22, 22, 2), (22, 11, 1, 1, 4)),\n ((37, 9, 7, 6, 10), (333, 2, 2, 3, 35)),\n ((8, 1, 1, 8, 1, 8), (8, 2, 4, 1, 8)),\n ((1, 333, 1), (1, 37, 9)),\n ((1, 333), (1, 1, 1, 111, 1, 3)),\n ((1, 27454, 1, 2), (1, 7844, 1, 7)),\n ((1, 7844, 1, 7), (1, 27454, 2)),\n )\n\n for input_shape, output_shape in cases:\n input_tensor = make_arg(input_shape)\n if op.name == \"reshape_symbolic\":\n reshaped_tensor = make_arg(output_shape)\n yield SampleInput(input_tensor, reshaped_tensor)\n else:\n yield SampleInput(input_tensor, output_shape)\n\n\ndef reshape_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.reshape(input: Tensor, shape: [int])\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n input_shape = (3, 14)\n\n # Only a single inferred axis -1. Skip reshape_symbolic because\n # make_arg can't create a tensor with negative dimensions.\n if op.name == \"reshape_constant\":\n yield SampleInput(\n make_arg(input_shape), (3, -1, -1)\n ), RuntimeError, \"A maximum of one value of -1\"\n","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.reshape_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.reshape_error_generator#L1291-L1314","kind":"function","name":"reshape_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1291,"end_line":1314,"context_start_line":1271,"context_end_line":1334,"code":" ((3, 17, 80, 1, 9), (51, 1, 2, 4, 10, 9)),\n ((2, 3, 4, 5), (1, 6, 1, 2, 2, 5)),\n ((22, 22, 2), (22, 11, 1, 1, 4)),\n ((37, 9, 7, 6, 10), (333, 2, 2, 3, 35)),\n ((8, 1, 1, 8, 1, 8), (8, 2, 4, 1, 8)),\n ((1, 333, 1), (1, 37, 9)),\n ((1, 333), (1, 1, 1, 111, 1, 3)),\n ((1, 27454, 1, 2), (1, 7844, 1, 7)),\n ((1, 7844, 1, 7), (1, 27454, 2)),\n )\n\n for input_shape, output_shape in cases:\n input_tensor = make_arg(input_shape)\n if op.name == \"reshape_symbolic\":\n reshaped_tensor = make_arg(output_shape)\n yield SampleInput(input_tensor, reshaped_tensor)\n else:\n yield SampleInput(input_tensor, output_shape)\n\n\ndef reshape_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.reshape(input: Tensor, shape: [int])\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n input_shape = (3, 14)\n\n # Only a single inferred axis -1. Skip reshape_symbolic because\n # make_arg can't create a tensor with negative dimensions.\n if op.name == \"reshape_constant\":\n yield SampleInput(\n make_arg(input_shape), (3, -1, -1)\n ), RuntimeError, \"A maximum of one value of -1\"\n\n # Number of elements must be equal for input and output tensors\n output_shape = (3, 2, 8)\n yield SampleInput(\n make_arg(input_shape),\n (output_shape if op.name == \"reshape_constant\" else make_arg(output_shape)),\n ), RuntimeError, \"Total element counts across view operation must match\"\n\n\n# TODO: add stride testing\ndef slice_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # shape, start_indices, end_indices\n cases = (\n ((5, 7, 8), (1, 0, 3), (2, 6, 8)),\n ((3,), (1,), (2,)),\n )\n\n for shape, start_indices, end_indices in cases:\n a = make_arg(shape)\n yield SampleInput(a, start_indices=start_indices, end_indices=end_indices)\n","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.slice_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.slice_generator#L1318-L1333","kind":"function","name":"slice_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1318,"end_line":1333,"context_start_line":1298,"context_end_line":1353,"code":" )\n\n input_shape = (3, 14)\n\n # Only a single inferred axis -1. Skip reshape_symbolic because\n # make_arg can't create a tensor with negative dimensions.\n if op.name == \"reshape_constant\":\n yield SampleInput(\n make_arg(input_shape), (3, -1, -1)\n ), RuntimeError, \"A maximum of one value of -1\"\n\n # Number of elements must be equal for input and output tensors\n output_shape = (3, 2, 8)\n yield SampleInput(\n make_arg(input_shape),\n (output_shape if op.name == \"reshape_constant\" else make_arg(output_shape)),\n ), RuntimeError, \"Total element counts across view operation must match\"\n\n\n# TODO: add stride testing\ndef slice_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # shape, start_indices, end_indices\n cases = (\n ((5, 7, 8), (1, 0, 3), (2, 6, 8)),\n ((3,), (1,), (2,)),\n )\n\n for shape, start_indices, end_indices in cases:\n a = make_arg(shape)\n yield SampleInput(a, start_indices=start_indices, end_indices=end_indices)\n\n\ndef slice_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # shape\n cases = ((10, 10), (5, 5))\n\n check_start_indices = ErrorSample(\n {\"start_indices\": [-1, -2], \"end_indices\": [5, 5], \"strides\": [7, 7]},\n \"Slice operation start_indices must be greater than or equal to 0.\",\n )\n\n check_end_indices = ErrorSample(\n {\"start_indices\": [3, 4], \"end_indices\": [1, 2], \"strides\": [1, 1]},\n \"Slice operation end_indices must be greater than or equal to start_indices.\",","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.slice_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.slice_error_generator#L1336-L1393","kind":"function","name":"slice_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1336,"end_line":1393,"context_start_line":1316,"context_end_line":1413,"code":"\n# TODO: add stride testing\ndef slice_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # shape, start_indices, end_indices\n cases = (\n ((5, 7, 8), (1, 0, 3), (2, 6, 8)),\n ((3,), (1,), (2,)),\n )\n\n for shape, start_indices, end_indices in cases:\n a = make_arg(shape)\n yield SampleInput(a, start_indices=start_indices, end_indices=end_indices)\n\n\ndef slice_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # shape\n cases = ((10, 10), (5, 5))\n\n check_start_indices = ErrorSample(\n {\"start_indices\": [-1, -2], \"end_indices\": [5, 5], \"strides\": [7, 7]},\n \"Slice operation start_indices must be greater than or equal to 0.\",\n )\n\n check_end_indices = ErrorSample(\n {\"start_indices\": [3, 4], \"end_indices\": [1, 2], \"strides\": [1, 1]},\n \"Slice operation end_indices must be greater than or equal to start_indices.\",\n )\n\n check_strides = ErrorSample(\n {\"start_indices\": [0, 0], \"end_indices\": [5, 5], \"strides\": [5, 5]},\n \"nvFuser Limitation: All slice operation strides must be of const size 1.\",\n )\n\n check_tensor_dims = ErrorSample(\n {\"start_indices\": [0, 0, 0], \"end_indices\": [4, 4, 4], \"strides\": [1, 1, 1]},\n \"Number of tensor dimensions does not match slice dimensions!\",\n )\n\n check_slice_dims_start = ErrorSample(\n {\"start_indices\": [0, 0, 0], \"end_indices\": [4, 4], \"strides\": [1, 1]},\n \"Slice start_indices and strides don't match!\",\n )\n\n check_slice_dims_end = ErrorSample(\n {\"start_indices\": [0, 0], \"end_indices\": [4, 4, 4], \"strides\": [1, 1]},\n \"Slice indexing attribute dimensions don't match!\",\n )\n\n check_slice_dims_stride = ErrorSample(\n {\"start_indices\": [0, 0], \"end_indices\": [4, 4], \"strides\": [1, 1, 1]},\n \"Slice start_indices and strides don't match!\",\n )\n\n error_cases = [\n check_start_indices,\n check_end_indices,\n check_strides,\n check_tensor_dims,\n check_slice_dims_start,\n check_slice_dims_end,\n check_slice_dims_stride,\n ]\n\n for shape, es in itertools.product(cases, error_cases):\n input_tensor = make_arg(shape)\n yield SampleInput(input_tensor, **es.kwargs), es.ex_type, es.ex_str\n\n\ndef squeeze_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # shape, squeeze_dims\n cases = (\n ((5, 1, 1), (1, 2)),\n ((5, 1, 1), (-2, -1)),\n ((5, 1, 1), (2, 1)),\n ((5, 1, 1), (-1, -2)),\n ((1, 5, 1), (0, 2)),\n ((1, 5, 1), (-3, -1)),\n ((1, 1, 5), (0, 1)),\n ((1, 1, 5), (-3, -2)),\n ((5, 5, 5), ()),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.squeeze_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.squeeze_generator#L1396-L1429","kind":"function","name":"squeeze_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1396,"end_line":1429,"context_start_line":1376,"context_end_line":1449,"code":" check_slice_dims_stride = ErrorSample(\n {\"start_indices\": [0, 0], \"end_indices\": [4, 4], \"strides\": [1, 1, 1]},\n \"Slice start_indices and strides don't match!\",\n )\n\n error_cases = [\n check_start_indices,\n check_end_indices,\n check_strides,\n check_tensor_dims,\n check_slice_dims_start,\n check_slice_dims_end,\n check_slice_dims_stride,\n ]\n\n for shape, es in itertools.product(cases, error_cases):\n input_tensor = make_arg(shape)\n yield SampleInput(input_tensor, **es.kwargs), es.ex_type, es.ex_str\n\n\ndef squeeze_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # shape, squeeze_dims\n cases = (\n ((5, 1, 1), (1, 2)),\n ((5, 1, 1), (-2, -1)),\n ((5, 1, 1), (2, 1)),\n ((5, 1, 1), (-1, -2)),\n ((1, 5, 1), (0, 2)),\n ((1, 5, 1), (-3, -1)),\n ((1, 1, 5), (0, 1)),\n ((1, 1, 5), (-3, -2)),\n ((5, 5, 5), ()),\n ((1, 1, 1), ()),\n ((1, 1, 1), (0, 1, 2)),\n ((1, 1, 1), (-3, -2, -1)),\n # No-op test cases\n # NOTE: These are skipped. We diverge from PyTorch behavior for squeeze\n # in nvFuser. Our squeeze op will throw an exception if we pass a\n # squeeze dimension that cannot be squeezed.\n # See https://github.com/NVIDIA/Fuser/pull/1717\n # ((5, 5, 5), (0, 1, 2)),\n # ((5, 5, 5), (-3, -2, -1)),\n ((), ()),\n )\n\n for shape, squeeze_dims in cases:\n a = make_arg(shape)\n yield SampleInput(a, squeeze_dims)\n\n\ndef squeeze_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # shape, start_indices, end_indices\n out_of_range_cases = (\n ((5, 1, 1), (-4, -5)), # Dims are completely outside of tensor dims\n ((5, 1, 1), (3, 4)),\n ((5, 1, 1), (-3, -4)), # One dim in range, one dim out of range\n ((5, 1, 1), (2, 3)),\n )\n\n error_type = RuntimeError\n error_str = \"Squeeze dim is outside of Tensor size!\"\n for shape, squeeze_dims in out_of_range_cases:","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.squeeze_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.squeeze_error_generator#L1432-L1465","kind":"function","name":"squeeze_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1432,"end_line":1465,"context_start_line":1412,"context_end_line":1485,"code":" ((1, 1, 5), (-3, -2)),\n ((5, 5, 5), ()),\n ((1, 1, 1), ()),\n ((1, 1, 1), (0, 1, 2)),\n ((1, 1, 1), (-3, -2, -1)),\n # No-op test cases\n # NOTE: These are skipped. We diverge from PyTorch behavior for squeeze\n # in nvFuser. Our squeeze op will throw an exception if we pass a\n # squeeze dimension that cannot be squeezed.\n # See https://github.com/NVIDIA/Fuser/pull/1717\n # ((5, 5, 5), (0, 1, 2)),\n # ((5, 5, 5), (-3, -2, -1)),\n ((), ()),\n )\n\n for shape, squeeze_dims in cases:\n a = make_arg(shape)\n yield SampleInput(a, squeeze_dims)\n\n\ndef squeeze_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n # shape, start_indices, end_indices\n out_of_range_cases = (\n ((5, 1, 1), (-4, -5)), # Dims are completely outside of tensor dims\n ((5, 1, 1), (3, 4)),\n ((5, 1, 1), (-3, -4)), # One dim in range, one dim out of range\n ((5, 1, 1), (2, 3)),\n )\n\n error_type = RuntimeError\n error_str = \"Squeeze dim is outside of Tensor size!\"\n for shape, squeeze_dims in out_of_range_cases:\n a = make_arg(shape)\n yield SampleInput(a, squeeze_dims), error_type, error_str\n\n # shape, start_indices, end_indices\n too_many_indices_cases = (\n ((5, 1, 1), (1, 2, 3, 4)),\n ((5, 1, 1), (-1, -2, -3, -4)),\n ((), (0,)),\n ((), (-1,)),\n )\n\n error_type = RuntimeError\n error_str = \"The dims to squeeze must be <= the number of dims of the input tensor\"\n for shape, squeeze_dims in too_many_indices_cases:\n a = make_arg(shape)\n yield SampleInput(a, squeeze_dims), error_type, error_str\n\n\ndef take_along_axis_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(\n make_tensor, device=\"cuda\", dtype=torch.long, requires_grad=False\n )\n\n # a.shape, dim, b.shape\n cases = (\n ((4, 2, 3), 0, (8, 2, 3)),\n ((4, 2, 3), 1, (4, 1, 3)),\n ((4, 2, 3), 2, (4, 2, 5)),\n ((4,), 0, (8)),\n ((4,), 0, (1)),\n ((4, 1), 0, (3, 1)),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.take_along_axis_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.take_along_axis_generator#L1468-L1504","kind":"function","name":"take_along_axis_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1468,"end_line":1504,"context_start_line":1448,"context_end_line":1524,"code":" error_str = \"Squeeze dim is outside of Tensor size!\"\n for shape, squeeze_dims in out_of_range_cases:\n a = make_arg(shape)\n yield SampleInput(a, squeeze_dims), error_type, error_str\n\n # shape, start_indices, end_indices\n too_many_indices_cases = (\n ((5, 1, 1), (1, 2, 3, 4)),\n ((5, 1, 1), (-1, -2, -3, -4)),\n ((), (0,)),\n ((), (-1,)),\n )\n\n error_type = RuntimeError\n error_str = \"The dims to squeeze must be <= the number of dims of the input tensor\"\n for shape, squeeze_dims in too_many_indices_cases:\n a = make_arg(shape)\n yield SampleInput(a, squeeze_dims), error_type, error_str\n\n\ndef take_along_axis_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(\n make_tensor, device=\"cuda\", dtype=torch.long, requires_grad=False\n )\n\n # a.shape, dim, b.shape\n cases = (\n ((4, 2, 3), 0, (8, 2, 3)),\n ((4, 2, 3), 1, (4, 1, 3)),\n ((4, 2, 3), 2, (4, 2, 5)),\n ((4,), 0, (8)),\n ((4,), 0, (1)),\n ((4, 1), 0, (3, 1)),\n ((4, 1), 1, (4, 5)),\n # negative dim\n ((4, 2, 3), -3, (8, 2, 3)),\n ((4, 2, 3), -2, (4, 1, 3)),\n ((4, 2, 3), -1, (4, 2, 5)),\n ((4,), -1, (8)),\n ((4,), -1, (1)),\n ((4, 1), -2, (3, 1)),\n ((4, 1), -1, (4, 5)),\n # broadcast non-axis dimensions\n ((4, 2, 3), 0, (8, 2, 1)),\n ((4, 2, 3), 0, (8, 1, 3)),\n ((4, 2, 3), 0, (8, 2, 3)),\n )\n\n for shape_a, dim, shape_b in cases:\n a = make_arg(shape_a)\n b = make_index(shape_b, low=0, high=shape_a[dim])\n yield SampleInput(a, b, dim)\n\n\ndef take_along_axis_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # numpy.take_along_axis(arr: Tensor, indices: LongTensor, axis: int)\n #\n # torch.take_along_dim(input: Tensor, indices: LongTensor, dim: int)\n # * If no dim argument, flatten tensors.\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(\n make_tensor, device=\"cuda\", dtype=torch.long, requires_grad=False\n )\n\n input_shape = (4, 2)\n a = make_arg(input_shape)\n","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.take_along_axis_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.take_along_axis_error_generator#L1507-L1534","kind":"function","name":"take_along_axis_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1507,"end_line":1534,"context_start_line":1487,"context_end_line":1554,"code":" # negative dim\n ((4, 2, 3), -3, (8, 2, 3)),\n ((4, 2, 3), -2, (4, 1, 3)),\n ((4, 2, 3), -1, (4, 2, 5)),\n ((4,), -1, (8)),\n ((4,), -1, (1)),\n ((4, 1), -2, (3, 1)),\n ((4, 1), -1, (4, 5)),\n # broadcast non-axis dimensions\n ((4, 2, 3), 0, (8, 2, 1)),\n ((4, 2, 3), 0, (8, 1, 3)),\n ((4, 2, 3), 0, (8, 2, 3)),\n )\n\n for shape_a, dim, shape_b in cases:\n a = make_arg(shape_a)\n b = make_index(shape_b, low=0, high=shape_a[dim])\n yield SampleInput(a, b, dim)\n\n\ndef take_along_axis_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # numpy.take_along_axis(arr: Tensor, indices: LongTensor, axis: int)\n #\n # torch.take_along_dim(input: Tensor, indices: LongTensor, dim: int)\n # * If no dim argument, flatten tensors.\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n make_index = partial(\n make_tensor, device=\"cuda\", dtype=torch.long, requires_grad=False\n )\n\n input_shape = (4, 2)\n a = make_arg(input_shape)\n\n valid_index_shape = (3, 1)\n b = make_index(valid_index_shape, low=0, high=10, dtype=torch.long)\n\n # out-of-bounds axis error checks\n ex_type = RuntimeError\n ex_str = \"Tensor arguments have dimension\"\n positive_error_dim = 2\n negative_error_dim = -3\n yield SampleInput(a, b, positive_error_dim), ex_type, ex_str\n yield SampleInput(a, b, negative_error_dim), ex_type, ex_str\n\n # TODO Fix: index tensor integer dtype\n # b = make_index(valid_index_shape, low=0, high=input_shape[0], dtype=torch.float)\n # yield SampleInput(a, b, 0), RuntimeError, \"index tensor can only be int or long dtype.\"\n\n # TODO Fix: out-of-bound index value\n # b = make_index(valid_index_shape, low=10, high=100, dtype=torch.long)\n # yield SampleInput(a, b, 0), RuntimeError, \"out of bounds index value.\"\n\n # TODO Fix: index shape exceeds input tensor axis\n # larger_index_shape = (5, 3)\n # b = make_index(\n # larger_index_shape, low=0, high=larger_index_shape[0], dtype=torch.long\n # )\n # yield (\n # SampleInput(a, b, 0),\n # RuntimeError,\n # \"Expected dimension of index tensor to be smaller than input tensor except for specified axis\",\n # )\n","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.var_mean_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.var_mean_generator#L1571-L1585","kind":"function","name":"var_mean_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1571,"end_line":1585,"context_start_line":1551,"context_end_line":1605,"code":" # RuntimeError,\n # \"Expected dimension of index tensor to be smaller than input tensor except for specified axis\",\n # )\n\n # TODO Fix: too many dimensions in index tensor\n # dim argument must be specified. Otherwise, the tensors are flattened.\n # too_many_dims_index_shape = (3, 1, 2)\n # b = make_index(\n # too_many_dims_index_shape,\n # low=0,\n # high=too_many_dims_index_shape[0],\n # dtype=torch.long,\n # )\n # yield (\n # SampleInput(a, b, 0),\n # RuntimeError,\n # \"input and indices should have the same number of dimensions\",\n # )\n\n\ndef var_mean_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"torch.var_mean(input, dim=None, *, correction=1, keepdim=False)\"\"\"\n correction = (0, 1)\n samples = reduction_generator(op, dtype, requires_grad)\n for c, sample in itertools.product(correction, samples):\n a = sample.args[0]\n dim = (\n sample.args[1]\n if (len(sample.args) > 1 and sample.args[1])\n else tuple(range(a.ndim))\n )\n keepdim = sample.args[2] if len(sample.args) > 2 else False\n yield SampleInput(a, dim, correction=c, keepdim=keepdim)\n\n\ndef where_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.where(condition, input, other)\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n input_shape = (2, 3, 4)\n yield SampleInput(\n make_tensor(input_shape, device=\"cuda\", dtype=torch.float32),\n make_arg(input_shape),\n make_arg(input_shape),\n ), RuntimeError, \"Condition should be of DataType Bool\"\n\n\ndef tensor_size_error_generator(","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.where_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.where_error_generator#L1588-L1602","kind":"function","name":"where_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1588,"end_line":1602,"context_start_line":1568,"context_end_line":1622,"code":" # )\n\n\ndef var_mean_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"torch.var_mean(input, dim=None, *, correction=1, keepdim=False)\"\"\"\n correction = (0, 1)\n samples = reduction_generator(op, dtype, requires_grad)\n for c, sample in itertools.product(correction, samples):\n a = sample.args[0]\n dim = (\n sample.args[1]\n if (len(sample.args) > 1 and sample.args[1])\n else tuple(range(a.ndim))\n )\n keepdim = sample.args[2] if len(sample.args) > 2 else False\n yield SampleInput(a, dim, correction=c, keepdim=keepdim)\n\n\ndef where_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.where(condition, input, other)\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n input_shape = (2, 3, 4)\n yield SampleInput(\n make_tensor(input_shape, device=\"cuda\", dtype=torch.float32),\n make_arg(input_shape),\n make_arg(input_shape),\n ), RuntimeError, \"Condition should be of DataType Bool\"\n\n\ndef tensor_size_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n check_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],\n \"dim\": MAX_TENSOR_DIMS,\n },\n RuntimeError,\n \"Tried to access out of boundary index\",\n )\n check_relative_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.tensor_size_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.tensor_size_error_generator#L1605-L1637","kind":"function","name":"tensor_size_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1605,"end_line":1637,"context_start_line":1585,"context_end_line":1657,"code":" yield SampleInput(a, dim, correction=c, keepdim=keepdim)\n\n\ndef where_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.where(condition, input, other)\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n input_shape = (2, 3, 4)\n yield SampleInput(\n make_tensor(input_shape, device=\"cuda\", dtype=torch.float32),\n make_arg(input_shape),\n make_arg(input_shape),\n ), RuntimeError, \"Condition should be of DataType Bool\"\n\n\ndef tensor_size_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n check_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],\n \"dim\": MAX_TENSOR_DIMS,\n },\n RuntimeError,\n \"Tried to access out of boundary index\",\n )\n check_relative_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],\n \"dim\": -MAX_TENSOR_DIMS - 1,\n },\n RuntimeError,\n \"Tried to access out of boundary index\",\n )\n\n error_checks = [\n check_index_beyond_num_dims,\n check_relative_index_beyond_num_dims,\n ]\n\n for error_case, error_type, error_msg in error_checks:\n yield SampleInput(\n make_arg(error_case[\"tensor_shape\"]), dim=error_case[\"dim\"]\n ), error_type, error_msg\n\n\ndef vector_at_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n check_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],\n \"index\": MAX_TENSOR_DIMS,\n },\n RuntimeError,\n \"Tried to access out of boundary index\",\n )\n check_relative_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.vector_at_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.vector_at_error_generator#L1640-L1672","kind":"function","name":"vector_at_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1640,"end_line":1672,"context_start_line":1620,"context_end_line":1692,"code":" check_relative_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],\n \"dim\": -MAX_TENSOR_DIMS - 1,\n },\n RuntimeError,\n \"Tried to access out of boundary index\",\n )\n\n error_checks = [\n check_index_beyond_num_dims,\n check_relative_index_beyond_num_dims,\n ]\n\n for error_case, error_type, error_msg in error_checks:\n yield SampleInput(\n make_arg(error_case[\"tensor_shape\"]), dim=error_case[\"dim\"]\n ), error_type, error_msg\n\n\ndef vector_at_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n check_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],\n \"index\": MAX_TENSOR_DIMS,\n },\n RuntimeError,\n \"Tried to access out of boundary index\",\n )\n check_relative_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],\n \"index\": -MAX_TENSOR_DIMS - 1,\n },\n RuntimeError,\n \"Tried to access out of boundary index\",\n )\n\n error_checks = [\n check_index_beyond_num_dims,\n check_relative_index_beyond_num_dims,\n ]\n\n for error_case, error_type, error_msg in error_checks:\n yield SampleInput(\n make_arg(error_case[\"tensor_shape\"]), index=error_case[\"index\"]\n ), error_type, error_msg\n\n\ndef matmul_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,\n )\n\n B = 4\n M = 256\n N = 128\n K = 32\n\n shapes_a = ((K,), (M, K), (1, K), (B, M, K), (B, 1, M, K))","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.matmul_input_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.matmul_input_generator#L1675-L1696","kind":"function","name":"matmul_input_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1675,"end_line":1696,"context_start_line":1655,"context_end_line":1716,"code":" check_relative_index_beyond_num_dims = (\n {\n \"tensor_shape\": [2 for _ in range(0, MAX_TENSOR_DIMS)],\n \"index\": -MAX_TENSOR_DIMS - 1,\n },\n RuntimeError,\n \"Tried to access out of boundary index\",\n )\n\n error_checks = [\n check_index_beyond_num_dims,\n check_relative_index_beyond_num_dims,\n ]\n\n for error_case, error_type, error_msg in error_checks:\n yield SampleInput(\n make_arg(error_case[\"tensor_shape\"]), index=error_case[\"index\"]\n ), error_type, error_msg\n\n\ndef matmul_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,\n )\n\n B = 4\n M = 256\n N = 128\n K = 32\n\n shapes_a = ((K,), (M, K), (1, K), (B, M, K), (B, 1, M, K))\n shapes_b = ((K,), (K, N), (K, 1), (B, K, N))\n\n for shape_a, shape_b in itertools.product(shapes_a, shapes_b):\n yield SampleInput(make_arg(shape_a), make_arg(shape_b))\n\n\ndef linear_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,\n )\n\n B = 64\n M = 512\n N = 256\n K = 32\n\n # Cases without bias","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.linear_input_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.linear_input_generator#L1699-L1728","kind":"function","name":"linear_input_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1699,"end_line":1728,"context_start_line":1679,"context_end_line":1748,"code":" make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,\n )\n\n B = 4\n M = 256\n N = 128\n K = 32\n\n shapes_a = ((K,), (M, K), (1, K), (B, M, K), (B, 1, M, K))\n shapes_b = ((K,), (K, N), (K, 1), (B, K, N))\n\n for shape_a, shape_b in itertools.product(shapes_a, shapes_b):\n yield SampleInput(make_arg(shape_a), make_arg(shape_b))\n\n\ndef linear_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,\n )\n\n B = 64\n M = 512\n N = 256\n K = 32\n\n # Cases without bias\n shapes_input = ((K), (M, K), (B, M, K), (B, 1, M, K))\n shapes_weight = ((N, K), (1, K))\n for shape_input, shape_weight in itertools.product(shapes_input, shapes_weight):\n yield SampleInput(make_arg(shape_input), make_arg(shape_weight))\n\n # Cases with bias\n shape_weight = (N, K)\n shapes_bias = ((N,),)\n for shape_input, shape_bias in itertools.product(shapes_input, shapes_bias):\n yield SampleInput(\n make_arg(shape_input), make_arg(shape_weight), make_arg(shape_bias)\n )\n\n\ndef linear_error_generator(\n op, dtype=torch.float32, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n # shapes, dim, exception type, exception string\n M = 512\n N = 256\n K = 32\n\n mismatched_bias_extent = (\n ((M, K), (1, K), (N)),\n RuntimeError,\n f\"The expanded size of the tensor (1) must match the existing size ({N}) at non-singleton dimension 1. Target sizes: [{M}, 1]. Tensor sizes: [{N}]\",\n )\n\n error_cases = [mismatched_bias_extent]","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.linear_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.linear_error_generator#L1731-L1754","kind":"function","name":"linear_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1731,"end_line":1754,"context_start_line":1711,"context_end_line":1774,"code":" B = 64\n M = 512\n N = 256\n K = 32\n\n # Cases without bias\n shapes_input = ((K), (M, K), (B, M, K), (B, 1, M, K))\n shapes_weight = ((N, K), (1, K))\n for shape_input, shape_weight in itertools.product(shapes_input, shapes_weight):\n yield SampleInput(make_arg(shape_input), make_arg(shape_weight))\n\n # Cases with bias\n shape_weight = (N, K)\n shapes_bias = ((N,),)\n for shape_input, shape_bias in itertools.product(shapes_input, shapes_bias):\n yield SampleInput(\n make_arg(shape_input), make_arg(shape_weight), make_arg(shape_bias)\n )\n\n\ndef linear_error_generator(\n op, dtype=torch.float32, requires_grad: bool = False, **kwargs\n):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n # shapes, dim, exception type, exception string\n M = 512\n N = 256\n K = 32\n\n mismatched_bias_extent = (\n ((M, K), (1, K), (N)),\n RuntimeError,\n f\"The expanded size of the tensor (1) must match the existing size ({N}) at non-singleton dimension 1. Target sizes: [{M}, 1]. Tensor sizes: [{N}]\",\n )\n\n error_cases = [mismatched_bias_extent]\n\n for input_shapes, ex_type, ex_str in error_cases:\n shape_input, shape_weight, shape_bias = input_shapes\n yield SampleInput(\n make_arg(shape_input), make_arg(shape_weight), make_arg(shape_bias)\n ), ex_type, ex_str\n\n\ndef div_input_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n):\n \"\"\"Rescale to avoid very small denominators\"\"\"\n for sample in elementwise_binary_generator(\n op,\n dtype,\n requires_grad,\n supports_numbers=True,\n enable_small_value_testing=False,\n enable_extremal_value_testing=False,\n exclude_zero=True,\n ):\n if not is_floating_dtype(dtype):\n yield sample\n continue","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.div_input_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.div_input_generator#L1757-L1785","kind":"function","name":"div_input_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1757,"end_line":1785,"context_start_line":1737,"context_end_line":1805,"code":" # shapes, dim, exception type, exception string\n M = 512\n N = 256\n K = 32\n\n mismatched_bias_extent = (\n ((M, K), (1, K), (N)),\n RuntimeError,\n f\"The expanded size of the tensor (1) must match the existing size ({N}) at non-singleton dimension 1. Target sizes: [{M}, 1]. Tensor sizes: [{N}]\",\n )\n\n error_cases = [mismatched_bias_extent]\n\n for input_shapes, ex_type, ex_str in error_cases:\n shape_input, shape_weight, shape_bias = input_shapes\n yield SampleInput(\n make_arg(shape_input), make_arg(shape_weight), make_arg(shape_bias)\n ), ex_type, ex_str\n\n\ndef div_input_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n):\n \"\"\"Rescale to avoid very small denominators\"\"\"\n for sample in elementwise_binary_generator(\n op,\n dtype,\n requires_grad,\n supports_numbers=True,\n enable_small_value_testing=False,\n enable_extremal_value_testing=False,\n exclude_zero=True,\n ):\n if not is_floating_dtype(dtype):\n yield sample\n continue\n\n # rescale so that the denominator always has at least this modulus\n minabs = 1e-2\n numer, denom = sample.args\n denom = denom * 1e-4\n denom_abs = denom.abs() # this is never zero because of exclude_zero=True\n denom_is_small = denom_abs < minabs\n denom_scaled_to_minabs = denom * (minabs / denom_abs)\n denom = torch.where(denom_is_small, denom_scaled_to_minabs, denom).detach()\n denom.requires_grad_(requires_grad)\n yield SampleInput(numer, denom)\n\n\ndef triu_input_generator(op: OpInfo, dtype: torch.dtype, requires_grad: bool = False):\n offsets = (0, 1, -1, 2, 3, -3, 1024, -1024)\n\n for element in elementwise_unary_generator(\n op,\n dtype,\n requires_grad,\n enable_extremal_value_testing=False,\n enable_large_value_testing=False,\n enable_small_value_testing=False,\n ):\n if element.args[0].ndim < 2:\n continue\n # to test cases where offset is not passed as an argument\n yield element\n # to test cases where offset is passed as an argument\n for offset in offsets:\n yield SampleInput(*element.args, offset)","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.triu_input_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.triu_input_generator#L1788-L1805","kind":"function","name":"triu_input_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1788,"end_line":1805,"context_start_line":1768,"context_end_line":1825,"code":" enable_small_value_testing=False,\n enable_extremal_value_testing=False,\n exclude_zero=True,\n ):\n if not is_floating_dtype(dtype):\n yield sample\n continue\n\n # rescale so that the denominator always has at least this modulus\n minabs = 1e-2\n numer, denom = sample.args\n denom = denom * 1e-4\n denom_abs = denom.abs() # this is never zero because of exclude_zero=True\n denom_is_small = denom_abs < minabs\n denom_scaled_to_minabs = denom * (minabs / denom_abs)\n denom = torch.where(denom_is_small, denom_scaled_to_minabs, denom).detach()\n denom.requires_grad_(requires_grad)\n yield SampleInput(numer, denom)\n\n\ndef triu_input_generator(op: OpInfo, dtype: torch.dtype, requires_grad: bool = False):\n offsets = (0, 1, -1, 2, 3, -3, 1024, -1024)\n\n for element in elementwise_unary_generator(\n op,\n dtype,\n requires_grad,\n enable_extremal_value_testing=False,\n enable_large_value_testing=False,\n enable_small_value_testing=False,\n ):\n if element.args[0].ndim < 2:\n continue\n # to test cases where offset is not passed as an argument\n yield element\n # to test cases where offset is passed as an argument\n for offset in offsets:\n yield SampleInput(*element.args, offset)\n\n\ndef triu_error_generator(op: OpInfo, dtype: torch.dtype, requires_grad: bool = False):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n invalid_shapes = (\n (),\n (4,),\n )\n\n for shape in invalid_shapes:\n yield SampleInput(\n make_arg(shape),\n ), RuntimeError, f\"input tensor for triu must have 2 or more dims, but got {len(shape)} dims\"\n\n\ndef cumsum_input_generator(op: OpInfo, dtype: torch.dtype, requires_grad: bool = False):\n make_arg = partial(","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.triu_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.triu_error_generator#L1808-L1821","kind":"function","name":"triu_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1808,"end_line":1821,"context_start_line":1788,"context_end_line":1841,"code":"def triu_input_generator(op: OpInfo, dtype: torch.dtype, requires_grad: bool = False):\n offsets = (0, 1, -1, 2, 3, -3, 1024, -1024)\n\n for element in elementwise_unary_generator(\n op,\n dtype,\n requires_grad,\n enable_extremal_value_testing=False,\n enable_large_value_testing=False,\n enable_small_value_testing=False,\n ):\n if element.args[0].ndim < 2:\n continue\n # to test cases where offset is not passed as an argument\n yield element\n # to test cases where offset is passed as an argument\n for offset in offsets:\n yield SampleInput(*element.args, offset)\n\n\ndef triu_error_generator(op: OpInfo, dtype: torch.dtype, requires_grad: bool = False):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n invalid_shapes = (\n (),\n (4,),\n )\n\n for shape in invalid_shapes:\n yield SampleInput(\n make_arg(shape),\n ), RuntimeError, f\"input tensor for triu must have 2 or more dims, but got {len(shape)} dims\"\n\n\ndef cumsum_input_generator(op: OpInfo, dtype: torch.dtype, requires_grad: bool = False):\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n low=-2,\n high=3,\n )\n\n # shape, dim\n cases = (\n ((4, 4), 0),\n ((5,), 0),\n ((8, 1, 6), 1),\n ((8, 7, 5, 1), 2),\n ((8, 7, 5, 1), -1),\n ((8, 7, 5, 1), -2),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.cumsum_input_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.cumsum_input_generator#L1824-L1845","kind":"function","name":"cumsum_input_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1824,"end_line":1845,"context_start_line":1804,"context_end_line":1865,"code":" for offset in offsets:\n yield SampleInput(*element.args, offset)\n\n\ndef triu_error_generator(op: OpInfo, dtype: torch.dtype, requires_grad: bool = False):\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n invalid_shapes = (\n (),\n (4,),\n )\n\n for shape in invalid_shapes:\n yield SampleInput(\n make_arg(shape),\n ), RuntimeError, f\"input tensor for triu must have 2 or more dims, but got {len(shape)} dims\"\n\n\ndef cumsum_input_generator(op: OpInfo, dtype: torch.dtype, requires_grad: bool = False):\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n low=-2,\n high=3,\n )\n\n # shape, dim\n cases = (\n ((4, 4), 0),\n ((5,), 0),\n ((8, 1, 6), 1),\n ((8, 7, 5, 1), 2),\n ((8, 7, 5, 1), -1),\n ((8, 7, 5, 1), -2),\n )\n\n for shape, dim in cases:\n yield SampleInput(make_arg(shape), dim)\n\n\ndef cumsum_error_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n):\n \"\"\"\n Generate test cases that should produce errors for cumsum operation.\n\n Yields:\n Tuples of (SampleInput, expected_exception_type, error_message_pattern)\n \"\"\"\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n low=-2,\n high=3,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.cumsum_error_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.cumsum_error_generator#L1848-L1887","kind":"function","name":"cumsum_error_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1848,"end_line":1887,"context_start_line":1828,"context_end_line":1907,"code":" dtype=dtype,\n requires_grad=requires_grad,\n low=-2,\n high=3,\n )\n\n # shape, dim\n cases = (\n ((4, 4), 0),\n ((5,), 0),\n ((8, 1, 6), 1),\n ((8, 7, 5, 1), 2),\n ((8, 7, 5, 1), -1),\n ((8, 7, 5, 1), -2),\n )\n\n for shape, dim in cases:\n yield SampleInput(make_arg(shape), dim)\n\n\ndef cumsum_error_generator(\n op: OpInfo,\n dtype: torch.dtype,\n requires_grad: bool = False,\n):\n \"\"\"\n Generate test cases that should produce errors for cumsum operation.\n\n Yields:\n Tuples of (SampleInput, expected_exception_type, error_message_pattern)\n \"\"\"\n make_arg = partial(\n make_tensor,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n low=-2,\n high=3,\n )\n\n # Invalid dimension: out of bounds positive\n input_shape = (4, 4)\n yield SampleInput(\n make_arg(input_shape), 2\n ), RuntimeError, \"Tried to access out of boundary index\"\n\n # Invalid dimension: out of bounds negative\n yield SampleInput(\n make_arg(input_shape), -3\n ), RuntimeError, \"Tried to access out of boundary index\"\n\n # Invalid dimension type: float instead of int\n yield SampleInput(\n make_arg(input_shape), 0.5\n ), TypeError, \"cumsum(): incompatible function arguments\"\n\n # Invalid input: 0-dim tensor (scalar)\n yield SampleInput(\n make_arg(()), 0\n ), RuntimeError, \"Tried to access out of boundary index 0. total index: 0\"\n\n\ndef grouped_mm_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate valid test cases for grouped matrix multiplication.\n\n Args:\n op: OpInfo object for the bmm operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n \"\"\"\n make_arg = partial(\n make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.grouped_mm_input_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.grouped_mm_input_generator#L1890-L1945","kind":"function","name":"grouped_mm_input_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1890,"end_line":1945,"context_start_line":1870,"context_end_line":1965,"code":" yield SampleInput(\n make_arg(input_shape), 2\n ), RuntimeError, \"Tried to access out of boundary index\"\n\n # Invalid dimension: out of bounds negative\n yield SampleInput(\n make_arg(input_shape), -3\n ), RuntimeError, \"Tried to access out of boundary index\"\n\n # Invalid dimension type: float instead of int\n yield SampleInput(\n make_arg(input_shape), 0.5\n ), TypeError, \"cumsum(): incompatible function arguments\"\n\n # Invalid input: 0-dim tensor (scalar)\n yield SampleInput(\n make_arg(()), 0\n ), RuntimeError, \"Tried to access out of boundary index 0. total index: 0\"\n\n\ndef grouped_mm_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate valid test cases for grouped matrix multiplication.\n\n Args:\n op: OpInfo object for the bmm operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n \"\"\"\n make_arg = partial(\n make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,\n )\n\n def make_index(extent, num_groups):\n group_size = extent // num_groups\n return torch.arange(\n group_size,\n group_size * g + 1,\n group_size,\n device=\"cuda\",\n dtype=torch.int32,\n requires_grad=False,\n )\n\n # TODO: expand the test when kernel restrictions are lifted\n # Test various group sizes and matrix dimensions\n configs = (\n (4, 128, 256, 64),\n (2, 32, 32, 32),\n )\n\n for config in configs:\n g, m, k, n = config\n\n # case 1: 2d x 2d\n mat1 = make_arg((m, k))\n mat2 = make_arg((k, n))\n offsets = make_index(k, g)\n yield SampleInput(mat1, mat2, offsets)\n # case 3: 2d x 3d\n mat1 = make_arg((m, k))\n mat2 = make_arg((g, k, n))\n offsets = make_index(m, g)\n yield SampleInput(mat1, mat2, offsets)\n # case 1: 3d x 2d\n mat1 = make_arg((g, m, k))\n mat2 = make_arg((k, n))\n offsets = make_index(n, g)\n yield SampleInput(mat1, mat2, offsets)\n\n\ndef scaled_grouped_mm_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate valid test cases for scaled grouped matrix multiplication.\n\n Args:\n op: OpInfo object for the bmm operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n \"\"\"\n\n # TODO: enable mxfp8 test when backend supports it.\n make_arg = partial(\n make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.scaled_grouped_mm_input_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.scaled_grouped_mm_input_generator#L1948-L2023","kind":"function","name":"scaled_grouped_mm_input_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1948,"end_line":2023,"context_start_line":1928,"context_end_line":2043,"code":" for config in configs:\n g, m, k, n = config\n\n # case 1: 2d x 2d\n mat1 = make_arg((m, k))\n mat2 = make_arg((k, n))\n offsets = make_index(k, g)\n yield SampleInput(mat1, mat2, offsets)\n # case 3: 2d x 3d\n mat1 = make_arg((m, k))\n mat2 = make_arg((g, k, n))\n offsets = make_index(m, g)\n yield SampleInput(mat1, mat2, offsets)\n # case 1: 3d x 2d\n mat1 = make_arg((g, m, k))\n mat2 = make_arg((k, n))\n offsets = make_index(n, g)\n yield SampleInput(mat1, mat2, offsets)\n\n\ndef scaled_grouped_mm_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate valid test cases for scaled grouped matrix multiplication.\n\n Args:\n op: OpInfo object for the bmm operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n \"\"\"\n\n # TODO: enable mxfp8 test when backend supports it.\n make_arg = partial(\n make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,\n )\n\n make_scale_factor = partial(\n make_tensor,\n dtype=torch.float32,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=False,\n )\n\n def make_index(extent, num_groups):\n group_size = extent // num_groups\n return torch.arange(\n group_size,\n group_size * g + 1,\n group_size,\n device=\"cuda\",\n dtype=torch.int32,\n requires_grad=False,\n )\n\n # TODO: expand the test when fallback kernel restrictions are lifted\n # currently only bf16 output is supported.\n # there are also restrictions on the input/output shapes.\n # Test various group sizes and matrix dimensions\n # configs: list(g, m, k, n, output_dtype)\n configs = (\n (4, 128, 256, 64, torch.bfloat16),\n (2, 32, 32, 32, torch.bfloat16),\n )\n\n # TODO: Enable mxfp8 test when backend supports it.\n for config in configs:\n g, m, k, n, dtype = config\n # case 1: 2d x 2d\n mat1 = make_arg((m, k))\n mat2 = make_arg((k, n))\n scale1 = make_scale_factor((g, m, 1))\n scale2 = make_scale_factor((g, 1, n))\n offsets = make_index(k, g)\n yield SampleInput(mat1, mat2, offsets, scale1, scale2, None, None, None, dtype)\n # case 3: 2d x 3d\n mat1 = make_arg((m, k))\n mat2 = make_arg((g, k, n))\n scale1 = make_scale_factor((m, 1))\n scale2 = make_scale_factor((g, 1, n))\n offsets = make_index(m, g)\n yield SampleInput(mat1, mat2, offsets, scale1, scale2, None, None, None, dtype)\n # case 1: 3d x 2d\n mat1 = make_arg((g, m, k))\n mat2 = make_arg((k, n))\n offsets = make_index(n, g)\n scale1 = make_scale_factor((g, m, 1))\n scale2 = make_scale_factor((1, n))\n yield SampleInput(mat1, mat2, offsets, scale1, scale2, None, None, None, dtype)\n\n\n###############################################################################\n#\n# NOTE: quantization taken from torch testing. Since this is using aten backend\n#\n###############################################################################\n# largest power of 2 representable in `torch.float8_e4m3fn`\nF8E4M3_LARGEST_POW2 = 8\n# max value of `torch.float8_e4m3fn` (448)\nF8E4M3_MAX_VAL = torch.finfo(torch.float8_e4m3fn).max\n# exponent bias of `torch.float8_e8m0fnu`\nF8E8M0_EXP_BIAS = 127\n\n\ndef data_to_mxfp8_scale(x, block_size):\n # simple implementation of https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf\n # section 6.3, not all edge cases (such as NaN) are handled/tested\n orig_shape = x.shape\n x = x.reshape(-1, block_size)","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.data_to_mxfp8_scale","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.data_to_mxfp8_scale#L2039-L2053","kind":"function","name":"data_to_mxfp8_scale","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":2039,"end_line":2053,"context_start_line":2019,"context_end_line":2073,"code":" mat2 = make_arg((k, n))\n offsets = make_index(n, g)\n scale1 = make_scale_factor((g, m, 1))\n scale2 = make_scale_factor((1, n))\n yield SampleInput(mat1, mat2, offsets, scale1, scale2, None, None, None, dtype)\n\n\n###############################################################################\n#\n# NOTE: quantization taken from torch testing. Since this is using aten backend\n#\n###############################################################################\n# largest power of 2 representable in `torch.float8_e4m3fn`\nF8E4M3_LARGEST_POW2 = 8\n# max value of `torch.float8_e4m3fn` (448)\nF8E4M3_MAX_VAL = torch.finfo(torch.float8_e4m3fn).max\n# exponent bias of `torch.float8_e8m0fnu`\nF8E8M0_EXP_BIAS = 127\n\n\ndef data_to_mxfp8_scale(x, block_size):\n # simple implementation of https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf\n # section 6.3, not all edge cases (such as NaN) are handled/tested\n orig_shape = x.shape\n x = x.reshape(-1, block_size)\n max_abs = torch.amax(torch.abs(x), 1)\n largest_p2_lt_max_abs = torch.floor(torch.log2(max_abs))\n scale_e8m0_unbiased = largest_p2_lt_max_abs - F8E4M3_LARGEST_POW2\n scale_e8m0_unbiased = torch.clamp(\n scale_e8m0_unbiased, -1 * F8E8M0_EXP_BIAS, F8E8M0_EXP_BIAS\n )\n scale_e8m0_biased = scale_e8m0_unbiased + F8E8M0_EXP_BIAS\n scale_e8m0_biased = scale_e8m0_biased.to(torch.uint8)\n scale_e8m0_biased = scale_e8m0_biased.view(torch.float8_e8m0fnu)\n return scale_e8m0_biased.reshape(orig_shape[0], -1)\n\n\ndef data_to_mxfp8(x, block_size):\n x_scale = data_to_mxfp8_scale(x, block_size)\n K = x.shape[1]\n max_val = F8E4M3_MAX_VAL\n min_val = -1 * max_val\n x = (x.reshape(-1, block_size) / x_scale.reshape(-1, 1).float()).reshape(-1, K)\n x = x.clamp(min=min_val, max=max_val).to(torch.float8_e4m3fn)\n return x, x_scale\n\n\ndef scaled_mm_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate valid test cases for scaled matrix multiplication.\n\n Args:\n op: OpInfo object for the bmm operation","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.data_to_mxfp8","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.data_to_mxfp8#L2056-L2063","kind":"function","name":"data_to_mxfp8","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":2056,"end_line":2063,"context_start_line":2036,"context_end_line":2083,"code":"F8E8M0_EXP_BIAS = 127\n\n\ndef data_to_mxfp8_scale(x, block_size):\n # simple implementation of https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf\n # section 6.3, not all edge cases (such as NaN) are handled/tested\n orig_shape = x.shape\n x = x.reshape(-1, block_size)\n max_abs = torch.amax(torch.abs(x), 1)\n largest_p2_lt_max_abs = torch.floor(torch.log2(max_abs))\n scale_e8m0_unbiased = largest_p2_lt_max_abs - F8E4M3_LARGEST_POW2\n scale_e8m0_unbiased = torch.clamp(\n scale_e8m0_unbiased, -1 * F8E8M0_EXP_BIAS, F8E8M0_EXP_BIAS\n )\n scale_e8m0_biased = scale_e8m0_unbiased + F8E8M0_EXP_BIAS\n scale_e8m0_biased = scale_e8m0_biased.to(torch.uint8)\n scale_e8m0_biased = scale_e8m0_biased.view(torch.float8_e8m0fnu)\n return scale_e8m0_biased.reshape(orig_shape[0], -1)\n\n\ndef data_to_mxfp8(x, block_size):\n x_scale = data_to_mxfp8_scale(x, block_size)\n K = x.shape[1]\n max_val = F8E4M3_MAX_VAL\n min_val = -1 * max_val\n x = (x.reshape(-1, block_size) / x_scale.reshape(-1, 1).float()).reshape(-1, K)\n x = x.clamp(min=min_val, max=max_val).to(torch.float8_e4m3fn)\n return x, x_scale\n\n\ndef scaled_mm_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate valid test cases for scaled matrix multiplication.\n\n Args:\n op: OpInfo object for the bmm operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n \"\"\"\n\n # TODO: enable mxfp8 test when backend supports it.\n make_arg = partial(\n make_tensor,\n dtype=torch.float32,\n device=\"cuda\",\n low=None,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.scaled_mm_input_generator","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.scaled_mm_input_generator#L2066-L2108","kind":"function","name":"scaled_mm_input_generator","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":2066,"end_line":2108,"context_start_line":2046,"context_end_line":2108,"code":" scale_e8m0_unbiased = largest_p2_lt_max_abs - F8E4M3_LARGEST_POW2\n scale_e8m0_unbiased = torch.clamp(\n scale_e8m0_unbiased, -1 * F8E8M0_EXP_BIAS, F8E8M0_EXP_BIAS\n )\n scale_e8m0_biased = scale_e8m0_unbiased + F8E8M0_EXP_BIAS\n scale_e8m0_biased = scale_e8m0_biased.to(torch.uint8)\n scale_e8m0_biased = scale_e8m0_biased.view(torch.float8_e8m0fnu)\n return scale_e8m0_biased.reshape(orig_shape[0], -1)\n\n\ndef data_to_mxfp8(x, block_size):\n x_scale = data_to_mxfp8_scale(x, block_size)\n K = x.shape[1]\n max_val = F8E4M3_MAX_VAL\n min_val = -1 * max_val\n x = (x.reshape(-1, block_size) / x_scale.reshape(-1, 1).float()).reshape(-1, K)\n x = x.clamp(min=min_val, max=max_val).to(torch.float8_e4m3fn)\n return x, x_scale\n\n\ndef scaled_mm_input_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n \"\"\"\n Generate valid test cases for scaled matrix multiplication.\n\n Args:\n op: OpInfo object for the bmm operation\n dtype: Data type for test tensors\n requires_grad: Whether tensors should require gradients\n \"\"\"\n\n # TODO: enable mxfp8 test when backend supports it.\n make_arg = partial(\n make_tensor,\n dtype=torch.float32,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,\n )\n\n # TODO: expand the test when fallback kernel restrictions are lifted\n # currently only bf16 output is supported.\n # there are also restrictions on the input/output shapes.\n # Test various group sizes and matrix dimensions\n # configs: list(m, k, n, output_dtype)\n configs = (\n (128, 256, 512, torch.bfloat16),\n (128, 128, 128, torch.bfloat16),\n )\n\n # TODO: support nvfp4\n assert dtype == torch.float8_e4m3fn\n quantization = partial(data_to_mxfp8, block_size=32)\n\n for config in configs:\n m, k, n, dtype = config\n mat1_ref = make_arg((m, k))\n mat2_ref = make_arg((n, k))\n mat1, scale1 = quantization(mat1_ref)\n mat2, scale2 = quantization(mat2_ref)\n yield SampleInput(mat1, mat2.t(), scale1, scale2, None, None, None, dtype)","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._filter_lhs_domain","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._filter_lhs_domain#L551-L552","kind":"function","name":"_filter_lhs_domain","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":551,"end_line":552,"context_start_line":531,"context_end_line":572,"code":" ((1,), ()),\n ((2,), ()),\n ((1,), (2,)),\n ((2, 1), (2,)),\n ((1, 2), (2,)),\n ((3, 2), (2,)),\n ((1, 3, 2), (2,)),\n ((1, 3, 2), (3, 2)),\n ((3, 1, 2), (3, 2)),\n ((2, 3, 2), ()),\n ((3, 1, 2), (1, 3, 2)),\n )\n for lhs_shape, rhs_shape in broadcast_shapes:\n yield SampleInput(make_arg(lhs_shape), make_arg(rhs_shape))\n yield SampleInput(\n make_arg(lhs_shape, noncontiguous=True),\n make_arg(rhs_shape, noncontiguous=True),\n )\n\n # Create filtered special inputs for this operation's domain\n def _filter_lhs_domain(values):\n return [v for v in values if is_within_domain(op.domain, v)]\n\n def _filter_rhs_domain(values):\n # NOTE: Check exclude_zero flag to avoid undefined behavior such as ZeroDivisionError: division by zero\n exclude_zero = kwargs.get(\"exclude_zero\", False)\n return [v for v in values if is_within_domain(op.domain, v, exclude_zero)]\n\n if (\n enable_large_value_testing\n and dtype != torch.bool\n and dtype not in complex_dtypes\n ):\n lhs_large_values = _filter_lhs_domain(_large_values(dtype))\n rhs_large_values = _filter_rhs_domain(_large_values(dtype))\n yield _special_value_binary_generator(\n lhs_large_values, rhs_large_values, dtype, requires_grad\n )\n\n if enable_small_value_testing and dtype != torch.bool:\n lhs_small_values = _filter_lhs_domain(_small_values(dtype))\n rhs_small_values = _filter_rhs_domain(_small_values(dtype))","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._filter_rhs_domain","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._filter_rhs_domain#L554-L557","kind":"function","name":"_filter_rhs_domain","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":554,"end_line":557,"context_start_line":534,"context_end_line":577,"code":" ((2, 1), (2,)),\n ((1, 2), (2,)),\n ((3, 2), (2,)),\n ((1, 3, 2), (2,)),\n ((1, 3, 2), (3, 2)),\n ((3, 1, 2), (3, 2)),\n ((2, 3, 2), ()),\n ((3, 1, 2), (1, 3, 2)),\n )\n for lhs_shape, rhs_shape in broadcast_shapes:\n yield SampleInput(make_arg(lhs_shape), make_arg(rhs_shape))\n yield SampleInput(\n make_arg(lhs_shape, noncontiguous=True),\n make_arg(rhs_shape, noncontiguous=True),\n )\n\n # Create filtered special inputs for this operation's domain\n def _filter_lhs_domain(values):\n return [v for v in values if is_within_domain(op.domain, v)]\n\n def _filter_rhs_domain(values):\n # NOTE: Check exclude_zero flag to avoid undefined behavior such as ZeroDivisionError: division by zero\n exclude_zero = kwargs.get(\"exclude_zero\", False)\n return [v for v in values if is_within_domain(op.domain, v, exclude_zero)]\n\n if (\n enable_large_value_testing\n and dtype != torch.bool\n and dtype not in complex_dtypes\n ):\n lhs_large_values = _filter_lhs_domain(_large_values(dtype))\n rhs_large_values = _filter_rhs_domain(_large_values(dtype))\n yield _special_value_binary_generator(\n lhs_large_values, rhs_large_values, dtype, requires_grad\n )\n\n if enable_small_value_testing and dtype != torch.bool:\n lhs_small_values = _filter_lhs_domain(_small_values(dtype))\n rhs_small_values = _filter_rhs_domain(_small_values(dtype))\n yield _special_value_binary_generator(\n lhs_small_values, rhs_small_values, dtype, requires_grad\n )\n\n if enable_extremal_value_testing and dtype in float_complex_dtypes:","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._fn","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._fn#L690-L693","kind":"function","name":"_fn","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":690,"end_line":693,"context_start_line":670,"context_end_line":713,"code":" device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n )\n )\n\n if enable_extremal_value_testing and dtype in float_complex_dtypes:\n filtered_extremal_values = _filter_domain(_extremal_values(dtype))\n yield SampleInput(\n torch.tensor(\n filtered_extremal_values,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n )\n )\n\n\ndef _elementwise_unary_torch(op):\n @wraps(op)\n def _fn(x):\n if isinstance(x, torch.Tensor):\n return op(x)\n return op(torch.tensor(x)).item()\n\n return _fn\n\n\ndef full_error_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.full(size, fill_value, dtype=None)\n # Error: Trying to create tensor with negative dimension\n negative_input_shape = [2, -2]\n yield SampleInput(\n negative_input_shape, make_number(dtype), dtype\n ), RuntimeError, \"The value -2 at index 1 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1).\"\n\n\ndef scatter_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.scatter(input: Tensor, dim: int, index: LongTensor, src: LongTensor)\n # * input, index and src tensors have same ndims.","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators._filter_domain","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators._filter_domain#L647-L648","kind":"function","name":"_filter_domain","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":647,"end_line":648,"context_start_line":627,"context_end_line":668,"code":" requires_grad=requires_grad,\n **kwargs,\n )\n\n shapes = (\n (0, 2, 1),\n (5, 0, 3),\n (),\n (11,),\n (4, 4),\n (1024, 1024),\n (64, 64, 64),\n )\n\n # Typical inputs\n for shape in shapes:\n yield SampleInput(make_arg(shape))\n yield SampleInput(make_arg(shape, noncontiguous=True))\n\n # Create filtered special inputs for this operation's domain\n def _filter_domain(values):\n return [v for v in values if is_within_domain(op.domain, v)]\n\n if (\n enable_large_value_testing\n and dtype != torch.bool\n and dtype not in complex_dtypes\n ):\n filtered_large_values = _filter_domain(_large_values(dtype))\n yield SampleInput(\n torch.tensor(\n filtered_large_values,\n device=\"cuda\",\n dtype=dtype,\n requires_grad=requires_grad,\n )\n )\n\n if enable_small_value_testing and dtype != torch.bool:\n filtered_small_values = _filter_domain(_small_values(dtype))\n yield SampleInput(\n torch.tensor(","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.make_unique_index","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.make_unique_index#L722-L727","kind":"function","name":"make_unique_index","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":722,"end_line":727,"context_start_line":702,"context_end_line":747,"code":" # Error: Trying to create tensor with negative dimension\n negative_input_shape = [2, -2]\n yield SampleInput(\n negative_input_shape, make_number(dtype), dtype\n ), RuntimeError, \"The value -2 at index 1 was neither symbolic(-1), zero_element(0), broadcast(1), or static(>1).\"\n\n\ndef scatter_generator(\n op: OpInfo, dtype: torch.dtype, requires_grad: bool = False, **kwargs\n):\n # torch.scatter(input: Tensor, dim: int, index: LongTensor, src: LongTensor)\n # * input, index and src tensors have same ndims.\n # * index tensors must be <= input tensor along all dims.\n # * index tensors must be == src tensor along all dims.\n # * index tensors must have unique value across specified axis.\n\n make_arg = partial(\n make_tensor, device=\"cuda\", dtype=dtype, requires_grad=requires_grad\n )\n\n def make_unique_index(shape_b, dim, extent):\n logits_shape = list(shape_b)\n logits_shape[dim] = extent\n logits = make_tensor(logits_shape, device=\"cuda\", dtype=torch.float)\n # return index tensor with unique entry\n return logits.argsort(dim).narrow(dim, 0, shape_b[dim])\n\n make_index = partial(\n make_tensor, device=\"cuda\", dtype=torch.long, requires_grad=False\n )\n\n # a.shape, dim, b.shape\n cases = (\n ((8, 2, 3), 0, (8, 2, 3)),\n ((8, 2, 3), 1, (8, 2, 3)),\n ((8, 2, 3), 2, (8, 2, 3)),\n # TODO: enable the test below when we fix mapping for scatter.\n # scatter supporting unmatched scatter dim\n # ((8, 2, 3), 0, (4, 2, 3)),\n # ((8, 2, 3), 1, (8, 1, 3)),\n # ((8, 2, 3), 2, (8, 2, 2)),\n # ((8,), 0, (8)),\n # ((8,), 0, (4)),\n # ((8,), 0, (1)),\n # ((8, 2, 3), -3, (4, 2, 3)),\n # ((8, 2, 3), -2, (8, 1, 3)),","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_input_generators.make_index","uri":"program://Fuser/function/tests.python.opinfo.opinfo_input_generators.make_index#L1979-L1988","kind":"function","name":"make_index","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1979,"end_line":1988,"context_start_line":1959,"context_end_line":2008,"code":"\n # TODO: enable mxfp8 test when backend supports it.\n make_arg = partial(\n make_tensor,\n dtype=dtype,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=requires_grad,\n )\n\n make_scale_factor = partial(\n make_tensor,\n dtype=torch.float32,\n device=\"cuda\",\n low=None,\n high=None,\n requires_grad=False,\n )\n\n def make_index(extent, num_groups):\n group_size = extent // num_groups\n return torch.arange(\n group_size,\n group_size * g + 1,\n group_size,\n device=\"cuda\",\n dtype=torch.int32,\n requires_grad=False,\n )\n\n # TODO: expand the test when fallback kernel restrictions are lifted\n # currently only bf16 output is supported.\n # there are also restrictions on the input/output shapes.\n # Test various group sizes and matrix dimensions\n # configs: list(g, m, k, n, output_dtype)\n configs = (\n (4, 128, 256, 64, torch.bfloat16),\n (2, 32, 32, 32, torch.bfloat16),\n )\n\n # TODO: Enable mxfp8 test when backend supports it.\n for config in configs:\n g, m, k, n, dtype = config\n # case 1: 2d x 2d\n mat1 = make_arg((m, k))\n mat2 = make_arg((k, n))\n scale1 = make_scale_factor((g, m, 1))\n scale2 = make_scale_factor((g, 1, n))\n offsets = make_index(k, g)","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops","uri":"program://Fuser/module/tests.python.opinfo.test_direct_ops#L1-L229","kind":"module","name":"tests.python.opinfo.test_direct_ops","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":1,"end_line":229,"context_start_line":1,"context_end_line":229,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\n# import nvfuser_direct first to conditionally avoid importing nvfuser\nimport nvfuser_direct # noqa: F401,F403\n\nimport torch\nimport pytest\nimport numpy as np\nfrom copy import deepcopy\nfrom typing import Callable\n\nfrom opinfo_fusion_definitions import default_fd_fn\nfrom opinfo_framework import create_op_test\nfrom opinfo_core import ReferenceType, OpInfo, SampleInput\nfrom opinfos import opinfos\nfrom opinfo_utils import (\n ArgumentType,\n is_tensor,\n requiresJAX,\n)\n\nimport io\nfrom contextlib import redirect_stdout, redirect_stderr\nfrom nvfuser_direct import FusionDefinition\nfrom nvfuser_direct.pytorch_utils import retry_on_oom_or_skip_test\nfrom python.direct_utils import check_captured_python_definition\n\n\ndef parse_args_fusion_execution(opinfo: OpInfo, *args):\n if len(args) == 0:\n return []\n\n symbolic_parameter_list = (\n opinfo.symbolic_parameter_list\n if opinfo.symbolic_parameter_list is not None\n else [ArgumentType.Symbolic] * len(args)\n )\n\n assert len(symbolic_parameter_list) >= len(args)\n\n result = []\n for arg_type, a in zip(symbolic_parameter_list, args):\n if arg_type == ArgumentType.Symbolic:\n if isinstance(a, list) and all(map(is_tensor, a)):\n result.extend(a)\n else:\n result.append(a)\n return result\n\n\n# ****** Check an Operation's Results are Correct ******\n\n\ndef torch_correctness_test_fn(fd_fn: Callable, nvf_op: OpInfo, sample: SampleInput):\n with FusionDefinition() as fd:\n fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n inputs = parse_args_fusion_execution(nvf_op, *sample.args)\n inputs_cap = deepcopy(inputs)\n nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n torch_result = nvf_op.reference(*sample.args, **sample.kwargs)\n\n if isinstance(nvfuser_result, Exception):\n raise nvfuser_result\n\n if len(nvfuser_result) == 1:\n nvfuser_result = nvfuser_result[0]\n\n # TODO If dtype is fp16 or bf16, skip dtype check because nvfuser promotes\n # to fp32 but does not return original dtype.\n # TODO Add specific dtype tolerances\n torch.testing.assert_close(\n nvfuser_result, torch_result, equal_nan=True, atol=1e-3, rtol=0\n )\n\n\n@requiresJAX\ndef jax_correctness_test_fn(fd_fn: Callable, nvf_op: OpInfo, sample: SampleInput):\n with FusionDefinition() as fd:\n fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n inputs = parse_args_fusion_execution(nvf_op, *sample.args)\n inputs_cap = deepcopy(inputs)\n nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n jax_sample = sample.jax()\n jax_result = nvf_op.reference(*jax_sample.args, **jax_sample.kwargs)\n\n # NOTE: this strange unpacking is to handle NumPy's and JAX's sometimes odd\n # number vs. array representation. In particular, NumPy can mimic\n # Python numbers, but `asarray` doesn't understand this mimicry\n np_array = np.array(jax_result)\n if np_array.shape == ():\n jax_result = torch.tensor(np_array.item(), device=\"cuda\")\n else:\n jax_result = torch.asarray(np_array, device=\"cuda\")\n\n if len(nvfuser_result) == 1:\n nvfuser_result = nvfuser_result[0]\n\n # NOTE: dtype is not checked because jax will translate int64, float64, and complex128 to int32, float32 and complex64\n torch.testing.assert_close(\n nvfuser_result, jax_result, equal_nan=True, atol=1e-3, rtol=0, check_dtype=False\n )\n\n\ndef python_correctness_test_fn(fd_fn: Callable, nvf_op: OpInfo, sample: SampleInput):\n # python reference function does not accept keyword arguments\n assert len(sample.kwargs) == 0\n\n with FusionDefinition() as fd:\n fd_fn(fd, nvf_op, *sample.args)\n inputs = parse_args_fusion_execution(nvf_op, *sample.args)\n inputs_cap = deepcopy(inputs)\n nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n # expect only single result from function\n assert len(nvfuser_result) == 1\n\n # convert tensor arguments into flat, python lists\n python_sample = sample.python()\n\n # apply reference to python lists\n python_result = map(nvf_op.reference, *python_sample.args)\n\n # create pytorch tensor\n np_array = np.array(list(python_result))\n if np_array.shape == ():\n python_result = torch.tensor(\n np_array.item(), dtype=nvfuser_result[0].dtype, device=\"cuda\"\n )\n else:\n python_result = torch.asarray(\n np_array, dtype=nvfuser_result[0].dtype, device=\"cuda\"\n )\n\n # reshape flat output tensor into expected shape\n torch.testing.assert_close(\n nvfuser_result[0],\n python_result.reshape(nvfuser_result[0].shape),\n equal_nan=True,\n atol=1e-3,\n rtol=0,\n )\n\n\ndef correctness_test_fn(\n reference_type: ReferenceType,\n nvf_op: OpInfo,\n sample: SampleInput,\n):\n _fd_fn = (\n nvf_op.fd_correctness_fn\n if nvf_op.fd_correctness_fn is not None\n else default_fd_fn\n )\n if reference_type == ReferenceType.Pytorch:\n return torch_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Jax:\n return jax_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Python:\n return python_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Numpy:\n pytest.xfail(\"Numpy feference functions are not supported.\")\n else:\n pytest.xfail(\"Reference function is not defined for this correctness test.\")\n\n\n@create_op_test(\n tuple(\n op\n for op in opinfos\n if op.sample_input_generator is not None and op.supports_direct_bindings\n )\n)\ndef test_correctness(op: OpInfo, dtype: torch.dtype):\n for sample in op.sample_input_generator(op, dtype):\n result = correctness_test_fn(op.reference_type, op, sample)\n if result is not None:\n return result\n\n\n# ****** Check that an Operation's API Gives Appropriate Input Errors ******\n\n\ndef errors_test_fn(\n nvf_op: OpInfo,\n sample: SampleInput,\n):\n _fd_fn = (\n nvf_op.fd_error_input_fn\n if nvf_op.fd_error_input_fn is not None\n else default_fd_fn\n )\n with FusionDefinition() as fd:\n _fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n fd.execute(parse_args_fusion_execution(nvf_op, *sample.args))\n\n\n# A pair of parentheses ()/[] represents a capture group in regex.\n# Escape parenthesis in regex string to match raw characters.\ndef _regex_escape_parenthesis(a: str) -> str:\n b = a.replace(r\"[\", r\"\\[\").replace(r\"]\", r\"\\]\")\n return b.replace(r\"(\", r\"\\(\").replace(r\")\", r\"\\)\")\n\n\n@create_op_test(\n tuple(\n op\n for op in opinfos\n if op.error_input_generator is not None and op.supports_direct_bindings\n )\n)\n@retry_on_oom_or_skip_test\ndef test_errors(op: OpInfo, dtype: torch.dtype):\n for sample, exception_type, exception_regex in op.error_input_generator(op, dtype):\n # TODO skip regex check because direct bindings do not have same error message as frontend.\n # Capture error strings to avoid false positives in the CI\n stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n with pytest.raises(exception_type), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n errors_test_fn(op, sample)","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops.parse_args_fusion_execution","uri":"program://Fuser/function/tests.python.opinfo.test_direct_ops.parse_args_fusion_execution#L32-L51","kind":"function","name":"parse_args_fusion_execution","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":32,"end_line":51,"context_start_line":12,"context_end_line":71,"code":"from copy import deepcopy\nfrom typing import Callable\n\nfrom opinfo_fusion_definitions import default_fd_fn\nfrom opinfo_framework import create_op_test\nfrom opinfo_core import ReferenceType, OpInfo, SampleInput\nfrom opinfos import opinfos\nfrom opinfo_utils import (\n ArgumentType,\n is_tensor,\n requiresJAX,\n)\n\nimport io\nfrom contextlib import redirect_stdout, redirect_stderr\nfrom nvfuser_direct import FusionDefinition\nfrom nvfuser_direct.pytorch_utils import retry_on_oom_or_skip_test\nfrom python.direct_utils import check_captured_python_definition\n\n\ndef parse_args_fusion_execution(opinfo: OpInfo, *args):\n if len(args) == 0:\n return []\n\n symbolic_parameter_list = (\n opinfo.symbolic_parameter_list\n if opinfo.symbolic_parameter_list is not None\n else [ArgumentType.Symbolic] * len(args)\n )\n\n assert len(symbolic_parameter_list) >= len(args)\n\n result = []\n for arg_type, a in zip(symbolic_parameter_list, args):\n if arg_type == ArgumentType.Symbolic:\n if isinstance(a, list) and all(map(is_tensor, a)):\n result.extend(a)\n else:\n result.append(a)\n return result\n\n\n# ****** Check an Operation's Results are Correct ******\n\n\ndef torch_correctness_test_fn(fd_fn: Callable, nvf_op: OpInfo, sample: SampleInput):\n with FusionDefinition() as fd:\n fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n inputs = parse_args_fusion_execution(nvf_op, *sample.args)\n inputs_cap = deepcopy(inputs)\n nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n torch_result = nvf_op.reference(*sample.args, **sample.kwargs)\n\n if isinstance(nvfuser_result, Exception):\n raise nvfuser_result\n\n if len(nvfuser_result) == 1:\n nvfuser_result = nvfuser_result[0]","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops.torch_correctness_test_fn","uri":"program://Fuser/function/tests.python.opinfo.test_direct_ops.torch_correctness_test_fn#L57-L78","kind":"function","name":"torch_correctness_test_fn","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":57,"end_line":78,"context_start_line":37,"context_end_line":98,"code":" opinfo.symbolic_parameter_list\n if opinfo.symbolic_parameter_list is not None\n else [ArgumentType.Symbolic] * len(args)\n )\n\n assert len(symbolic_parameter_list) >= len(args)\n\n result = []\n for arg_type, a in zip(symbolic_parameter_list, args):\n if arg_type == ArgumentType.Symbolic:\n if isinstance(a, list) and all(map(is_tensor, a)):\n result.extend(a)\n else:\n result.append(a)\n return result\n\n\n# ****** Check an Operation's Results are Correct ******\n\n\ndef torch_correctness_test_fn(fd_fn: Callable, nvf_op: OpInfo, sample: SampleInput):\n with FusionDefinition() as fd:\n fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n inputs = parse_args_fusion_execution(nvf_op, *sample.args)\n inputs_cap = deepcopy(inputs)\n nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n torch_result = nvf_op.reference(*sample.args, **sample.kwargs)\n\n if isinstance(nvfuser_result, Exception):\n raise nvfuser_result\n\n if len(nvfuser_result) == 1:\n nvfuser_result = nvfuser_result[0]\n\n # TODO If dtype is fp16 or bf16, skip dtype check because nvfuser promotes\n # to fp32 but does not return original dtype.\n # TODO Add specific dtype tolerances\n torch.testing.assert_close(\n nvfuser_result, torch_result, equal_nan=True, atol=1e-3, rtol=0\n )\n\n\n@requiresJAX\ndef jax_correctness_test_fn(fd_fn: Callable, nvf_op: OpInfo, sample: SampleInput):\n with FusionDefinition() as fd:\n fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n inputs = parse_args_fusion_execution(nvf_op, *sample.args)\n inputs_cap = deepcopy(inputs)\n nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n jax_sample = sample.jax()\n jax_result = nvf_op.reference(*jax_sample.args, **jax_sample.kwargs)\n\n # NOTE: this strange unpacking is to handle NumPy's and JAX's sometimes odd\n # number vs. array representation. In particular, NumPy can mimic\n # Python numbers, but `asarray` doesn't understand this mimicry\n np_array = np.array(jax_result)\n if np_array.shape == ():\n jax_result = torch.tensor(np_array.item(), device=\"cuda\")","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops.jax_correctness_test_fn","uri":"program://Fuser/function/tests.python.opinfo.test_direct_ops.jax_correctness_test_fn#L82-L108","kind":"function","name":"jax_correctness_test_fn","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":82,"end_line":108,"context_start_line":62,"context_end_line":128,"code":" nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n torch_result = nvf_op.reference(*sample.args, **sample.kwargs)\n\n if isinstance(nvfuser_result, Exception):\n raise nvfuser_result\n\n if len(nvfuser_result) == 1:\n nvfuser_result = nvfuser_result[0]\n\n # TODO If dtype is fp16 or bf16, skip dtype check because nvfuser promotes\n # to fp32 but does not return original dtype.\n # TODO Add specific dtype tolerances\n torch.testing.assert_close(\n nvfuser_result, torch_result, equal_nan=True, atol=1e-3, rtol=0\n )\n\n\n@requiresJAX\ndef jax_correctness_test_fn(fd_fn: Callable, nvf_op: OpInfo, sample: SampleInput):\n with FusionDefinition() as fd:\n fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n inputs = parse_args_fusion_execution(nvf_op, *sample.args)\n inputs_cap = deepcopy(inputs)\n nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n jax_sample = sample.jax()\n jax_result = nvf_op.reference(*jax_sample.args, **jax_sample.kwargs)\n\n # NOTE: this strange unpacking is to handle NumPy's and JAX's sometimes odd\n # number vs. array representation. In particular, NumPy can mimic\n # Python numbers, but `asarray` doesn't understand this mimicry\n np_array = np.array(jax_result)\n if np_array.shape == ():\n jax_result = torch.tensor(np_array.item(), device=\"cuda\")\n else:\n jax_result = torch.asarray(np_array, device=\"cuda\")\n\n if len(nvfuser_result) == 1:\n nvfuser_result = nvfuser_result[0]\n\n # NOTE: dtype is not checked because jax will translate int64, float64, and complex128 to int32, float32 and complex64\n torch.testing.assert_close(\n nvfuser_result, jax_result, equal_nan=True, atol=1e-3, rtol=0, check_dtype=False\n )\n\n\ndef python_correctness_test_fn(fd_fn: Callable, nvf_op: OpInfo, sample: SampleInput):\n # python reference function does not accept keyword arguments\n assert len(sample.kwargs) == 0\n\n with FusionDefinition() as fd:\n fd_fn(fd, nvf_op, *sample.args)\n inputs = parse_args_fusion_execution(nvf_op, *sample.args)\n inputs_cap = deepcopy(inputs)\n nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n # expect only single result from function\n assert len(nvfuser_result) == 1\n\n # convert tensor arguments into flat, python lists\n python_sample = sample.python()\n\n # apply reference to python lists","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops.python_correctness_test_fn","uri":"program://Fuser/function/tests.python.opinfo.test_direct_ops.python_correctness_test_fn#L111-L149","kind":"function","name":"python_correctness_test_fn","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":111,"end_line":149,"context_start_line":91,"context_end_line":169,"code":" jax_result = nvf_op.reference(*jax_sample.args, **jax_sample.kwargs)\n\n # NOTE: this strange unpacking is to handle NumPy's and JAX's sometimes odd\n # number vs. array representation. In particular, NumPy can mimic\n # Python numbers, but `asarray` doesn't understand this mimicry\n np_array = np.array(jax_result)\n if np_array.shape == ():\n jax_result = torch.tensor(np_array.item(), device=\"cuda\")\n else:\n jax_result = torch.asarray(np_array, device=\"cuda\")\n\n if len(nvfuser_result) == 1:\n nvfuser_result = nvfuser_result[0]\n\n # NOTE: dtype is not checked because jax will translate int64, float64, and complex128 to int32, float32 and complex64\n torch.testing.assert_close(\n nvfuser_result, jax_result, equal_nan=True, atol=1e-3, rtol=0, check_dtype=False\n )\n\n\ndef python_correctness_test_fn(fd_fn: Callable, nvf_op: OpInfo, sample: SampleInput):\n # python reference function does not accept keyword arguments\n assert len(sample.kwargs) == 0\n\n with FusionDefinition() as fd:\n fd_fn(fd, nvf_op, *sample.args)\n inputs = parse_args_fusion_execution(nvf_op, *sample.args)\n inputs_cap = deepcopy(inputs)\n nvfuser_result = fd.execute(inputs)\n assert check_captured_python_definition(nvfuser_result, fd, inputs_cap)\n\n # expect only single result from function\n assert len(nvfuser_result) == 1\n\n # convert tensor arguments into flat, python lists\n python_sample = sample.python()\n\n # apply reference to python lists\n python_result = map(nvf_op.reference, *python_sample.args)\n\n # create pytorch tensor\n np_array = np.array(list(python_result))\n if np_array.shape == ():\n python_result = torch.tensor(\n np_array.item(), dtype=nvfuser_result[0].dtype, device=\"cuda\"\n )\n else:\n python_result = torch.asarray(\n np_array, dtype=nvfuser_result[0].dtype, device=\"cuda\"\n )\n\n # reshape flat output tensor into expected shape\n torch.testing.assert_close(\n nvfuser_result[0],\n python_result.reshape(nvfuser_result[0].shape),\n equal_nan=True,\n atol=1e-3,\n rtol=0,\n )\n\n\ndef correctness_test_fn(\n reference_type: ReferenceType,\n nvf_op: OpInfo,\n sample: SampleInput,\n):\n _fd_fn = (\n nvf_op.fd_correctness_fn\n if nvf_op.fd_correctness_fn is not None\n else default_fd_fn\n )\n if reference_type == ReferenceType.Pytorch:\n return torch_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Jax:\n return jax_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Python:\n return python_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Numpy:\n pytest.xfail(\"Numpy feference functions are not supported.\")","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops.correctness_test_fn","uri":"program://Fuser/function/tests.python.opinfo.test_direct_ops.correctness_test_fn#L152-L171","kind":"function","name":"correctness_test_fn","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":152,"end_line":171,"context_start_line":132,"context_end_line":191,"code":" np_array = np.array(list(python_result))\n if np_array.shape == ():\n python_result = torch.tensor(\n np_array.item(), dtype=nvfuser_result[0].dtype, device=\"cuda\"\n )\n else:\n python_result = torch.asarray(\n np_array, dtype=nvfuser_result[0].dtype, device=\"cuda\"\n )\n\n # reshape flat output tensor into expected shape\n torch.testing.assert_close(\n nvfuser_result[0],\n python_result.reshape(nvfuser_result[0].shape),\n equal_nan=True,\n atol=1e-3,\n rtol=0,\n )\n\n\ndef correctness_test_fn(\n reference_type: ReferenceType,\n nvf_op: OpInfo,\n sample: SampleInput,\n):\n _fd_fn = (\n nvf_op.fd_correctness_fn\n if nvf_op.fd_correctness_fn is not None\n else default_fd_fn\n )\n if reference_type == ReferenceType.Pytorch:\n return torch_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Jax:\n return jax_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Python:\n return python_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Numpy:\n pytest.xfail(\"Numpy feference functions are not supported.\")\n else:\n pytest.xfail(\"Reference function is not defined for this correctness test.\")\n\n\n@create_op_test(\n tuple(\n op\n for op in opinfos\n if op.sample_input_generator is not None and op.supports_direct_bindings\n )\n)\ndef test_correctness(op: OpInfo, dtype: torch.dtype):\n for sample in op.sample_input_generator(op, dtype):\n result = correctness_test_fn(op.reference_type, op, sample)\n if result is not None:\n return result\n\n\n# ****** Check that an Operation's API Gives Appropriate Input Errors ******\n\n\ndef errors_test_fn(","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops.test_correctness","uri":"program://Fuser/function/tests.python.opinfo.test_direct_ops.test_correctness#L181-L185","kind":"function","name":"test_correctness","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":181,"end_line":185,"context_start_line":161,"context_end_line":205,"code":" )\n if reference_type == ReferenceType.Pytorch:\n return torch_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Jax:\n return jax_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Python:\n return python_correctness_test_fn(_fd_fn, nvf_op, sample)\n elif reference_type == ReferenceType.Numpy:\n pytest.xfail(\"Numpy feference functions are not supported.\")\n else:\n pytest.xfail(\"Reference function is not defined for this correctness test.\")\n\n\n@create_op_test(\n tuple(\n op\n for op in opinfos\n if op.sample_input_generator is not None and op.supports_direct_bindings\n )\n)\ndef test_correctness(op: OpInfo, dtype: torch.dtype):\n for sample in op.sample_input_generator(op, dtype):\n result = correctness_test_fn(op.reference_type, op, sample)\n if result is not None:\n return result\n\n\n# ****** Check that an Operation's API Gives Appropriate Input Errors ******\n\n\ndef errors_test_fn(\n nvf_op: OpInfo,\n sample: SampleInput,\n):\n _fd_fn = (\n nvf_op.fd_error_input_fn\n if nvf_op.fd_error_input_fn is not None\n else default_fd_fn\n )\n with FusionDefinition() as fd:\n _fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n fd.execute(parse_args_fusion_execution(nvf_op, *sample.args))\n\n\n# A pair of parentheses ()/[] represents a capture group in regex.","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops.errors_test_fn","uri":"program://Fuser/function/tests.python.opinfo.test_direct_ops.errors_test_fn#L191-L202","kind":"function","name":"errors_test_fn","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":191,"end_line":202,"context_start_line":171,"context_end_line":222,"code":" pytest.xfail(\"Reference function is not defined for this correctness test.\")\n\n\n@create_op_test(\n tuple(\n op\n for op in opinfos\n if op.sample_input_generator is not None and op.supports_direct_bindings\n )\n)\ndef test_correctness(op: OpInfo, dtype: torch.dtype):\n for sample in op.sample_input_generator(op, dtype):\n result = correctness_test_fn(op.reference_type, op, sample)\n if result is not None:\n return result\n\n\n# ****** Check that an Operation's API Gives Appropriate Input Errors ******\n\n\ndef errors_test_fn(\n nvf_op: OpInfo,\n sample: SampleInput,\n):\n _fd_fn = (\n nvf_op.fd_error_input_fn\n if nvf_op.fd_error_input_fn is not None\n else default_fd_fn\n )\n with FusionDefinition() as fd:\n _fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n fd.execute(parse_args_fusion_execution(nvf_op, *sample.args))\n\n\n# A pair of parentheses ()/[] represents a capture group in regex.\n# Escape parenthesis in regex string to match raw characters.\ndef _regex_escape_parenthesis(a: str) -> str:\n b = a.replace(r\"[\", r\"\\[\").replace(r\"]\", r\"\\]\")\n return b.replace(r\"(\", r\"\\(\").replace(r\")\", r\"\\)\")\n\n\n@create_op_test(\n tuple(\n op\n for op in opinfos\n if op.error_input_generator is not None and op.supports_direct_bindings\n )\n)\n@retry_on_oom_or_skip_test\ndef test_errors(op: OpInfo, dtype: torch.dtype):\n for sample, exception_type, exception_regex in op.error_input_generator(op, dtype):\n # TODO skip regex check because direct bindings do not have same error message as frontend.","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops._regex_escape_parenthesis","uri":"program://Fuser/function/tests.python.opinfo.test_direct_ops._regex_escape_parenthesis#L207-L209","kind":"function","name":"_regex_escape_parenthesis","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":207,"end_line":209,"context_start_line":187,"context_end_line":229,"code":"\n# ****** Check that an Operation's API Gives Appropriate Input Errors ******\n\n\ndef errors_test_fn(\n nvf_op: OpInfo,\n sample: SampleInput,\n):\n _fd_fn = (\n nvf_op.fd_error_input_fn\n if nvf_op.fd_error_input_fn is not None\n else default_fd_fn\n )\n with FusionDefinition() as fd:\n _fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n fd.execute(parse_args_fusion_execution(nvf_op, *sample.args))\n\n\n# A pair of parentheses ()/[] represents a capture group in regex.\n# Escape parenthesis in regex string to match raw characters.\ndef _regex_escape_parenthesis(a: str) -> str:\n b = a.replace(r\"[\", r\"\\[\").replace(r\"]\", r\"\\]\")\n return b.replace(r\"(\", r\"\\(\").replace(r\")\", r\"\\)\")\n\n\n@create_op_test(\n tuple(\n op\n for op in opinfos\n if op.error_input_generator is not None and op.supports_direct_bindings\n )\n)\n@retry_on_oom_or_skip_test\ndef test_errors(op: OpInfo, dtype: torch.dtype):\n for sample, exception_type, exception_regex in op.error_input_generator(op, dtype):\n # TODO skip regex check because direct bindings do not have same error message as frontend.\n # Capture error strings to avoid false positives in the CI\n stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n with pytest.raises(exception_type), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n errors_test_fn(op, sample)","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.test_direct_ops.test_errors","uri":"program://Fuser/function/tests.python.opinfo.test_direct_ops.test_errors#L220-L229","kind":"function","name":"test_errors","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":220,"end_line":229,"context_start_line":200,"context_end_line":229,"code":" with FusionDefinition() as fd:\n _fd_fn(fd, nvf_op, *sample.args, **sample.kwargs)\n fd.execute(parse_args_fusion_execution(nvf_op, *sample.args))\n\n\n# A pair of parentheses ()/[] represents a capture group in regex.\n# Escape parenthesis in regex string to match raw characters.\ndef _regex_escape_parenthesis(a: str) -> str:\n b = a.replace(r\"[\", r\"\\[\").replace(r\"]\", r\"\\]\")\n return b.replace(r\"(\", r\"\\(\").replace(r\")\", r\"\\)\")\n\n\n@create_op_test(\n tuple(\n op\n for op in opinfos\n if op.error_input_generator is not None and op.supports_direct_bindings\n )\n)\n@retry_on_oom_or_skip_test\ndef test_errors(op: OpInfo, dtype: torch.dtype):\n for sample, exception_type, exception_regex in op.error_input_generator(op, dtype):\n # TODO skip regex check because direct bindings do not have same error message as frontend.\n # Capture error strings to avoid false positives in the CI\n stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n with pytest.raises(exception_type), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n errors_test_fn(op, sample)","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_framework","uri":"program://Fuser/module/tests.python.opinfo.opinfo_framework#L1-L84","kind":"module","name":"tests.python.opinfo.opinfo_framework","path":"tests/python/opinfo/opinfo_framework.py","language":"python","start_line":1,"end_line":84,"context_start_line":1,"context_end_line":84,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport inspect\nimport torch\nfrom typing import Callable\nfrom opinfo_utils import map_dtype_to_str\nimport pytest\n\n\ndef _instantiate_opinfo_test_template(\n template: Callable, *, opinfo, dtype: torch.dtype\n) -> Callable:\n \"\"\"Instantiates a test template for an operator.\"\"\"\n\n def test():\n # Ref: https://github.com/pytorch/pytorch/blob/aa8ea1d787a9d21b064b664c5344376265feea6c/torch/testing/_internal/common_utils.py#L2251-L2263\n # > CUDA device side error will cause subsequence test cases to fail.\n # > stop entire test suite if catches RuntimeError during torch.cuda.synchronize().\n if torch.cuda.is_initialized():\n try:\n torch.cuda.synchronize()\n except RuntimeError as rte:\n pytest.exit(\n \"TEST SUITE EARLY TERMINATION due to torch.cuda.synchronize() failure\"\n )\n\n return template(opinfo, dtype)\n\n test.__name__ = \"_\".join((template.__name__, opinfo.name, map_dtype_to_str[dtype]))\n test.__module__ = test.__module__\n return test\n\n\nclass create_op_test:\n def __init__(self, opinfos, *, scope=None):\n self.opinfos = opinfos\n\n # Acquires the caller's global scope\n if scope is None:\n previous_frame = inspect.currentframe().f_back\n scope = previous_frame.f_globals\n self.scope = scope\n\n def __call__(self, test_template):\n # NOTE Unlike a typical decorator, this __call__ does not return a function, because it may\n # (and typically does) instantiate multiple functions from the template it consumes.\n # Since Python doesn't natively support one-to-many function decorators, the produced\n # functions are directly assigned to the requested scope (the caller's global scope by default)\n for opinfo in self.opinfos:\n for dtype in sorted(opinfo.dtypes, key=lambda t: repr(t)):\n test = _instantiate_opinfo_test_template(\n test_template,\n opinfo=opinfo,\n dtype=dtype,\n )\n # Adds the instantiated test to the requested scope\n self.scope[test.__name__] = test\n\n\n# This pseudo-decorator enables automatic serialization upon program exit and\n# tests deserializing the default workspace upon creating the tests.\n#\n# Serializing error test cases corrupts the serialized binary. We call\n# FusionCache.reset() to clear the cache after running an error test in\n# `test_python_frontend.py'. In the pytest framework, the error tests are\n# separate from the correctness tests. Only apply this decorator to the\n# correctness tests to avoid calling FusionCache.reset().\nclass atexit_serde_create_op_test(create_op_test):\n def __init__(self, opinfos, *, scope=None):\n from python.utils import atexit_serde_check\n\n atexit_serde_check()\n\n # Replicate create_op_test.__init__ to have correct scope\n self.opinfos = opinfos\n\n # Acquires the caller's global scope\n if scope is None:\n previous_frame = inspect.currentframe().f_back\n scope = previous_frame.f_globals\n self.scope = scope","source_hash":"4f3ed271b48407a66bec01b8baaabfecc481eb0b15f1ff5ded5cc6f25376e13a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_framework._instantiate_opinfo_test_template","uri":"program://Fuser/function/tests.python.opinfo.opinfo_framework._instantiate_opinfo_test_template#L13-L34","kind":"function","name":"_instantiate_opinfo_test_template","path":"tests/python/opinfo/opinfo_framework.py","language":"python","start_line":13,"end_line":34,"context_start_line":1,"context_end_line":54,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport inspect\nimport torch\nfrom typing import Callable\nfrom opinfo_utils import map_dtype_to_str\nimport pytest\n\n\ndef _instantiate_opinfo_test_template(\n template: Callable, *, opinfo, dtype: torch.dtype\n) -> Callable:\n \"\"\"Instantiates a test template for an operator.\"\"\"\n\n def test():\n # Ref: https://github.com/pytorch/pytorch/blob/aa8ea1d787a9d21b064b664c5344376265feea6c/torch/testing/_internal/common_utils.py#L2251-L2263\n # > CUDA device side error will cause subsequence test cases to fail.\n # > stop entire test suite if catches RuntimeError during torch.cuda.synchronize().\n if torch.cuda.is_initialized():\n try:\n torch.cuda.synchronize()\n except RuntimeError as rte:\n pytest.exit(\n \"TEST SUITE EARLY TERMINATION due to torch.cuda.synchronize() failure\"\n )\n\n return template(opinfo, dtype)\n\n test.__name__ = \"_\".join((template.__name__, opinfo.name, map_dtype_to_str[dtype]))\n test.__module__ = test.__module__\n return test\n\n\nclass create_op_test:\n def __init__(self, opinfos, *, scope=None):\n self.opinfos = opinfos\n\n # Acquires the caller's global scope\n if scope is None:\n previous_frame = inspect.currentframe().f_back\n scope = previous_frame.f_globals\n self.scope = scope\n\n def __call__(self, test_template):\n # NOTE Unlike a typical decorator, this __call__ does not return a function, because it may\n # (and typically does) instantiate multiple functions from the template it consumes.\n # Since Python doesn't natively support one-to-many function decorators, the produced\n # functions are directly assigned to the requested scope (the caller's global scope by default)\n for opinfo in self.opinfos:\n for dtype in sorted(opinfo.dtypes, key=lambda t: repr(t)):\n test = _instantiate_opinfo_test_template(","source_hash":"4f3ed271b48407a66bec01b8baaabfecc481eb0b15f1ff5ded5cc6f25376e13a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_framework.create_op_test","uri":"program://Fuser/class/tests.python.opinfo.opinfo_framework.create_op_test#L37-L60","kind":"class","name":"create_op_test","path":"tests/python/opinfo/opinfo_framework.py","language":"python","start_line":37,"end_line":60,"context_start_line":17,"context_end_line":80,"code":"\n def test():\n # Ref: https://github.com/pytorch/pytorch/blob/aa8ea1d787a9d21b064b664c5344376265feea6c/torch/testing/_internal/common_utils.py#L2251-L2263\n # > CUDA device side error will cause subsequence test cases to fail.\n # > stop entire test suite if catches RuntimeError during torch.cuda.synchronize().\n if torch.cuda.is_initialized():\n try:\n torch.cuda.synchronize()\n except RuntimeError as rte:\n pytest.exit(\n \"TEST SUITE EARLY TERMINATION due to torch.cuda.synchronize() failure\"\n )\n\n return template(opinfo, dtype)\n\n test.__name__ = \"_\".join((template.__name__, opinfo.name, map_dtype_to_str[dtype]))\n test.__module__ = test.__module__\n return test\n\n\nclass create_op_test:\n def __init__(self, opinfos, *, scope=None):\n self.opinfos = opinfos\n\n # Acquires the caller's global scope\n if scope is None:\n previous_frame = inspect.currentframe().f_back\n scope = previous_frame.f_globals\n self.scope = scope\n\n def __call__(self, test_template):\n # NOTE Unlike a typical decorator, this __call__ does not return a function, because it may\n # (and typically does) instantiate multiple functions from the template it consumes.\n # Since Python doesn't natively support one-to-many function decorators, the produced\n # functions are directly assigned to the requested scope (the caller's global scope by default)\n for opinfo in self.opinfos:\n for dtype in sorted(opinfo.dtypes, key=lambda t: repr(t)):\n test = _instantiate_opinfo_test_template(\n test_template,\n opinfo=opinfo,\n dtype=dtype,\n )\n # Adds the instantiated test to the requested scope\n self.scope[test.__name__] = test\n\n\n# This pseudo-decorator enables automatic serialization upon program exit and\n# tests deserializing the default workspace upon creating the tests.\n#\n# Serializing error test cases corrupts the serialized binary. We call\n# FusionCache.reset() to clear the cache after running an error test in\n# `test_python_frontend.py'. In the pytest framework, the error tests are\n# separate from the correctness tests. Only apply this decorator to the\n# correctness tests to avoid calling FusionCache.reset().\nclass atexit_serde_create_op_test(create_op_test):\n def __init__(self, opinfos, *, scope=None):\n from python.utils import atexit_serde_check\n\n atexit_serde_check()\n\n # Replicate create_op_test.__init__ to have correct scope\n self.opinfos = opinfos\n\n # Acquires the caller's global scope","source_hash":"4f3ed271b48407a66bec01b8baaabfecc481eb0b15f1ff5ded5cc6f25376e13a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_framework.atexit_serde_create_op_test","uri":"program://Fuser/class/tests.python.opinfo.opinfo_framework.atexit_serde_create_op_test#L71-L84","kind":"class","name":"atexit_serde_create_op_test","path":"tests/python/opinfo/opinfo_framework.py","language":"python","start_line":71,"end_line":84,"context_start_line":51,"context_end_line":84,"code":" # functions are directly assigned to the requested scope (the caller's global scope by default)\n for opinfo in self.opinfos:\n for dtype in sorted(opinfo.dtypes, key=lambda t: repr(t)):\n test = _instantiate_opinfo_test_template(\n test_template,\n opinfo=opinfo,\n dtype=dtype,\n )\n # Adds the instantiated test to the requested scope\n self.scope[test.__name__] = test\n\n\n# This pseudo-decorator enables automatic serialization upon program exit and\n# tests deserializing the default workspace upon creating the tests.\n#\n# Serializing error test cases corrupts the serialized binary. We call\n# FusionCache.reset() to clear the cache after running an error test in\n# `test_python_frontend.py'. In the pytest framework, the error tests are\n# separate from the correctness tests. Only apply this decorator to the\n# correctness tests to avoid calling FusionCache.reset().\nclass atexit_serde_create_op_test(create_op_test):\n def __init__(self, opinfos, *, scope=None):\n from python.utils import atexit_serde_check\n\n atexit_serde_check()\n\n # Replicate create_op_test.__init__ to have correct scope\n self.opinfos = opinfos\n\n # Acquires the caller's global scope\n if scope is None:\n previous_frame = inspect.currentframe().f_back\n scope = previous_frame.f_globals\n self.scope = scope","source_hash":"4f3ed271b48407a66bec01b8baaabfecc481eb0b15f1ff5ded5cc6f25376e13a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_framework.test","uri":"program://Fuser/function/tests.python.opinfo.opinfo_framework.test#L18-L30","kind":"function","name":"test","path":"tests/python/opinfo/opinfo_framework.py","language":"python","start_line":18,"end_line":30,"context_start_line":1,"context_end_line":50,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport inspect\nimport torch\nfrom typing import Callable\nfrom opinfo_utils import map_dtype_to_str\nimport pytest\n\n\ndef _instantiate_opinfo_test_template(\n template: Callable, *, opinfo, dtype: torch.dtype\n) -> Callable:\n \"\"\"Instantiates a test template for an operator.\"\"\"\n\n def test():\n # Ref: https://github.com/pytorch/pytorch/blob/aa8ea1d787a9d21b064b664c5344376265feea6c/torch/testing/_internal/common_utils.py#L2251-L2263\n # > CUDA device side error will cause subsequence test cases to fail.\n # > stop entire test suite if catches RuntimeError during torch.cuda.synchronize().\n if torch.cuda.is_initialized():\n try:\n torch.cuda.synchronize()\n except RuntimeError as rte:\n pytest.exit(\n \"TEST SUITE EARLY TERMINATION due to torch.cuda.synchronize() failure\"\n )\n\n return template(opinfo, dtype)\n\n test.__name__ = \"_\".join((template.__name__, opinfo.name, map_dtype_to_str[dtype]))\n test.__module__ = test.__module__\n return test\n\n\nclass create_op_test:\n def __init__(self, opinfos, *, scope=None):\n self.opinfos = opinfos\n\n # Acquires the caller's global scope\n if scope is None:\n previous_frame = inspect.currentframe().f_back\n scope = previous_frame.f_globals\n self.scope = scope\n\n def __call__(self, test_template):\n # NOTE Unlike a typical decorator, this __call__ does not return a function, because it may\n # (and typically does) instantiate multiple functions from the template it consumes.\n # Since Python doesn't natively support one-to-many function decorators, the produced","source_hash":"4f3ed271b48407a66bec01b8baaabfecc481eb0b15f1ff5ded5cc6f25376e13a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_framework.__init__","uri":"program://Fuser/function/tests.python.opinfo.opinfo_framework.__init__#L72-L84","kind":"function","name":"__init__","path":"tests/python/opinfo/opinfo_framework.py","language":"python","start_line":72,"end_line":84,"context_start_line":52,"context_end_line":84,"code":" for opinfo in self.opinfos:\n for dtype in sorted(opinfo.dtypes, key=lambda t: repr(t)):\n test = _instantiate_opinfo_test_template(\n test_template,\n opinfo=opinfo,\n dtype=dtype,\n )\n # Adds the instantiated test to the requested scope\n self.scope[test.__name__] = test\n\n\n# This pseudo-decorator enables automatic serialization upon program exit and\n# tests deserializing the default workspace upon creating the tests.\n#\n# Serializing error test cases corrupts the serialized binary. We call\n# FusionCache.reset() to clear the cache after running an error test in\n# `test_python_frontend.py'. In the pytest framework, the error tests are\n# separate from the correctness tests. Only apply this decorator to the\n# correctness tests to avoid calling FusionCache.reset().\nclass atexit_serde_create_op_test(create_op_test):\n def __init__(self, opinfos, *, scope=None):\n from python.utils import atexit_serde_check\n\n atexit_serde_check()\n\n # Replicate create_op_test.__init__ to have correct scope\n self.opinfos = opinfos\n\n # Acquires the caller's global scope\n if scope is None:\n previous_frame = inspect.currentframe().f_back\n scope = previous_frame.f_globals\n self.scope = scope","source_hash":"4f3ed271b48407a66bec01b8baaabfecc481eb0b15f1ff5ded5cc6f25376e13a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_framework.__call__","uri":"program://Fuser/function/tests.python.opinfo.opinfo_framework.__call__#L47-L60","kind":"function","name":"__call__","path":"tests/python/opinfo/opinfo_framework.py","language":"python","start_line":47,"end_line":60,"context_start_line":27,"context_end_line":80,"code":" \"TEST SUITE EARLY TERMINATION due to torch.cuda.synchronize() failure\"\n )\n\n return template(opinfo, dtype)\n\n test.__name__ = \"_\".join((template.__name__, opinfo.name, map_dtype_to_str[dtype]))\n test.__module__ = test.__module__\n return test\n\n\nclass create_op_test:\n def __init__(self, opinfos, *, scope=None):\n self.opinfos = opinfos\n\n # Acquires the caller's global scope\n if scope is None:\n previous_frame = inspect.currentframe().f_back\n scope = previous_frame.f_globals\n self.scope = scope\n\n def __call__(self, test_template):\n # NOTE Unlike a typical decorator, this __call__ does not return a function, because it may\n # (and typically does) instantiate multiple functions from the template it consumes.\n # Since Python doesn't natively support one-to-many function decorators, the produced\n # functions are directly assigned to the requested scope (the caller's global scope by default)\n for opinfo in self.opinfos:\n for dtype in sorted(opinfo.dtypes, key=lambda t: repr(t)):\n test = _instantiate_opinfo_test_template(\n test_template,\n opinfo=opinfo,\n dtype=dtype,\n )\n # Adds the instantiated test to the requested scope\n self.scope[test.__name__] = test\n\n\n# This pseudo-decorator enables automatic serialization upon program exit and\n# tests deserializing the default workspace upon creating the tests.\n#\n# Serializing error test cases corrupts the serialized binary. We call\n# FusionCache.reset() to clear the cache after running an error test in\n# `test_python_frontend.py'. In the pytest framework, the error tests are\n# separate from the correctness tests. Only apply this decorator to the\n# correctness tests to avoid calling FusionCache.reset().\nclass atexit_serde_create_op_test(create_op_test):\n def __init__(self, opinfos, *, scope=None):\n from python.utils import atexit_serde_check\n\n atexit_serde_check()\n\n # Replicate create_op_test.__init__ to have correct scope\n self.opinfos = opinfos\n\n # Acquires the caller's global scope","source_hash":"4f3ed271b48407a66bec01b8baaabfecc481eb0b15f1ff5ded5cc6f25376e13a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos","uri":"program://Fuser/module/tests.python.opinfo.opinfos#L1-L1462","kind":"module","name":"tests.python.opinfo.opinfos","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1,"end_line":1462,"context_start_line":1,"context_end_line":1462,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport math\nimport torch\nfrom looseversion import LooseVersion\nfrom opinfo_core import OpInfo, ReferenceType, Domain\nfrom opinfo_fusion_definitions import (\n api_test_fd_fn,\n tensor_input_fd_fn,\n tensor_api_test_fd_fn,\n vector_api_test_fd_fn,\n)\nfrom opinfo_input_generators import (\n argsort_generator,\n topk_generator,\n topk_error_generator,\n broadcast_error_generator,\n broadcast_in_dim_generator,\n broadcast_in_dim_error_generator,\n cat_generator,\n cat_error_generator,\n div_input_generator,\n define_tensor_error_generator,\n define_vector_constant_error_generator,\n elementwise_binary_generator,\n _elementwise_binary_torch,\n elementwise_unary_generator,\n _elementwise_unary_torch,\n full_error_generator,\n gather_generator,\n scatter_generator,\n index_select_generator,\n index_select_error_generator,\n index_put_accumulate_generator,\n iota_error_generator,\n pad_error_generator,\n permute_generator,\n permute_error_generator,\n random_dist_error_generator,\n reduction_error_generator,\n reshape_generator,\n reshape_error_generator,\n slice_generator,\n slice_error_generator,\n squeeze_generator,\n squeeze_error_generator,\n take_along_axis_generator,\n take_along_axis_error_generator,\n tensor_size_error_generator,\n var_mean_generator,\n vector_at_error_generator,\n where_error_generator,\n matmul_input_generator,\n linear_input_generator,\n linear_error_generator,\n triu_input_generator,\n triu_error_generator,\n cumsum_input_generator,\n cumsum_error_generator,\n grouped_mm_input_generator,\n scaled_grouped_mm_input_generator,\n scaled_mm_input_generator,\n)\nfrom opinfo_utils import (\n bool_int_dtypes,\n complex_dtypes,\n full_precision_float_dtypes,\n int_dtypes,\n int_float_dtypes,\n float_dtypes,\n float_complex_dtypes,\n ArgumentType,\n JAX_AVAILABLE,\n)\nfrom functools import partial\n\nif JAX_AVAILABLE:\n import jax\n\n\neps = 1e-2\n\nopinfos = []\n\n\"\"\" Start Fusion Input Operations \"\"\"\nfusion_input_ops = []\n\ndefine_tensor_opinfo = OpInfo(\n lambda fd: fd.define_tensor,\n \"define_tensor\",\n error_input_generator=define_tensor_error_generator,\n fd_error_input_fn=tensor_input_fd_fn,\n)\nfusion_input_ops.append(define_tensor_opinfo)\n\n# NOTE: \"define_vector\" only supports vectors of integers that represent\n# tensor shapes and is not a general interface for defining vectors of\n# data. Vectors of data should be handled with a 1D `define_tensor`.\ndefine_vector_constant_opinfo = OpInfo(\n lambda fd: fd.define_vector,\n \"define_vector_constant\",\n error_input_generator=define_vector_constant_error_generator,\n fd_error_input_fn=api_test_fd_fn,\n # Direct bindings supports python lists and tuples of values.\n # These python lists are directly indexable, so `define_vector_constant` is not needed.\n supports_direct_bindings=False,\n)\nfusion_input_ops.append(define_vector_constant_opinfo)\n\n\"\"\" End Fusion Input Operations \"\"\"\n\n\"\"\" Start Unary-Float Operations \"\"\"\nunary_ops = []\n\nabs_opinfo = OpInfo(\n lambda fd: fd.ops.abs,\n \"abs\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.abs),\n is_clonable=True,\n)\nunary_ops.append(abs_opinfo)\n\nacos_opinfo = OpInfo(\n lambda fd: fd.ops.acos,\n \"acos\",\n domain=Domain(-1, 1),\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.acos),\n is_clonable=True,\n)\nunary_ops.append(acos_opinfo)\n\nacosh_opinfo = OpInfo(\n lambda fd: fd.ops.acosh,\n \"acosh\",\n domain=Domain(-1, math.inf),\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.acosh),\n is_clonable=True,\n)\nunary_ops.append(acosh_opinfo)\n\nasin_opinfo = OpInfo(\n lambda fd: fd.ops.asin,\n \"asin\",\n domain=Domain(-1, 1),\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.asin),\n is_clonable=True,\n)\nunary_ops.append(asin_opinfo)\n\nasinh_opinfo = OpInfo(\n lambda fd: fd.ops.asinh,\n \"asinh\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.asinh),\n is_clonable=True,\n)\nunary_ops.append(asinh_opinfo)\n\natan_opinfo = OpInfo(\n lambda fd: fd.ops.atan,\n \"atan\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.atan),\n is_clonable=True,\n)\nunary_ops.append(atan_opinfo)\n\natanh_opinfo = OpInfo(\n lambda fd: fd.ops.atanh,\n \"atanh\",\n domain=Domain(-1 + eps, 1 + eps),\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.atanh),\n is_clonable=True,\n)\nunary_ops.append(atanh_opinfo)\n\nbitwise_not_opinfo = OpInfo(\n lambda fd: fd.ops.bitwise_not,\n \"bitwise_not\",\n dtypes=bool_int_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.bitwise_not),\n is_clonable=True,\n)\nunary_ops.append(bitwise_not_opinfo)\n\n# TODO add nvfuser exception for int dtypes\nceil_opinfo = OpInfo(\n lambda fd: fd.ops.ceil,\n \"ceil\",\n dtypes=full_precision_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.ceil),\n is_clonable=True,\n)\nunary_ops.append(ceil_opinfo)\n\ncos_opinfo = OpInfo(\n lambda fd: fd.ops.cos,\n \"cos\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.cos),\n is_clonable=True,\n)\nunary_ops.append(cos_opinfo)\n\ncosh_opinfo = OpInfo(\n lambda fd: fd.ops.cosh,\n \"cosh\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.cosh),\n is_clonable=True,\n)\nunary_ops.append(cosh_opinfo)\n\nerf_opinfo = OpInfo(\n lambda fd: fd.ops.erf,\n \"erf\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.erf),\n is_clonable=True,\n)\nunary_ops.append(erf_opinfo)\n\nerfc_opinfo = OpInfo(\n lambda fd: fd.ops.erfc,\n \"erfc\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.erfc),\n is_clonable=True,\n)\nunary_ops.append(erfc_opinfo)\n\nerfcinv_opinfo = OpInfo(\n lambda fd: fd.ops.erfcinv,\n \"erfcinv\",\n dtypes=(\n torch.float32,\n torch.float64,\n ),\n domain=Domain(0.3, 0.7),\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(lambda x: torch.erfinv(1 - x)),\n is_clonable=True,\n)\nunary_ops.append(erfcinv_opinfo)\n\nerfinv_opinfo = OpInfo(\n lambda fd: fd.ops.erfinv,\n \"erfinv\",\n dtypes=int_float_dtypes,\n domain=Domain(-1, 1),\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.erfinv),\n is_clonable=True,\n)\nunary_ops.append(erfinv_opinfo)\n\nexp_opinfo = OpInfo(\n lambda fd: fd.ops.exp,\n \"exp\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.exp),\n is_clonable=True,\n)\nunary_ops.append(exp_opinfo)\n\nexp2_opinfo = OpInfo(\n lambda fd: fd.ops.exp2,\n \"exp2\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.exp2),\n is_clonable=True,\n)\nunary_ops.append(exp2_opinfo)\n\nexpm1_opinfo = OpInfo(\n lambda fd: fd.ops.expm1,\n \"expm1\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.expm1),\n is_clonable=True,\n)\nunary_ops.append(expm1_opinfo)\n\n# TODO add nvfuser exception for int dtypes\nfloor_opinfo = OpInfo(\n lambda fd: fd.ops.floor,\n \"floor\",\n dtypes=full_precision_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.floor),\n is_clonable=True,\n)\nunary_ops.append(floor_opinfo)\n\nfrac_opinfo = OpInfo(\n lambda fd: fd.ops.frac,\n \"frac\",\n dtypes=full_precision_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.frac),\n is_clonable=True,\n)\nunary_ops.append(frac_opinfo)\n\nisfinite_opinfo = OpInfo(\n lambda fd: fd.ops.isfinite,\n \"isfinite\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.isfinite),\n is_clonable=True,\n)\nunary_ops.append(isfinite_opinfo)\n\nisinf_opinfo = OpInfo(\n lambda fd: fd.ops.isinf,\n \"isinf\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.isinf),\n is_clonable=True,\n)\nunary_ops.append(isinf_opinfo)\n\nisnan_opinfo = OpInfo(\n lambda fd: fd.ops.isnan,\n \"isnan\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.isnan),\n is_clonable=True,\n)\nunary_ops.append(isnan_opinfo)\n\n# NOTE half-precision floating types are not automatically promoted to fp32\nisneginf_opinfo = OpInfo(\n lambda fd: fd.ops.isneginf,\n \"isneginf\",\n dtypes=full_precision_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.isneginf),\n is_clonable=True,\n)\nunary_ops.append(isneginf_opinfo)\n\n# NOTE half-precision floating types are not automatically promoted to fp32\nisposinf_opinfo = OpInfo(\n lambda fd: fd.ops.isposinf,\n \"isposinf\",\n dtypes=full_precision_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.isposinf),\n is_clonable=True,\n)\nunary_ops.append(isposinf_opinfo)\n\nisreal_opinfo = OpInfo(\n lambda fd: fd.ops.isreal,\n \"isreal\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.isreal),\n is_clonable=True,\n)\nunary_ops.append(isreal_opinfo)\n\nlgamma_opinfo = OpInfo(\n lambda fd: fd.ops.lgamma,\n \"lgamma\",\n dtypes=int_float_dtypes,\n domain=Domain(-1.0 + eps, math.inf),\n sample_input_generator=partial(elementwise_unary_generator, exclude_zero=True),\n reference=_elementwise_unary_torch(torch.lgamma),\n is_clonable=True,\n)\nunary_ops.append(lgamma_opinfo)\n\nlog_opinfo = OpInfo(\n lambda fd: fd.ops.log,\n \"log\",\n domain=Domain(0, math.inf),\n sample_input_generator=partial(elementwise_unary_generator, exclude_zero=True),\n reference=_elementwise_unary_torch(torch.log),\n is_clonable=True,\n)\nunary_ops.append(log_opinfo)\n\nlog10_opinfo = OpInfo(\n lambda fd: fd.ops.log10,\n \"log10\",\n dtypes=int_float_dtypes,\n domain=Domain(0, math.inf),\n sample_input_generator=partial(elementwise_unary_generator, exclude_zero=True),\n reference=_elementwise_unary_torch(torch.log10),\n is_clonable=True,\n)\nunary_ops.append(log10_opinfo)\n\nlog1p_opinfo = OpInfo(\n lambda fd: fd.ops.log1p,\n \"log1p\",\n dtypes=int_float_dtypes,\n domain=Domain(-1 + eps, math.inf),\n sample_input_generator=partial(elementwise_unary_generator, exclude_zero=True),\n reference=_elementwise_unary_torch(torch.log1p),\n is_clonable=True,\n)\nunary_ops.append(log1p_opinfo)\n\nlog2_opinfo = OpInfo(\n lambda fd: fd.ops.log2,\n \"log2\",\n domain=Domain(0, math.inf),\n sample_input_generator=partial(elementwise_unary_generator, exclude_zero=True),\n reference=_elementwise_unary_torch(torch.log2),\n is_clonable=True,\n)\nunary_ops.append(log2_opinfo)\n\nneg_opinfo = OpInfo(\n lambda fd: fd.ops.neg,\n \"neg\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.neg),\n is_clonable=True,\n)\nunary_ops.append(neg_opinfo)\n\nreciprocal_opinfo = OpInfo(\n lambda fd: fd.ops.reciprocal,\n \"reciprocal\",\n domain=Domain(0 + eps, math.inf),\n sample_input_generator=partial(\n elementwise_unary_generator,\n enable_small_value_testing=False,\n enable_extremal_value_testing=False,\n exclude_zero=True,\n ),\n reference=_elementwise_unary_torch(torch.reciprocal),\n is_clonable=True,\n)\nunary_ops.append(reciprocal_opinfo)\n\n# TODO add nvfuser exception for int dtypes\nround_opinfo = OpInfo(\n lambda fd: fd.ops.round,\n \"round\",\n dtypes=full_precision_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.round),\n is_clonable=True,\n)\nunary_ops.append(round_opinfo)\n\nrsqrt_opinfo = OpInfo(\n lambda fd: fd.ops.rsqrt,\n \"rsqrt\",\n domain=Domain(0 + eps, math.inf),\n sample_input_generator=partial(\n elementwise_unary_generator,\n enable_small_value_testing=False,\n enable_extremal_value_testing=False,\n exclude_zero=True,\n ),\n reference=_elementwise_unary_torch(torch.rsqrt),\n is_clonable=True,\n)\nunary_ops.append(rsqrt_opinfo)\n\nsigmoid_opinfo = OpInfo(\n lambda fd: fd.ops.sigmoid,\n \"sigmoid\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.sigmoid),\n is_clonable=True,\n)\nunary_ops.append(sigmoid_opinfo)\n\nsignbit_opinfo = OpInfo(\n lambda fd: fd.ops.signbit,\n \"signbit\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.signbit),\n is_clonable=True,\n)\nunary_ops.append(signbit_opinfo)\n\nsin_opinfo = OpInfo(\n lambda fd: fd.ops.sin,\n \"sin\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.sin),\n is_clonable=True,\n)\nunary_ops.append(sin_opinfo)\n\nsinh_opinfo = OpInfo(\n lambda fd: fd.ops.sinh,\n \"sinh\",\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.sinh),\n is_clonable=True,\n)\nunary_ops.append(sinh_opinfo)\n\nsqrt_opinfo = OpInfo(\n lambda fd: fd.ops.sqrt,\n \"sqrt\",\n domain=Domain(0, math.inf),\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.sqrt),\n is_clonable=True,\n)\nunary_ops.append(sqrt_opinfo)\n\ntan_opinfo = OpInfo(\n lambda fd: fd.ops.tan,\n \"tan\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.tan),\n is_clonable=True,\n)\nunary_ops.append(tan_opinfo)\n\ntanh_opinfo = OpInfo(\n lambda fd: fd.ops.tanh,\n \"tanh\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.tanh),\n is_clonable=True,\n)\nunary_ops.append(tanh_opinfo)\n\n# TODO add nvfuser exception for int dtypes\ntrunc_opinfo = OpInfo(\n lambda fd: fd.ops.trunc,\n \"trunc\",\n dtypes=full_precision_float_dtypes,\n sample_input_generator=elementwise_unary_generator,\n reference=_elementwise_unary_torch(torch.trunc),\n is_clonable=True,\n)\nunary_ops.append(trunc_opinfo)\n\n\"\"\" End Unary-Float Operations \"\"\"\n\n\"\"\" Start Binary Operations \"\"\"\n\n# atan2 --- promote int to float; allows fp16 and bf16\n# nextafter, truediv --- promote int to float; requires full-precision fp32, fp64\n# ceildiv, div, fmod, mod, remainder, truediv --- except_zero\n# add, mul, pow, sub\n# bitwise_and, bitwise_or, bitwise_xor --- bool_int_only\n# bitwise_left_shift, bitwise_right_shift, logical_right_shift --- int_only\n# eq, ne, ge, gt, le, lt --- compare\n\n# TODO Add \"ceildiv\" to python_frontend\n# TODO Add support for python reference for \"mod\".\n# TODO atan2 - complex dtypes are unsupported, but we fail when compiling kernel\n# TODO logical_right_shift - domain of shift parameter is non-zero; Otherwise the result is undefined.\n\n\nbinary_ops = []\n\nadd_opinfo = OpInfo(\n lambda fd: fd.ops.add,\n \"add\",\n sample_input_generator=partial(\n elementwise_binary_generator, enable_extremal_value_testing=False\n ),\n reference=_elementwise_binary_torch(torch.add),\n is_clonable=True,\n)\nbinary_ops.append(add_opinfo)\n\n# TODO complex dtypes are unsupported, but we fail when compiling kernel\natan2_opinfo = OpInfo(\n lambda fd: fd.ops.atan2,\n \"atan2\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.atan2),\n is_clonable=True,\n)\nbinary_ops.append(atan2_opinfo)\n\nbitwise_and_opinfo = OpInfo(\n lambda fd: fd.ops.bitwise_and,\n \"bitwise_and\",\n dtypes=bool_int_dtypes,\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.bitwise_and),\n is_clonable=True,\n)\nbinary_ops.append(bitwise_and_opinfo)\n\nbitwise_left_shift_opinfo = OpInfo(\n lambda fd: fd.ops.bitwise_left_shift,\n \"bitwise_left_shift\",\n dtypes=int_dtypes,\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.bitwise_left_shift),\n is_clonable=True,\n)\nbinary_ops.append(bitwise_left_shift_opinfo)\n\nbitwise_or_opinfo = OpInfo(\n lambda fd: fd.ops.bitwise_or,\n \"bitwise_or\",\n dtypes=bool_int_dtypes,\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.bitwise_or),\n is_clonable=True,\n)\nbinary_ops.append(bitwise_or_opinfo)\n\nbitwise_right_shift_opinfo = OpInfo(\n lambda fd: fd.ops.bitwise_right_shift,\n \"bitwise_right_shift\",\n dtypes=int_dtypes,\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.bitwise_right_shift),\n is_clonable=True,\n)\nbinary_ops.append(bitwise_right_shift_opinfo)\n\nbitwise_xor_opinfo = OpInfo(\n lambda fd: fd.ops.bitwise_xor,\n \"bitwise_xor\",\n dtypes=bool_int_dtypes,\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.bitwise_xor),\n is_clonable=True,\n)\nbinary_ops.append(bitwise_xor_opinfo)\n\ndiv_opinfo = OpInfo(\n lambda fd: fd.ops.div,\n \"div\",\n dtypes=float_complex_dtypes,\n sample_input_generator=div_input_generator,\n reference=_elementwise_binary_torch(torch.div),\n is_clonable=True,\n)\nbinary_ops.append(div_opinfo)\n\neq_opinfo = OpInfo(\n lambda fd: fd.ops.eq,\n \"eq\",\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.eq),\n is_clonable=True,\n)\nbinary_ops.append(eq_opinfo)\n\nfmod_opinfo = OpInfo(\n lambda fd: fd.ops.fmod,\n \"fmod\",\n dtypes=int_float_dtypes,\n sample_input_generator=partial(elementwise_binary_generator, exclude_zero=True),\n reference=_elementwise_binary_torch(torch.fmod),\n is_clonable=True,\n)\nbinary_ops.append(fmod_opinfo)\n\nge_opinfo = OpInfo(\n lambda fd: fd.ops.ge,\n \"ge\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.ge),\n is_clonable=True,\n)\nbinary_ops.append(ge_opinfo)\n\ngt_opinfo = OpInfo(\n lambda fd: fd.ops.gt,\n \"gt\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.gt),\n is_clonable=True,\n)\nbinary_ops.append(gt_opinfo)\n\nle_opinfo = OpInfo(\n lambda fd: fd.ops.le,\n \"le\",\n dtypes=int_float_dtypes,\n sample_input_generator=elementwise_binary_generator,\n reference=_elementwise_binary_torch(torch.le),\n is_clonable=True,\n)\nbinary_ops.append(le_opinfo)\n\n# TODO domain of shift parameter greater than zero; Otherwise the result is undefined.\nlogical_right_shift_opinfo = OpInfo(\n lambda fd: fd.ops.logical_right_shift,\n \"logical_right_shift\",\n domain=Domain(0, None),\n dtypes=int_dtypes,\n sample_input_generator=partial(\n elementwise_binary_generator,\n enable_broadcast_testing=False,\n enable_extremal_value_testing=False,\n enable_large_value_testing=False,\n enable_small_value_testing=False,\n ),\n reference=jax.lax.shift_right_logical if JAX_AVAILA\n# ... truncated ...","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.broadcast_in_dim_sym_fn","uri":"program://Fuser/function/tests.python.opinfo.opinfos.broadcast_in_dim_sym_fn#L987-L988","kind":"function","name":"broadcast_in_dim_sym_fn","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":987,"end_line":988,"context_start_line":967,"context_end_line":1008,"code":"broadcast_in_dim_constant_opinfo = OpInfo(\n lambda fd: fd.ops.broadcast_in_dim,\n \"broadcast_in_dim_constant\",\n sample_input_generator=broadcast_in_dim_generator,\n error_input_generator=broadcast_in_dim_error_generator,\n reference=jax.lax.broadcast_in_dim if JAX_AVAILABLE else None,\n reference_type=ReferenceType.Jax,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n # This argument is purposely Constant even though the positional\n # argument can also be symbolic.\n ArgumentType.Constant,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(broadcast_in_dim_constant_opinfo)\n\n\n# NOTE: The symbolic version of broadcast_in_dim opinfo tests the \"shape\"\n# argument with a Vector generated from another operation like ops.shape.\ndef broadcast_in_dim_sym_fn(fd, arg1, arg2, broadcast_dims):\n return fd.ops.broadcast_in_dim(arg1, arg2.shape(), broadcast_dims)\n\n\ndef jax_broadcast_in_dim_fn(arg1, arg2, broadcast_dims):\n return jax.lax.broadcast_in_dim(arg1, jax.numpy.shape(arg2), broadcast_dims)\n\n\nbroadcast_in_dim_symbolic_opinfo = OpInfo(\n lambda fd: partial(broadcast_in_dim_sym_fn, fd),\n \"broadcast_in_dim_symbolic\",\n sample_input_generator=broadcast_in_dim_generator,\n error_input_generator=broadcast_in_dim_error_generator,\n reference=jax_broadcast_in_dim_fn if JAX_AVAILABLE else None,\n reference_type=ReferenceType.Jax,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(broadcast_in_dim_symbolic_opinfo)","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.jax_broadcast_in_dim_fn","uri":"program://Fuser/function/tests.python.opinfo.opinfos.jax_broadcast_in_dim_fn#L991-L992","kind":"function","name":"jax_broadcast_in_dim_fn","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":991,"end_line":992,"context_start_line":971,"context_end_line":1012,"code":" error_input_generator=broadcast_in_dim_error_generator,\n reference=jax.lax.broadcast_in_dim if JAX_AVAILABLE else None,\n reference_type=ReferenceType.Jax,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n # This argument is purposely Constant even though the positional\n # argument can also be symbolic.\n ArgumentType.Constant,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(broadcast_in_dim_constant_opinfo)\n\n\n# NOTE: The symbolic version of broadcast_in_dim opinfo tests the \"shape\"\n# argument with a Vector generated from another operation like ops.shape.\ndef broadcast_in_dim_sym_fn(fd, arg1, arg2, broadcast_dims):\n return fd.ops.broadcast_in_dim(arg1, arg2.shape(), broadcast_dims)\n\n\ndef jax_broadcast_in_dim_fn(arg1, arg2, broadcast_dims):\n return jax.lax.broadcast_in_dim(arg1, jax.numpy.shape(arg2), broadcast_dims)\n\n\nbroadcast_in_dim_symbolic_opinfo = OpInfo(\n lambda fd: partial(broadcast_in_dim_sym_fn, fd),\n \"broadcast_in_dim_symbolic\",\n sample_input_generator=broadcast_in_dim_generator,\n error_input_generator=broadcast_in_dim_error_generator,\n reference=jax_broadcast_in_dim_fn if JAX_AVAILABLE else None,\n reference_type=ReferenceType.Jax,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(broadcast_in_dim_symbolic_opinfo)\n\n\n# translate between nvfuser and pytorch argument order for scatter\ndef scatter_wrapper(","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.scatter_wrapper","uri":"program://Fuser/function/tests.python.opinfo.opinfos.scatter_wrapper#L1012-L1015","kind":"function","name":"scatter_wrapper","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1012,"end_line":1015,"context_start_line":992,"context_end_line":1035,"code":" return jax.lax.broadcast_in_dim(arg1, jax.numpy.shape(arg2), broadcast_dims)\n\n\nbroadcast_in_dim_symbolic_opinfo = OpInfo(\n lambda fd: partial(broadcast_in_dim_sym_fn, fd),\n \"broadcast_in_dim_symbolic\",\n sample_input_generator=broadcast_in_dim_generator,\n error_input_generator=broadcast_in_dim_error_generator,\n reference=jax_broadcast_in_dim_fn if JAX_AVAILABLE else None,\n reference_type=ReferenceType.Jax,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(broadcast_in_dim_symbolic_opinfo)\n\n\n# translate between nvfuser and pytorch argument order for scatter\ndef scatter_wrapper(\n fn: callable, input: torch.Tensor, index: torch.Tensor, src: torch.Tensor, dim: int\n):\n return fn(input, dim, index, src)\n\n\nscatter_opinfo = OpInfo(\n lambda fd: fd.ops.scatter,\n \"scatter\",\n sample_input_generator=scatter_generator,\n reference=partial(scatter_wrapper, torch.scatter),\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(scatter_opinfo)\n\n\n# translate between nvfuser and pytorch argument order for gather, take_along_dim, and index_select\ndef gather_wrapper(fn: callable, input: torch.Tensor, index: torch.Tensor, dim: int):\n return fn(input, dim, index)","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.gather_wrapper","uri":"program://Fuser/function/tests.python.opinfo.opinfos.gather_wrapper#L1034-L1035","kind":"function","name":"gather_wrapper","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1034,"end_line":1035,"context_start_line":1014,"context_end_line":1055,"code":"):\n return fn(input, dim, index, src)\n\n\nscatter_opinfo = OpInfo(\n lambda fd: fd.ops.scatter,\n \"scatter\",\n sample_input_generator=scatter_generator,\n reference=partial(scatter_wrapper, torch.scatter),\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(scatter_opinfo)\n\n\n# translate between nvfuser and pytorch argument order for gather, take_along_dim, and index_select\ndef gather_wrapper(fn: callable, input: torch.Tensor, index: torch.Tensor, dim: int):\n return fn(input, dim, index)\n\n\ngather_opinfo = OpInfo(\n lambda fd: fd.ops.gather,\n \"gather\",\n sample_input_generator=gather_generator,\n error_input_generator=take_along_axis_error_generator,\n reference=partial(gather_wrapper, torch.gather),\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(gather_opinfo)\n\nindex_select_opinfo = OpInfo(\n lambda fd: fd.ops.index_select,\n \"index_select\",\n sample_input_generator=index_select_generator,","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.argsort_ref","uri":"program://Fuser/function/tests.python.opinfo.opinfos.argsort_ref#L1068-L1069","kind":"function","name":"argsort_ref","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1068,"end_line":1069,"context_start_line":1048,"context_end_line":1089,"code":" ),\n)\nshape_ops.append(gather_opinfo)\n\nindex_select_opinfo = OpInfo(\n lambda fd: fd.ops.index_select,\n \"index_select\",\n sample_input_generator=index_select_generator,\n error_input_generator=index_select_error_generator,\n reference=partial(gather_wrapper, torch.index_select),\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(index_select_opinfo)\n\n\n# we needed a reference because argsort requires kwargs.\ndef argsort_ref(a, dim, descending, stable):\n return torch.argsort(a, dim=dim, descending=descending, stable=stable)\n\n\nargsort_opinfo = OpInfo(\n lambda fd: fd.ops.argsort,\n \"argsort\",\n # TODO: complex dtypes are not supported by aten fallback\n dtypes=(int_float_dtypes),\n sample_input_generator=argsort_generator,\n reference=argsort_ref,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(argsort_opinfo)\n\n\ntopk_opinfo = OpInfo(","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.index_put_accumulate_ref","uri":"program://Fuser/function/tests.python.opinfo.opinfos.index_put_accumulate_ref#L1107-L1117","kind":"function","name":"index_put_accumulate_ref","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1107,"end_line":1117,"context_start_line":1087,"context_end_line":1137,"code":"\n\ntopk_opinfo = OpInfo(\n lambda fd: fd.ops.topk,\n \"topk\",\n dtypes=(int_float_dtypes),\n sample_input_generator=topk_generator,\n error_input_generator=topk_error_generator,\n reference=torch.topk,\n symbolic_parameter_list=(\n ArgumentType.Symbolic, # input tensor\n ArgumentType.Symbolic, # k (number of elements)\n ArgumentType.Constant, # dim\n ArgumentType.Constant, # largest\n ArgumentType.Constant, # sorted\n ),\n)\nshape_ops.append(topk_opinfo)\n\n\ndef index_put_accumulate_ref(\n acc: torch.Tensor, index: torch.Tensor, value: torch.Tensor\n):\n return torch.index_put(\n acc,\n [\n index,\n ],\n value,\n accumulate=True,\n )\n\n\nindex_put_accumulate_opinfo = OpInfo(\n lambda fd: fd.ops.index_put_accumulate,\n \"index_put_accumulate\",\n sample_input_generator=index_put_accumulate_generator,\n reference=index_put_accumulate_ref,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ),\n # index_put_accumulate is not used in Thunder, so skip in direct bindings for now.\n supports_direct_bindings=False,\n)\nshape_ops.append(index_put_accumulate_opinfo)\n\n# NvFuser's API is significantly different than JAX.\n# TODO: Change python frontend api to match JAX using a cpp wrapper function.\npad_opinfo = OpInfo(","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.reshape_sym_fn","uri":"program://Fuser/function/tests.python.opinfo.opinfos.reshape_sym_fn#L1175-L1176","kind":"function","name":"reshape_sym_fn","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1175,"end_line":1176,"context_start_line":1155,"context_end_line":1196,"code":" reference=torch.permute,\n symbolic_parameter_list=(ArgumentType.Symbolic, ArgumentType.Constant),\n)\nshape_ops.append(permute_opinfo)\n\n\nreshape_constant_opinfo = OpInfo(\n lambda fd: fd.ops.reshape,\n \"reshape_constant\",\n sample_input_generator=reshape_generator,\n error_input_generator=reshape_error_generator,\n reference=torch.reshape,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(reshape_constant_opinfo)\n\n\ndef reshape_sym_fn(fd, input_tensor, output_shaped_tensor):\n return fd.ops.reshape(input_tensor, output_shaped_tensor.shape())\n\n\ndef torch_reshape_sym_fn(input_tensor, output_shaped_tensor):\n return torch.reshape(input_tensor, output_shaped_tensor.size())\n\n\nreshape_symbolic_opinfo = OpInfo(\n lambda fd: partial(reshape_sym_fn, fd),\n \"reshape_symbolic\",\n sample_input_generator=reshape_generator,\n error_input_generator=reshape_error_generator,\n reference=torch_reshape_sym_fn,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ),\n)\nshape_ops.append(reshape_symbolic_opinfo)\n\n","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.torch_reshape_sym_fn","uri":"program://Fuser/function/tests.python.opinfo.opinfos.torch_reshape_sym_fn#L1179-L1180","kind":"function","name":"torch_reshape_sym_fn","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1179,"end_line":1180,"context_start_line":1159,"context_end_line":1200,"code":"\n\nreshape_constant_opinfo = OpInfo(\n lambda fd: fd.ops.reshape,\n \"reshape_constant\",\n sample_input_generator=reshape_generator,\n error_input_generator=reshape_error_generator,\n reference=torch.reshape,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ),\n)\nshape_ops.append(reshape_constant_opinfo)\n\n\ndef reshape_sym_fn(fd, input_tensor, output_shaped_tensor):\n return fd.ops.reshape(input_tensor, output_shaped_tensor.shape())\n\n\ndef torch_reshape_sym_fn(input_tensor, output_shaped_tensor):\n return torch.reshape(input_tensor, output_shaped_tensor.size())\n\n\nreshape_symbolic_opinfo = OpInfo(\n lambda fd: partial(reshape_sym_fn, fd),\n \"reshape_symbolic\",\n sample_input_generator=reshape_generator,\n error_input_generator=reshape_error_generator,\n reference=torch_reshape_sym_fn,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ),\n)\nshape_ops.append(reshape_symbolic_opinfo)\n\n\nslice_opinfo = OpInfo(\n lambda fd: fd.ops.slice,\n \"slice\",\n sample_input_generator=slice_generator,","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.scaled_grouped_mm_wrapper","uri":"program://Fuser/function/tests.python.opinfo.opinfos.scaled_grouped_mm_wrapper#L1328-L1351","kind":"function","name":"scaled_grouped_mm_wrapper","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1328,"end_line":1351,"context_start_line":1308,"context_end_line":1371,"code":" (torch.float16, torch.bfloat16)\n if torch.cuda.get_device_properties(torch.cuda.current_device()).major >= 8\n else (torch.float16,)\n ),\n sample_input_generator=matmul_input_generator,\n reference=torch.matmul,\n)\nmatmul_ops.append(matmul_opinfo)\n\n# torch._grouped_mm and torch._scaled_grouped_mm is not available prior to PyTorch 2.8.0\nif LooseVersion(torch.__version__) >= LooseVersion(\"2.8.0\"):\n grouped_mm_opinfo = OpInfo(\n lambda fd: fd.ops.grouped_mm,\n \"grouped_mm\",\n # only bf16 is supported\n dtypes=(torch.bfloat16,),\n sample_input_generator=grouped_mm_input_generator,\n reference=torch._grouped_mm,\n )\n\n def scaled_grouped_mm_wrapper(\n mat1, mat2, offsets, scale1, scale2, alpha, bias, beta, dtype\n ):\n assert beta is None\n # mat1 needs to be in column major while mat2 needs to be in row major.\n row_major_mat2 = mat2.transpose(-1, -2).contiguous().transpose(-1, -2)\n if mat1.ndim == 2 and mat2.ndim == 2:\n # case 1, mat1 and mat2 are both 2D, aten fallback expects collapsed 1D scale with group dimension on the slower side.\n reshaped_scale1 = scale1.reshape(-1)\n reshaped_scale2 = scale2.reshape(-1)\n else:\n # squeeze out the k dimension\n reshaped_scale1 = scale1.squeeze(-1)\n reshaped_scale2 = scale2.squeeze(-2)\n return torch._scaled_grouped_mm(\n mat1,\n row_major_mat2,\n reshaped_scale1,\n reshaped_scale2,\n offsets,\n bias,\n alpha,\n dtype,\n )\n\n scaled_grouped_mm_opinfo = OpInfo(\n lambda fd: fd.ops.grouped_mm,\n \"scaled_grouped_mm\",\n # only float8 is supported\n dtypes=(torch.float8_e4m3fn,),\n sample_input_generator=scaled_grouped_mm_input_generator,\n reference=scaled_grouped_mm_wrapper,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ),\n )","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfos.scaled_mm_wrapper","uri":"program://Fuser/function/tests.python.opinfo.opinfos.scaled_mm_wrapper#L1373-L1377","kind":"function","name":"scaled_mm_wrapper","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1373,"end_line":1377,"context_start_line":1353,"context_end_line":1397,"code":" scaled_grouped_mm_opinfo = OpInfo(\n lambda fd: fd.ops.grouped_mm,\n \"scaled_grouped_mm\",\n # only float8 is supported\n dtypes=(torch.float8_e4m3fn,),\n sample_input_generator=scaled_grouped_mm_input_generator,\n reference=scaled_grouped_mm_wrapper,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ),\n )\n\n def scaled_mm_wrapper(mat1, mat2, scale1, scale2, alpha, bias, beta, dtype):\n assert beta is None\n return torch._scaled_mm(\n mat1, mat2, scale1, scale2, bias, alpha, out_dtype=dtype\n )\n\n scaled_mm_opinfo = OpInfo(\n lambda fd: fd.ops.scaled_mm,\n \"scaled_mm\",\n # limit test to mxfp8 for now\n dtypes=(torch.float8_e4m3fn,),\n sample_input_generator=scaled_mm_input_generator,\n reference=scaled_mm_wrapper,\n symbolic_parameter_list=(\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Symbolic,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ArgumentType.Constant,\n ),\n )\n","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils","uri":"program://Fuser/module/tests.python.opinfo.opinfo_utils#L1-L184","kind":"module","name":"tests.python.opinfo.opinfo_utils","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":1,"end_line":184,"context_start_line":1,"context_end_line":184,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom torch.testing import make_tensor\nfrom enum import Enum, auto\nfrom typing import Optional\nfrom functools import wraps\n\ntry:\n # flake8: noqa\n import jax\n\n JAX_AVAILABLE = True\nexcept ImportError as e:\n JAX_AVAILABLE = False\n pass\n\n\ndef requiresJAX(fn):\n @wraps(fn)\n def _fn(*args, **kwargs):\n if not JAX_AVAILABLE:\n pytest.xfail(\"Requires JAX\")\n return fn(*args, **kwargs)\n\n return _fn\n\n\nclass ArgumentType(Enum):\n # a symbolic value requires an input argument during kernel execution\n Symbolic = auto()\n # scalar with constant value\n ConstantScalar = auto()\n # python number - int, float, complex, bool\n Constant = auto()\n\n\nbool_dtypes = (torch.bool,)\n\nint_dtypes = (\n torch.int32,\n torch.int64,\n)\n\nhalf_precision_float_dtypes = (\n torch.bfloat16,\n torch.float16,\n)\n\nfull_precision_float_dtypes = (\n torch.float32,\n torch.float64,\n)\n\ncomplex_dtypes = (\n torch.complex64,\n torch.complex128,\n)\n\n# Half-precision float dtypes bf16, fp16 are skipped because nvfuser upcasts those dtypes to fp32\n# but does not return the original type.\nbool_int_dtypes = bool_dtypes + int_dtypes\nfloat_dtypes = half_precision_float_dtypes + full_precision_float_dtypes\nint_float_dtypes = int_dtypes + full_precision_float_dtypes\nfloat_complex_dtypes = full_precision_float_dtypes + complex_dtypes\nall_dtypes_except_reduced = int_dtypes + full_precision_float_dtypes + complex_dtypes\nall_dtypes_except_bool = all_dtypes_except_reduced + half_precision_float_dtypes\nall_dtypes = all_dtypes_except_bool + bool_dtypes\n\nmap_dtype_to_str = {\n torch.bool: \"bool\",\n torch.uint8: \"uint8\",\n torch.int8: \"int8\",\n torch.int16: \"int16\",\n torch.int32: \"int32\",\n torch.int64: \"int64\",\n torch.float8_e4m3fn: \"float8_e4m3fn\",\n torch.float8_e5m2: \"float8_e5m2\",\n torch.float8_e8m0fnu: \"float8_e8m0fnu\",\n torch.bfloat16: \"bfloat16\",\n torch.float16: \"float16\",\n torch.float32: \"float32\",\n torch.float64: \"float64\",\n torch.complex64: \"complex64\",\n torch.complex128: \"complex128\",\n}\n\nif hasattr(torch, \"float4_e2m1fn_x2\"):\n map_dtype_to_str[torch.float4_e2m1fn_x2] = \"float4_e2m1fn_x2\"\n\ntorch_to_jax_dtype_map = None\nif JAX_AVAILABLE:\n import jax.numpy as jnp\n\n torch_to_jax_dtype_map = {\n torch.bool: jnp.bool_,\n torch.uint8: jnp.uint8,\n torch.int8: jnp.int8,\n torch.int16: jnp.int16,\n torch.int32: jnp.int32,\n torch.int64: jnp.int64,\n torch.bfloat16: jnp.bfloat16,\n torch.float16: jnp.float16,\n torch.float32: jnp.float32,\n torch.float64: jnp.float64,\n torch.complex64: jnp.complex64,\n torch.complex128: jnp.complex128,\n }\n\ntorch_to_python_dtype_map = {\n torch.bool: bool,\n torch.uint8: int,\n torch.int8: int,\n torch.int16: int,\n torch.int32: int,\n torch.int64: int,\n torch.bfloat16: float,\n torch.float16: float,\n torch.float32: float,\n torch.float64: float,\n torch.complex64: complex,\n torch.complex128: complex,\n}\n\n\ndef make_tensor_like(a):\n # type: (torch.Tensor) -> torch.Tensor\n \"\"\"Returns a tensor with the same properties as the given tensor.\n\n Args:\n a (torch.Tensor): The tensor to copy properties from.\n\n Returns:\n torch.Tensor: A tensor with the same properties as :attr:`a`.\n \"\"\"\n return torch.testing.make_tensor(\n a.shape, device=a.device, dtype=a.dtype, requires_grad=a.requires_grad\n )\n\n\ndef make_number(\n dtype: torch.dtype, low: Optional[float] = None, high: Optional[float] = None\n):\n \"\"\"Returns a random number with desired dtype\n\n Args:\n dtype (torch.dtype): Desired dtype for number.\n low (Optional[Number]): Sets the lower limit (inclusive) of the given range.\n high (Optional[Number]): Sets the upper limit (exclusive) of the given range.\n\n Returns:\n (Scalar): The scalar number with specified dtype.\n \"\"\"\n return make_tensor([1], device=\"cpu\", dtype=dtype, low=low, high=high).item()\n\n\ndef find_nonmatching_dtype(dtype: torch.dtype):\n if dtype in int_float_dtypes:\n return torch.complex128\n elif dtype in complex_dtypes:\n return torch.double\n elif dtype is torch.bool:\n return torch.float32\n return None\n\n\ndef is_complex_dtype(dtype: torch.dtype):\n return dtype in complex_dtypes\n\n\ndef is_floating_dtype(dtype: torch.dtype):\n return dtype in float_dtypes\n\n\ndef is_integer_dtype(dtype: torch.dtype):\n return dtype in int_dtypes\n\n\ndef is_tensor(a):\n return isinstance(a, torch.Tensor)","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils.requiresJAX","uri":"program://Fuser/function/tests.python.opinfo.opinfo_utils.requiresJAX#L23-L30","kind":"function","name":"requiresJAX","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":23,"end_line":30,"context_start_line":3,"context_end_line":50,"code":"# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom torch.testing import make_tensor\nfrom enum import Enum, auto\nfrom typing import Optional\nfrom functools import wraps\n\ntry:\n # flake8: noqa\n import jax\n\n JAX_AVAILABLE = True\nexcept ImportError as e:\n JAX_AVAILABLE = False\n pass\n\n\ndef requiresJAX(fn):\n @wraps(fn)\n def _fn(*args, **kwargs):\n if not JAX_AVAILABLE:\n pytest.xfail(\"Requires JAX\")\n return fn(*args, **kwargs)\n\n return _fn\n\n\nclass ArgumentType(Enum):\n # a symbolic value requires an input argument during kernel execution\n Symbolic = auto()\n # scalar with constant value\n ConstantScalar = auto()\n # python number - int, float, complex, bool\n Constant = auto()\n\n\nbool_dtypes = (torch.bool,)\n\nint_dtypes = (\n torch.int32,\n torch.int64,\n)\n\nhalf_precision_float_dtypes = (\n torch.bfloat16,","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils.ArgumentType","uri":"program://Fuser/class/tests.python.opinfo.opinfo_utils.ArgumentType#L33-L39","kind":"class","name":"ArgumentType","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":33,"end_line":39,"context_start_line":13,"context_end_line":59,"code":"try:\n # flake8: noqa\n import jax\n\n JAX_AVAILABLE = True\nexcept ImportError as e:\n JAX_AVAILABLE = False\n pass\n\n\ndef requiresJAX(fn):\n @wraps(fn)\n def _fn(*args, **kwargs):\n if not JAX_AVAILABLE:\n pytest.xfail(\"Requires JAX\")\n return fn(*args, **kwargs)\n\n return _fn\n\n\nclass ArgumentType(Enum):\n # a symbolic value requires an input argument during kernel execution\n Symbolic = auto()\n # scalar with constant value\n ConstantScalar = auto()\n # python number - int, float, complex, bool\n Constant = auto()\n\n\nbool_dtypes = (torch.bool,)\n\nint_dtypes = (\n torch.int32,\n torch.int64,\n)\n\nhalf_precision_float_dtypes = (\n torch.bfloat16,\n torch.float16,\n)\n\nfull_precision_float_dtypes = (\n torch.float32,\n torch.float64,\n)\n\ncomplex_dtypes = (","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils.make_tensor_like","uri":"program://Fuser/function/tests.python.opinfo.opinfo_utils.make_tensor_like#L130-L142","kind":"function","name":"make_tensor_like","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":130,"end_line":142,"context_start_line":110,"context_end_line":162,"code":" torch.complex64: jnp.complex64,\n torch.complex128: jnp.complex128,\n }\n\ntorch_to_python_dtype_map = {\n torch.bool: bool,\n torch.uint8: int,\n torch.int8: int,\n torch.int16: int,\n torch.int32: int,\n torch.int64: int,\n torch.bfloat16: float,\n torch.float16: float,\n torch.float32: float,\n torch.float64: float,\n torch.complex64: complex,\n torch.complex128: complex,\n}\n\n\ndef make_tensor_like(a):\n # type: (torch.Tensor) -> torch.Tensor\n \"\"\"Returns a tensor with the same properties as the given tensor.\n\n Args:\n a (torch.Tensor): The tensor to copy properties from.\n\n Returns:\n torch.Tensor: A tensor with the same properties as :attr:`a`.\n \"\"\"\n return torch.testing.make_tensor(\n a.shape, device=a.device, dtype=a.dtype, requires_grad=a.requires_grad\n )\n\n\ndef make_number(\n dtype: torch.dtype, low: Optional[float] = None, high: Optional[float] = None\n):\n \"\"\"Returns a random number with desired dtype\n\n Args:\n dtype (torch.dtype): Desired dtype for number.\n low (Optional[Number]): Sets the lower limit (inclusive) of the given range.\n high (Optional[Number]): Sets the upper limit (exclusive) of the given range.\n\n Returns:\n (Scalar): The scalar number with specified dtype.\n \"\"\"\n return make_tensor([1], device=\"cpu\", dtype=dtype, low=low, high=high).item()\n\n\ndef find_nonmatching_dtype(dtype: torch.dtype):\n if dtype in int_float_dtypes:","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils.make_number","uri":"program://Fuser/function/tests.python.opinfo.opinfo_utils.make_number#L145-L158","kind":"function","name":"make_number","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":145,"end_line":158,"context_start_line":125,"context_end_line":178,"code":" torch.complex64: complex,\n torch.complex128: complex,\n}\n\n\ndef make_tensor_like(a):\n # type: (torch.Tensor) -> torch.Tensor\n \"\"\"Returns a tensor with the same properties as the given tensor.\n\n Args:\n a (torch.Tensor): The tensor to copy properties from.\n\n Returns:\n torch.Tensor: A tensor with the same properties as :attr:`a`.\n \"\"\"\n return torch.testing.make_tensor(\n a.shape, device=a.device, dtype=a.dtype, requires_grad=a.requires_grad\n )\n\n\ndef make_number(\n dtype: torch.dtype, low: Optional[float] = None, high: Optional[float] = None\n):\n \"\"\"Returns a random number with desired dtype\n\n Args:\n dtype (torch.dtype): Desired dtype for number.\n low (Optional[Number]): Sets the lower limit (inclusive) of the given range.\n high (Optional[Number]): Sets the upper limit (exclusive) of the given range.\n\n Returns:\n (Scalar): The scalar number with specified dtype.\n \"\"\"\n return make_tensor([1], device=\"cpu\", dtype=dtype, low=low, high=high).item()\n\n\ndef find_nonmatching_dtype(dtype: torch.dtype):\n if dtype in int_float_dtypes:\n return torch.complex128\n elif dtype in complex_dtypes:\n return torch.double\n elif dtype is torch.bool:\n return torch.float32\n return None\n\n\ndef is_complex_dtype(dtype: torch.dtype):\n return dtype in complex_dtypes\n\n\ndef is_floating_dtype(dtype: torch.dtype):\n return dtype in float_dtypes\n\n","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils.find_nonmatching_dtype","uri":"program://Fuser/function/tests.python.opinfo.opinfo_utils.find_nonmatching_dtype#L161-L168","kind":"function","name":"find_nonmatching_dtype","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":161,"end_line":168,"context_start_line":141,"context_end_line":184,"code":" a.shape, device=a.device, dtype=a.dtype, requires_grad=a.requires_grad\n )\n\n\ndef make_number(\n dtype: torch.dtype, low: Optional[float] = None, high: Optional[float] = None\n):\n \"\"\"Returns a random number with desired dtype\n\n Args:\n dtype (torch.dtype): Desired dtype for number.\n low (Optional[Number]): Sets the lower limit (inclusive) of the given range.\n high (Optional[Number]): Sets the upper limit (exclusive) of the given range.\n\n Returns:\n (Scalar): The scalar number with specified dtype.\n \"\"\"\n return make_tensor([1], device=\"cpu\", dtype=dtype, low=low, high=high).item()\n\n\ndef find_nonmatching_dtype(dtype: torch.dtype):\n if dtype in int_float_dtypes:\n return torch.complex128\n elif dtype in complex_dtypes:\n return torch.double\n elif dtype is torch.bool:\n return torch.float32\n return None\n\n\ndef is_complex_dtype(dtype: torch.dtype):\n return dtype in complex_dtypes\n\n\ndef is_floating_dtype(dtype: torch.dtype):\n return dtype in float_dtypes\n\n\ndef is_integer_dtype(dtype: torch.dtype):\n return dtype in int_dtypes\n\n\ndef is_tensor(a):\n return isinstance(a, torch.Tensor)","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils.is_complex_dtype","uri":"program://Fuser/function/tests.python.opinfo.opinfo_utils.is_complex_dtype#L171-L172","kind":"function","name":"is_complex_dtype","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":171,"end_line":172,"context_start_line":151,"context_end_line":184,"code":" dtype (torch.dtype): Desired dtype for number.\n low (Optional[Number]): Sets the lower limit (inclusive) of the given range.\n high (Optional[Number]): Sets the upper limit (exclusive) of the given range.\n\n Returns:\n (Scalar): The scalar number with specified dtype.\n \"\"\"\n return make_tensor([1], device=\"cpu\", dtype=dtype, low=low, high=high).item()\n\n\ndef find_nonmatching_dtype(dtype: torch.dtype):\n if dtype in int_float_dtypes:\n return torch.complex128\n elif dtype in complex_dtypes:\n return torch.double\n elif dtype is torch.bool:\n return torch.float32\n return None\n\n\ndef is_complex_dtype(dtype: torch.dtype):\n return dtype in complex_dtypes\n\n\ndef is_floating_dtype(dtype: torch.dtype):\n return dtype in float_dtypes\n\n\ndef is_integer_dtype(dtype: torch.dtype):\n return dtype in int_dtypes\n\n\ndef is_tensor(a):\n return isinstance(a, torch.Tensor)","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils.is_floating_dtype","uri":"program://Fuser/function/tests.python.opinfo.opinfo_utils.is_floating_dtype#L175-L176","kind":"function","name":"is_floating_dtype","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":175,"end_line":176,"context_start_line":155,"context_end_line":184,"code":" Returns:\n (Scalar): The scalar number with specified dtype.\n \"\"\"\n return make_tensor([1], device=\"cpu\", dtype=dtype, low=low, high=high).item()\n\n\ndef find_nonmatching_dtype(dtype: torch.dtype):\n if dtype in int_float_dtypes:\n return torch.complex128\n elif dtype in complex_dtypes:\n return torch.double\n elif dtype is torch.bool:\n return torch.float32\n return None\n\n\ndef is_complex_dtype(dtype: torch.dtype):\n return dtype in complex_dtypes\n\n\ndef is_floating_dtype(dtype: torch.dtype):\n return dtype in float_dtypes\n\n\ndef is_integer_dtype(dtype: torch.dtype):\n return dtype in int_dtypes\n\n\ndef is_tensor(a):\n return isinstance(a, torch.Tensor)","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils.is_integer_dtype","uri":"program://Fuser/function/tests.python.opinfo.opinfo_utils.is_integer_dtype#L179-L180","kind":"function","name":"is_integer_dtype","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":179,"end_line":180,"context_start_line":159,"context_end_line":184,"code":"\n\ndef find_nonmatching_dtype(dtype: torch.dtype):\n if dtype in int_float_dtypes:\n return torch.complex128\n elif dtype in complex_dtypes:\n return torch.double\n elif dtype is torch.bool:\n return torch.float32\n return None\n\n\ndef is_complex_dtype(dtype: torch.dtype):\n return dtype in complex_dtypes\n\n\ndef is_floating_dtype(dtype: torch.dtype):\n return dtype in float_dtypes\n\n\ndef is_integer_dtype(dtype: torch.dtype):\n return dtype in int_dtypes\n\n\ndef is_tensor(a):\n return isinstance(a, torch.Tensor)","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils.is_tensor","uri":"program://Fuser/function/tests.python.opinfo.opinfo_utils.is_tensor#L183-L184","kind":"function","name":"is_tensor","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":183,"end_line":184,"context_start_line":163,"context_end_line":184,"code":" return torch.complex128\n elif dtype in complex_dtypes:\n return torch.double\n elif dtype is torch.bool:\n return torch.float32\n return None\n\n\ndef is_complex_dtype(dtype: torch.dtype):\n return dtype in complex_dtypes\n\n\ndef is_floating_dtype(dtype: torch.dtype):\n return dtype in float_dtypes\n\n\ndef is_integer_dtype(dtype: torch.dtype):\n return dtype in int_dtypes\n\n\ndef is_tensor(a):\n return isinstance(a, torch.Tensor)","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.opinfo.opinfo_utils._fn","uri":"program://Fuser/function/tests.python.opinfo.opinfo_utils._fn#L25-L28","kind":"function","name":"_fn","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":25,"end_line":28,"context_start_line":5,"context_end_line":48,"code":"\nimport pytest\nimport torch\nfrom torch.testing import make_tensor\nfrom enum import Enum, auto\nfrom typing import Optional\nfrom functools import wraps\n\ntry:\n # flake8: noqa\n import jax\n\n JAX_AVAILABLE = True\nexcept ImportError as e:\n JAX_AVAILABLE = False\n pass\n\n\ndef requiresJAX(fn):\n @wraps(fn)\n def _fn(*args, **kwargs):\n if not JAX_AVAILABLE:\n pytest.xfail(\"Requires JAX\")\n return fn(*args, **kwargs)\n\n return _fn\n\n\nclass ArgumentType(Enum):\n # a symbolic value requires an input argument during kernel execution\n Symbolic = auto()\n # scalar with constant value\n ConstantScalar = auto()\n # python number - int, float, complex, bool\n Constant = auto()\n\n\nbool_dtypes = (torch.bool,)\n\nint_dtypes = (\n torch.int32,\n torch.int64,\n)\n","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.conftest","uri":"program://Fuser/module/tests.python.direct.conftest#L1-L99","kind":"module","name":"tests.python.direct.conftest","path":"tests/python/direct/conftest.py","language":"python","start_line":1,"end_line":99,"context_start_line":1,"context_end_line":99,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nfrom copy import deepcopy\nimport torch\nfrom torch.testing._internal.common_utils import TestCase\n\nfrom nvfuser_direct import FusionDefinition, LRUCache\nfrom python.direct_utils import is_pre_volta, check_captured_python_definition\n\n\nclass NVFuserTest(TestCase):\n def __init__(self, cache=None):\n super().__init__()\n self.cache = cache\n\n # Helper function to verify the nvfuser output and make sure the string\n # definition based on the FusionDefinition is executable and matches the\n # original definition\n def exec_nvfuser(\n self,\n fusion_func,\n inputs,\n *,\n new_fusion_expected=True,\n expected_fd_str=None,\n device=None,\n enable_options=None,\n disable_options=None,\n validate_results=False,\n ):\n # Copy inputs because aliased outputs can modify inputs when running\n # FusionDefinition\n inputs_captured = deepcopy(inputs)\n\n if self.cache is not None:\n prev_size = self.cache.num_fusions()\n\n # Run compilation twice to test lru cache; The number of fusions\n # should not increase during the second round.\n for _ in range(2):\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n fd.fec = self.cache.cache_compile(fd.fusion)\n del fd._fusion\n\n # The LRU cache is shared across all tests. If you run all the tests\n # together, a fusion can be cached from an earlier test. If you run\n # a test standalone, then the fusion will not exist. Skip this\n # assertion for this case but check that cache_compile works\n # correctly.\n if new_fusion_expected is not None:\n assert self.cache.num_fusions() == prev_size + int(new_fusion_expected)\n else:\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n # Execute a fusion function and capture the string python definition\n # Set manual_seed before running fusion to avoid mismatch results\n # with rng kernels\n torch.manual_seed(0)\n if validate_results:\n out = fd.validate(inputs)\n else:\n if enable_options is None:\n enable_options = []\n if disable_options is None:\n disable_options = []\n out = fd.execute(\n inputs,\n device=device,\n _enable_options=enable_options,\n _disable_options=disable_options,\n )\n\n assert check_captured_python_definition(\n out, fd, inputs_captured, device, enable_options, disable_options\n )\n assert expected_fd_str is None or expected_fd_str in repr(fd)\n return out, fd\n\n\n# Migrated tests to new direct python bindings use this.\n@pytest.fixture(params=[\"lru_cache\", \"eager\"])\ndef nvfuser_direct_test(request):\n if is_pre_volta():\n pytest.skip(\"Only supported on Volta and newer devices.\")\n\n cache_type = request.param\n if cache_type == \"lru_cache\":\n if not hasattr(nvfuser_direct_test, \"cache\"):\n nvfuser_direct_test.cache = LRUCache(max_fusions=16384)\n yield NVFuserTest(nvfuser_direct_test.cache)\n else:\n yield NVFuserTest()","source_hash":"a868b522b94ffe66899fc542b20baf53acdf618e326b56af07b7f9f2bf23b795","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.conftest.NVFuserTest","uri":"program://Fuser/class/tests.python.direct.conftest.NVFuserTest#L15-L84","kind":"class","name":"NVFuserTest","path":"tests/python/direct/conftest.py","language":"python","start_line":15,"end_line":84,"context_start_line":1,"context_end_line":99,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nfrom copy import deepcopy\nimport torch\nfrom torch.testing._internal.common_utils import TestCase\n\nfrom nvfuser_direct import FusionDefinition, LRUCache\nfrom python.direct_utils import is_pre_volta, check_captured_python_definition\n\n\nclass NVFuserTest(TestCase):\n def __init__(self, cache=None):\n super().__init__()\n self.cache = cache\n\n # Helper function to verify the nvfuser output and make sure the string\n # definition based on the FusionDefinition is executable and matches the\n # original definition\n def exec_nvfuser(\n self,\n fusion_func,\n inputs,\n *,\n new_fusion_expected=True,\n expected_fd_str=None,\n device=None,\n enable_options=None,\n disable_options=None,\n validate_results=False,\n ):\n # Copy inputs because aliased outputs can modify inputs when running\n # FusionDefinition\n inputs_captured = deepcopy(inputs)\n\n if self.cache is not None:\n prev_size = self.cache.num_fusions()\n\n # Run compilation twice to test lru cache; The number of fusions\n # should not increase during the second round.\n for _ in range(2):\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n fd.fec = self.cache.cache_compile(fd.fusion)\n del fd._fusion\n\n # The LRU cache is shared across all tests. If you run all the tests\n # together, a fusion can be cached from an earlier test. If you run\n # a test standalone, then the fusion will not exist. Skip this\n # assertion for this case but check that cache_compile works\n # correctly.\n if new_fusion_expected is not None:\n assert self.cache.num_fusions() == prev_size + int(new_fusion_expected)\n else:\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n # Execute a fusion function and capture the string python definition\n # Set manual_seed before running fusion to avoid mismatch results\n # with rng kernels\n torch.manual_seed(0)\n if validate_results:\n out = fd.validate(inputs)\n else:\n if enable_options is None:\n enable_options = []\n if disable_options is None:\n disable_options = []\n out = fd.execute(\n inputs,\n device=device,\n _enable_options=enable_options,\n _disable_options=disable_options,\n )\n\n assert check_captured_python_definition(\n out, fd, inputs_captured, device, enable_options, disable_options\n )\n assert expected_fd_str is None or expected_fd_str in repr(fd)\n return out, fd\n\n\n# Migrated tests to new direct python bindings use this.\n@pytest.fixture(params=[\"lru_cache\", \"eager\"])\ndef nvfuser_direct_test(request):\n if is_pre_volta():\n pytest.skip(\"Only supported on Volta and newer devices.\")\n\n cache_type = request.param\n if cache_type == \"lru_cache\":\n if not hasattr(nvfuser_direct_test, \"cache\"):\n nvfuser_direct_test.cache = LRUCache(max_fusions=16384)\n yield NVFuserTest(nvfuser_direct_test.cache)\n else:\n yield NVFuserTest()","source_hash":"a868b522b94ffe66899fc542b20baf53acdf618e326b56af07b7f9f2bf23b795","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.conftest.nvfuser_direct_test","uri":"program://Fuser/function/tests.python.direct.conftest.nvfuser_direct_test#L89-L99","kind":"function","name":"nvfuser_direct_test","path":"tests/python/direct/conftest.py","language":"python","start_line":89,"end_line":99,"context_start_line":69,"context_end_line":99,"code":" if enable_options is None:\n enable_options = []\n if disable_options is None:\n disable_options = []\n out = fd.execute(\n inputs,\n device=device,\n _enable_options=enable_options,\n _disable_options=disable_options,\n )\n\n assert check_captured_python_definition(\n out, fd, inputs_captured, device, enable_options, disable_options\n )\n assert expected_fd_str is None or expected_fd_str in repr(fd)\n return out, fd\n\n\n# Migrated tests to new direct python bindings use this.\n@pytest.fixture(params=[\"lru_cache\", \"eager\"])\ndef nvfuser_direct_test(request):\n if is_pre_volta():\n pytest.skip(\"Only supported on Volta and newer devices.\")\n\n cache_type = request.param\n if cache_type == \"lru_cache\":\n if not hasattr(nvfuser_direct_test, \"cache\"):\n nvfuser_direct_test.cache = LRUCache(max_fusions=16384)\n yield NVFuserTest(nvfuser_direct_test.cache)\n else:\n yield NVFuserTest()","source_hash":"a868b522b94ffe66899fc542b20baf53acdf618e326b56af07b7f9f2bf23b795","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.conftest.__init__","uri":"program://Fuser/function/tests.python.direct.conftest.__init__#L16-L18","kind":"function","name":"__init__","path":"tests/python/direct/conftest.py","language":"python","start_line":16,"end_line":18,"context_start_line":1,"context_end_line":38,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nfrom copy import deepcopy\nimport torch\nfrom torch.testing._internal.common_utils import TestCase\n\nfrom nvfuser_direct import FusionDefinition, LRUCache\nfrom python.direct_utils import is_pre_volta, check_captured_python_definition\n\n\nclass NVFuserTest(TestCase):\n def __init__(self, cache=None):\n super().__init__()\n self.cache = cache\n\n # Helper function to verify the nvfuser output and make sure the string\n # definition based on the FusionDefinition is executable and matches the\n # original definition\n def exec_nvfuser(\n self,\n fusion_func,\n inputs,\n *,\n new_fusion_expected=True,\n expected_fd_str=None,\n device=None,\n enable_options=None,\n disable_options=None,\n validate_results=False,\n ):\n # Copy inputs because aliased outputs can modify inputs when running\n # FusionDefinition\n inputs_captured = deepcopy(inputs)\n","source_hash":"a868b522b94ffe66899fc542b20baf53acdf618e326b56af07b7f9f2bf23b795","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.conftest.exec_nvfuser","uri":"program://Fuser/function/tests.python.direct.conftest.exec_nvfuser#L23-L84","kind":"function","name":"exec_nvfuser","path":"tests/python/direct/conftest.py","language":"python","start_line":23,"end_line":84,"context_start_line":3,"context_end_line":99,"code":"# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nfrom copy import deepcopy\nimport torch\nfrom torch.testing._internal.common_utils import TestCase\n\nfrom nvfuser_direct import FusionDefinition, LRUCache\nfrom python.direct_utils import is_pre_volta, check_captured_python_definition\n\n\nclass NVFuserTest(TestCase):\n def __init__(self, cache=None):\n super().__init__()\n self.cache = cache\n\n # Helper function to verify the nvfuser output and make sure the string\n # definition based on the FusionDefinition is executable and matches the\n # original definition\n def exec_nvfuser(\n self,\n fusion_func,\n inputs,\n *,\n new_fusion_expected=True,\n expected_fd_str=None,\n device=None,\n enable_options=None,\n disable_options=None,\n validate_results=False,\n ):\n # Copy inputs because aliased outputs can modify inputs when running\n # FusionDefinition\n inputs_captured = deepcopy(inputs)\n\n if self.cache is not None:\n prev_size = self.cache.num_fusions()\n\n # Run compilation twice to test lru cache; The number of fusions\n # should not increase during the second round.\n for _ in range(2):\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n fd.fec = self.cache.cache_compile(fd.fusion)\n del fd._fusion\n\n # The LRU cache is shared across all tests. If you run all the tests\n # together, a fusion can be cached from an earlier test. If you run\n # a test standalone, then the fusion will not exist. Skip this\n # assertion for this case but check that cache_compile works\n # correctly.\n if new_fusion_expected is not None:\n assert self.cache.num_fusions() == prev_size + int(new_fusion_expected)\n else:\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n # Execute a fusion function and capture the string python definition\n # Set manual_seed before running fusion to avoid mismatch results\n # with rng kernels\n torch.manual_seed(0)\n if validate_results:\n out = fd.validate(inputs)\n else:\n if enable_options is None:\n enable_options = []\n if disable_options is None:\n disable_options = []\n out = fd.execute(\n inputs,\n device=device,\n _enable_options=enable_options,\n _disable_options=disable_options,\n )\n\n assert check_captured_python_definition(\n out, fd, inputs_captured, device, enable_options, disable_options\n )\n assert expected_fd_str is None or expected_fd_str in repr(fd)\n return out, fd\n\n\n# Migrated tests to new direct python bindings use this.\n@pytest.fixture(params=[\"lru_cache\", \"eager\"])\ndef nvfuser_direct_test(request):\n if is_pre_volta():\n pytest.skip(\"Only supported on Volta and newer devices.\")\n\n cache_type = request.param\n if cache_type == \"lru_cache\":\n if not hasattr(nvfuser_direct_test, \"cache\"):\n nvfuser_direct_test.cache = LRUCache(max_fusions=16384)\n yield NVFuserTest(nvfuser_direct_test.cache)\n else:\n yield NVFuserTest()","source_hash":"a868b522b94ffe66899fc542b20baf53acdf618e326b56af07b7f9f2bf23b795","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_with_id_model_indexer","uri":"program://Fuser/module/tests.python.direct.test_with_id_model_indexer#L1-L212","kind":"module","name":"tests.python.direct.test_with_id_model_indexer","path":"tests/python/direct/test_with_id_model_indexer.py","language":"python","start_line":1,"end_line":212,"context_start_line":1,"context_end_line":212,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\n\nfrom nvfuser_direct import (\n FusionDefinition,\n DataType,\n)\nfrom python.direct_utils import (\n FLOAT4_E2M1_MAX,\n FLOAT8_E4M3_EPS,\n FLOAT8_E4M3_MAX,\n pytorch_nvfp4_quantize,\n microarchitecture_is,\n linear_to_swizzled_128_4,\n round_up,\n activation_scale_to_nvfp4,\n)\n\nimport pytest\n\n\n# FIXME: this test needs to be merged back into test_narrow_precision.py.\n# We have indexer issue: https://github.com/NVIDIA/Fuser/issues/5200, which\n# forces the adoption of environment variable in order to avoid codegen\n# assertion. Having this as a separate test file would avoid environment\n# variable contamination from others.\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on compute 10.0\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_layout_op_and_cutlass_nvfp4_grouped_mm(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n BLOCK_SIZE = 16\n\n # k dimension is multiple of 4 * 16 to avoid padding on block scaling factor\n m, n, k = config\n assert k % 64 == 0\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1 = torch.testing.make_tensor((m, k), dtype=torch.float32, device=\"cuda:0\")\n # format is g, n, k instead of g, k, n\n mat2 = torch.testing.make_tensor((g, n, k), dtype=torch.float32, device=\"cuda:0\")\n\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n blockscale_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n\n # prepare quantization for mat2\n mat2_gs = torch.empty((g,), dtype=torch.float32, device=\"cuda:0\")\n scale2 = torch.empty(\n (g, n, k // BLOCK_SIZE), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n\n acc_tokens = 0\n rounded_acc_tokens = 0\n mat2_scaled = torch.empty(\n (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n for i in range(g):\n global_sf = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2[i].max()\n offsets[i] = acc_tokens\n blockscale_offsets[i] = rounded_acc_tokens\n acc_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_acc_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n scaled_mat2_i, bs_mat2_i = pytorch_nvfp4_quantize(mat2[i], global_sf)\n mat2_gs[i] = 1.0 / global_sf\n mat2_scaled[i] = scaled_mat2_i\n scale2[i] = linear_to_swizzled_128_4(bs_mat2_i)\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n alpha = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n problem_sizes = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n blockscale_offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n # TODO: fix dynamic shape in issue https://github.com/NVIDIA/Fuser/issues/5199\n # m_size = fd.ops.size(mat1, 0)\n # k_size = fd.ops.size(mat1, 1)\n # k_tile_size = fd.ops.div(k_size, 16)\n # use static shape as a temporary WAR.\n m_size = m\n k_size = k\n k_tile_size = k_size // 16\n # using primitive operations to handle quantization\n reshaped_mat1 = fd.ops.reshape(mat1, [m_size, k_tile_size, 16])\n\n # quantization math to compute block scaling factor\n scale1 = fd.ops.abs(reshaped_mat1)\n scale1 = fd.ops.max(scale1, 2)\n scale1 = fd.ops.div(scale1, FLOAT4_E2M1_MAX)\n scale1 = fd.ops.clamp(scale1, FLOAT8_E4M3_EPS, FLOAT8_E4M3_MAX)\n broadcast_scale1 = fd.ops.broadcast(scale1, [False, False, True])\n reshaped_scaled_mat1 = fd.ops.div(reshaped_mat1, broadcast_scale1)\n reshaped_scaled_mat1 = fd.ops.clamp(\n reshaped_scaled_mat1, -FLOAT8_E4M3_MAX, FLOAT8_E4M3_MAX\n )\n\n scaled_mat1 = fd.ops.reshape(reshaped_scaled_mat1, [m_size, k_size])\n\n # cast the quantized tv and block sf to proper dtype\n fp4_mat1 = fd.ops.cast(scaled_mat1, DataType.Float4_e2m1fn)\n fp8_scale1 = fd.ops.cast(scale1, DataType.Float8_e4m3fn)\n\n # swizzle & pad block sf\n layout_fp8_scale1 = fd.ops.preprocess_grouped_matmul_input_sf(\n fp8_scale1, offsets, blockscale_offsets\n )\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n mat2,\n layout_fp8_scale1,\n scale2,\n alpha,\n problem_sizes,\n offsets,\n blockscale_offsets,\n DataType.BFloat16,\n )\n fd.add_output(out)\n\n inputs = [\n mat1,\n mat2_scaled.view(torch.float4_e2m1fn_x2).transpose(-1, -2),\n scale2,\n mat2_gs,\n problem_sizes,\n offsets,\n blockscale_offsets,\n ]\n\n # FIXME: force indexing to use IdModel indexer to avoid indexing error.\n # see issue: https://github.com/NVIDIA/Fuser/issues/5200\n # NOTE: IdModel indexer is now enabled by default, so this is no longer needed.\n o, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n\n # quantization for activation is needed for reference.\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")\n mat1_fp4, scale1 = activation_scale_to_nvfp4(\n mat1, mat1_gs, offsets, blockscale_offsets, BLOCK_SIZE\n )\n o_decomposed_ref = torch.empty(m, n, dtype=torch.bfloat16, device=\"cuda:0\")\n for i in range(g):\n l = offsets[i]\n l_sf = blockscale_offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n r_sf = round_up(tokens_per_expert[i], 128) + l_sf\n # For some reason I cannot feed mat2_gs[i] as alpha in the torch kernel.\n # This triggers a cublas invalid value error.\n o_decomposed_ref[l:r] = (\n torch._scaled_mm(\n mat1_fp4[l:r],\n mat2_scaled[i].transpose(-1, -2),\n scale1[l_sf:r_sf],\n scale2[i],\n None,\n None,\n torch.bfloat16,\n )\n * mat2_gs[i]\n )\n\n torch.testing.assert_close(o_decomposed_ref, o[0], atol=1e-2, rtol=1e-2)","source_hash":"d94a5942e48e7275c52f33258085cb65c5e386e4a07c2aa792c6d202ec025b38","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_with_id_model_indexer.test_layout_op_and_cutlass_nvfp4_grouped_mm","uri":"program://Fuser/function/tests.python.direct.test_with_id_model_indexer.test_layout_op_and_cutlass_nvfp4_grouped_mm#L37-L212","kind":"function","name":"test_layout_op_and_cutlass_nvfp4_grouped_mm","path":"tests/python/direct/test_with_id_model_indexer.py","language":"python","start_line":37,"end_line":212,"context_start_line":17,"context_end_line":212,"code":" microarchitecture_is,\n linear_to_swizzled_128_4,\n round_up,\n activation_scale_to_nvfp4,\n)\n\nimport pytest\n\n\n# FIXME: this test needs to be merged back into test_narrow_precision.py.\n# We have indexer issue: https://github.com/NVIDIA/Fuser/issues/5200, which\n# forces the adoption of environment variable in order to avoid codegen\n# assertion. Having this as a separate test file would avoid environment\n# variable contamination from others.\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on compute 10.0\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_layout_op_and_cutlass_nvfp4_grouped_mm(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n BLOCK_SIZE = 16\n\n # k dimension is multiple of 4 * 16 to avoid padding on block scaling factor\n m, n, k = config\n assert k % 64 == 0\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1 = torch.testing.make_tensor((m, k), dtype=torch.float32, device=\"cuda:0\")\n # format is g, n, k instead of g, k, n\n mat2 = torch.testing.make_tensor((g, n, k), dtype=torch.float32, device=\"cuda:0\")\n\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n blockscale_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n\n # prepare quantization for mat2\n mat2_gs = torch.empty((g,), dtype=torch.float32, device=\"cuda:0\")\n scale2 = torch.empty(\n (g, n, k // BLOCK_SIZE), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n\n acc_tokens = 0\n rounded_acc_tokens = 0\n mat2_scaled = torch.empty(\n (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n for i in range(g):\n global_sf = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2[i].max()\n offsets[i] = acc_tokens\n blockscale_offsets[i] = rounded_acc_tokens\n acc_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_acc_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n scaled_mat2_i, bs_mat2_i = pytorch_nvfp4_quantize(mat2[i], global_sf)\n mat2_gs[i] = 1.0 / global_sf\n mat2_scaled[i] = scaled_mat2_i\n scale2[i] = linear_to_swizzled_128_4(bs_mat2_i)\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n alpha = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n problem_sizes = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n blockscale_offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n # TODO: fix dynamic shape in issue https://github.com/NVIDIA/Fuser/issues/5199\n # m_size = fd.ops.size(mat1, 0)\n # k_size = fd.ops.size(mat1, 1)\n # k_tile_size = fd.ops.div(k_size, 16)\n # use static shape as a temporary WAR.\n m_size = m\n k_size = k\n k_tile_size = k_size // 16\n # using primitive operations to handle quantization\n reshaped_mat1 = fd.ops.reshape(mat1, [m_size, k_tile_size, 16])\n\n # quantization math to compute block scaling factor\n scale1 = fd.ops.abs(reshaped_mat1)\n scale1 = fd.ops.max(scale1, 2)\n scale1 = fd.ops.div(scale1, FLOAT4_E2M1_MAX)\n scale1 = fd.ops.clamp(scale1, FLOAT8_E4M3_EPS, FLOAT8_E4M3_MAX)\n broadcast_scale1 = fd.ops.broadcast(scale1, [False, False, True])\n reshaped_scaled_mat1 = fd.ops.div(reshaped_mat1, broadcast_scale1)\n reshaped_scaled_mat1 = fd.ops.clamp(\n reshaped_scaled_mat1, -FLOAT8_E4M3_MAX, FLOAT8_E4M3_MAX\n )\n\n scaled_mat1 = fd.ops.reshape(reshaped_scaled_mat1, [m_size, k_size])\n\n # cast the quantized tv and block sf to proper dtype\n fp4_mat1 = fd.ops.cast(scaled_mat1, DataType.Float4_e2m1fn)\n fp8_scale1 = fd.ops.cast(scale1, DataType.Float8_e4m3fn)\n\n # swizzle & pad block sf\n layout_fp8_scale1 = fd.ops.preprocess_grouped_matmul_input_sf(\n fp8_scale1, offsets, blockscale_offsets\n )\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n mat2,\n layout_fp8_scale1,\n scale2,\n alpha,\n problem_sizes,\n offsets,\n blockscale_offsets,\n DataType.BFloat16,\n )\n fd.add_output(out)\n\n inputs = [\n mat1,\n mat2_scaled.view(torch.float4_e2m1fn_x2).transpose(-1, -2),\n scale2,\n mat2_gs,\n problem_sizes,\n offsets,\n blockscale_offsets,\n ]\n\n # FIXME: force indexing to use IdModel indexer to avoid indexing error.\n # see issue: https://github.com/NVIDIA/Fuser/issues/5200\n # NOTE: IdModel indexer is now enabled by default, so this is no longer needed.\n o, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n\n # quantization for activation is needed for reference.\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")\n mat1_fp4, scale1 = activation_scale_to_nvfp4(\n mat1, mat1_gs, offsets, blockscale_offsets, BLOCK_SIZE\n )\n o_decomposed_ref = torch.empty(m, n, dtype=torch.bfloat16, device=\"cuda:0\")\n for i in range(g):\n l = offsets[i]\n l_sf = blockscale_offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n r_sf = round_up(tokens_per_expert[i], 128) + l_sf\n # For some reason I cannot feed mat2_gs[i] as alpha in the torch kernel.\n # This triggers a cublas invalid value error.\n o_decomposed_ref[l:r] = (\n torch._scaled_mm(\n mat1_fp4[l:r],\n mat2_scaled[i].transpose(-1, -2),\n scale1[l_sf:r_sf],\n scale2[i],\n None,\n None,\n torch.bfloat16,\n )\n * mat2_gs[i]\n )\n\n torch.testing.assert_close(o_decomposed_ref, o[0], atol=1e-2, rtol=1e-2)","source_hash":"d94a5942e48e7275c52f33258085cb65c5e386e4a07c2aa792c6d202ec025b38","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_with_id_model_indexer.nvfuser_fusion_id0","uri":"program://Fuser/function/tests.python.direct.test_with_id_model_indexer.nvfuser_fusion_id0#L89-L164","kind":"function","name":"nvfuser_fusion_id0","path":"tests/python/direct/test_with_id_model_indexer.py","language":"python","start_line":89,"end_line":164,"context_start_line":69,"context_end_line":184,"code":" (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n for i in range(g):\n global_sf = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2[i].max()\n offsets[i] = acc_tokens\n blockscale_offsets[i] = rounded_acc_tokens\n acc_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_acc_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n scaled_mat2_i, bs_mat2_i = pytorch_nvfp4_quantize(mat2[i], global_sf)\n mat2_gs[i] = 1.0 / global_sf\n mat2_scaled[i] = scaled_mat2_i\n scale2[i] = linear_to_swizzled_128_4(bs_mat2_i)\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n alpha = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n problem_sizes = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n blockscale_offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n # TODO: fix dynamic shape in issue https://github.com/NVIDIA/Fuser/issues/5199\n # m_size = fd.ops.size(mat1, 0)\n # k_size = fd.ops.size(mat1, 1)\n # k_tile_size = fd.ops.div(k_size, 16)\n # use static shape as a temporary WAR.\n m_size = m\n k_size = k\n k_tile_size = k_size // 16\n # using primitive operations to handle quantization\n reshaped_mat1 = fd.ops.reshape(mat1, [m_size, k_tile_size, 16])\n\n # quantization math to compute block scaling factor\n scale1 = fd.ops.abs(reshaped_mat1)\n scale1 = fd.ops.max(scale1, 2)\n scale1 = fd.ops.div(scale1, FLOAT4_E2M1_MAX)\n scale1 = fd.ops.clamp(scale1, FLOAT8_E4M3_EPS, FLOAT8_E4M3_MAX)\n broadcast_scale1 = fd.ops.broadcast(scale1, [False, False, True])\n reshaped_scaled_mat1 = fd.ops.div(reshaped_mat1, broadcast_scale1)\n reshaped_scaled_mat1 = fd.ops.clamp(\n reshaped_scaled_mat1, -FLOAT8_E4M3_MAX, FLOAT8_E4M3_MAX\n )\n\n scaled_mat1 = fd.ops.reshape(reshaped_scaled_mat1, [m_size, k_size])\n\n # cast the quantized tv and block sf to proper dtype\n fp4_mat1 = fd.ops.cast(scaled_mat1, DataType.Float4_e2m1fn)\n fp8_scale1 = fd.ops.cast(scale1, DataType.Float8_e4m3fn)\n\n # swizzle & pad block sf\n layout_fp8_scale1 = fd.ops.preprocess_grouped_matmul_input_sf(\n fp8_scale1, offsets, blockscale_offsets\n )\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n mat2,\n layout_fp8_scale1,\n scale2,\n alpha,\n problem_sizes,\n offsets,\n blockscale_offsets,\n DataType.BFloat16,\n )\n fd.add_output(out)\n\n inputs = [\n mat1,\n mat2_scaled.view(torch.float4_e2m1fn_x2).transpose(-1, -2),\n scale2,\n mat2_gs,\n problem_sizes,\n offsets,\n blockscale_offsets,\n ]\n\n # FIXME: force indexing to use IdModel indexer to avoid indexing error.\n # see issue: https://github.com/NVIDIA/Fuser/issues/5200\n # NOTE: IdModel indexer is now enabled by default, so this is no longer needed.\n o, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n\n # quantization for activation is needed for reference.\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")","source_hash":"d94a5942e48e7275c52f33258085cb65c5e386e4a07c2aa792c6d202ec025b38","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_import","uri":"program://Fuser/module/tests.python.direct.test_import#L1-L11","kind":"module","name":"tests.python.direct.test_import","path":"tests/python/direct/test_import.py","language":"python","start_line":1,"end_line":11,"context_start_line":1,"context_end_line":11,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\n\ndef test_import_correct():\n try:\n import nvfuser_direct # noqa: F401\n except Exception as e:\n raise RuntimeError(\"Failed to import nvfuser_direct.\")","source_hash":"9aeec2b01671c242bc8bd38b191ff5186e32b4d6e295be25954ee94fe37b9dd1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_import.test_import_correct","uri":"program://Fuser/function/tests.python.direct.test_import.test_import_correct#L7-L11","kind":"function","name":"test_import_correct","path":"tests/python/direct/test_import.py","language":"python","start_line":7,"end_line":11,"context_start_line":1,"context_end_line":11,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\n\ndef test_import_correct():\n try:\n import nvfuser_direct # noqa: F401\n except Exception as e:\n raise RuntimeError(\"Failed to import nvfuser_direct.\")","source_hash":"9aeec2b01671c242bc8bd38b191ff5186e32b4d6e295be25954ee94fe37b9dd1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_mxfp8_gemm","uri":"program://Fuser/module/tests.python.direct.test_cutlass_mxfp8_gemm#L1-L124","kind":"module","name":"tests.python.direct.test_cutlass_mxfp8_gemm","path":"tests/python/direct/test_cutlass_mxfp8_gemm.py","language":"python","start_line":1,"end_line":124,"context_start_line":1,"context_end_line":124,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom nvfuser_direct import nvf_cutlass\nfrom python.direct_utils import microarchitecture_is\n\nif not microarchitecture_is(10, 0):\n pytest.skip(\n reason=\"MxFp8 Requires compute capability 10.\",\n allow_module_level=True,\n )\n\nfrom python.direct_utils import (\n linear_to_swizzled_128_4,\n swizzled_to_linear_128_4,\n)\n\n\ndef dequantize_mxfp8(tensor_fp8, tensor_sf):\n \"\"\"Dequantize the fp8 tensor back to high precision.\"\"\"\n m, k = tensor_fp8.shape\n BLOCK_SIZE = 32\n tensor_sf_linear = swizzled_to_linear_128_4(tensor_sf, m, k)\n # Apply scale factor to all elements in the same block\n sf = tensor_sf_linear.repeat_interleave(BLOCK_SIZE, dim=1).to(torch.float32)\n dqx = tensor_fp8.to(torch.float32)\n # Account for padding of scale factor\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf\n return dequant.reshape(m, k)\n\n\ndef to_fp8(tensor: torch.Tensor) -> torch.Tensor:\n # The fn suffix means that fp8 is a finite type without infinite support.\n # Clamp values above 464 to avoid casting values to NaN.\n finfo = torch.finfo(torch.float8_e4m3fn)\n return torch.round(tensor.clamp(min=finfo.min, max=finfo.max)).to(\n dtype=torch.float8_e4m3fn\n )\n\n\ndef pytorch_mxfp8_quantize(a):\n BLOCK_SIZE = 32\n assert (\n a.size(-1) % BLOCK_SIZE == 0\n ), \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n # Find absolute maximum along blockwise dimension\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n\n # Get fp32 block scale factor for fp8\n FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n block_scale_fp32 = (max_abs / FLOAT8_E4M3_MAX).float()\n\n # Clamp scale factor within UE8M0\n FLOAT8_UE8M0_EPS = torch.finfo(torch.float8_e8m0fnu).tiny\n FLOAT8_UE8M0_MAX = torch.finfo(torch.float8_e8m0fnu).max\n block_scale_fp32 = torch.clamp(\n block_scale_fp32, min=FLOAT8_UE8M0_EPS, max=FLOAT8_UE8M0_MAX\n )\n\n # Apply block conversion factor\n a_scaled = a_fp32 / block_scale_fp32.unsqueeze(-1)\n a_scaled = a_scaled.view(original_shape)\n\n return to_fp8(a_scaled), block_scale_fp32.to(torch.float8_e8m0fnu)\n\n\ndef get_ref_results(\n a_fp8,\n b_fp8,\n a_sf,\n b_sf,\n m,\n n,\n):\n _, m_k = a_fp8.shape\n _, n_k = b_fp8.shape\n assert m_k == n_k\n a_in_dtype = dequantize_mxfp8(a_fp8, a_sf)\n b_in_dtype = dequantize_mxfp8(b_fp8, b_sf)\n return torch.matmul(a_in_dtype, b_in_dtype.t())\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(\n \"shape\", [(128, 128, 128), (128, 128, 256), (256, 128, 128), (128, 256, 256)]\n)\n@torch.inference_mode()\ndef test_mxfp8_gemm(\n dtype: torch.dtype,\n shape: tuple[int, int, int],\n) -> None:\n m, n, k = shape\n block_size = 32\n a_dtype = torch.randn((m, k), dtype=dtype, device=\"cuda\")\n b_dtype = torch.randn((n, k), dtype=dtype, device=\"cuda\")\n\n alpha = torch.tensor(1.0, device=\"cuda\")\n a_fp8, a_scale_linear = pytorch_mxfp8_quantize(a_dtype)\n b_fp8, b_scale_linear = pytorch_mxfp8_quantize(b_dtype)\n a_scale_interleaved = linear_to_swizzled_128_4(a_scale_linear)\n b_scale_interleaved = linear_to_swizzled_128_4(b_scale_linear)\n\n expected_out = get_ref_results(\n a_fp8,\n b_fp8,\n a_scale_interleaved,\n b_scale_interleaved,\n m,\n n,\n )\n out = nvf_cutlass.mxfp8_scaled_mm(\n a_fp8, b_fp8, a_scale_interleaved, b_scale_interleaved, alpha, dtype\n )\n\n torch.testing.assert_close(out, expected_out.to(dtype=dtype))","source_hash":"3a28c1acbf10abb1306ae3e47420674aa8ed7be482fdfafde8924b8499b19e2e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_mxfp8_gemm.dequantize_mxfp8","uri":"program://Fuser/function/tests.python.direct.test_cutlass_mxfp8_gemm.dequantize_mxfp8#L23-L34","kind":"function","name":"dequantize_mxfp8","path":"tests/python/direct/test_cutlass_mxfp8_gemm.py","language":"python","start_line":23,"end_line":34,"context_start_line":3,"context_end_line":54,"code":"# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom nvfuser_direct import nvf_cutlass\nfrom python.direct_utils import microarchitecture_is\n\nif not microarchitecture_is(10, 0):\n pytest.skip(\n reason=\"MxFp8 Requires compute capability 10.\",\n allow_module_level=True,\n )\n\nfrom python.direct_utils import (\n linear_to_swizzled_128_4,\n swizzled_to_linear_128_4,\n)\n\n\ndef dequantize_mxfp8(tensor_fp8, tensor_sf):\n \"\"\"Dequantize the fp8 tensor back to high precision.\"\"\"\n m, k = tensor_fp8.shape\n BLOCK_SIZE = 32\n tensor_sf_linear = swizzled_to_linear_128_4(tensor_sf, m, k)\n # Apply scale factor to all elements in the same block\n sf = tensor_sf_linear.repeat_interleave(BLOCK_SIZE, dim=1).to(torch.float32)\n dqx = tensor_fp8.to(torch.float32)\n # Account for padding of scale factor\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf\n return dequant.reshape(m, k)\n\n\ndef to_fp8(tensor: torch.Tensor) -> torch.Tensor:\n # The fn suffix means that fp8 is a finite type without infinite support.\n # Clamp values above 464 to avoid casting values to NaN.\n finfo = torch.finfo(torch.float8_e4m3fn)\n return torch.round(tensor.clamp(min=finfo.min, max=finfo.max)).to(\n dtype=torch.float8_e4m3fn\n )\n\n\ndef pytorch_mxfp8_quantize(a):\n BLOCK_SIZE = 32\n assert (\n a.size(-1) % BLOCK_SIZE == 0\n ), \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n # Find absolute maximum along blockwise dimension\n original_shape = a.shape","source_hash":"3a28c1acbf10abb1306ae3e47420674aa8ed7be482fdfafde8924b8499b19e2e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_mxfp8_gemm.to_fp8","uri":"program://Fuser/function/tests.python.direct.test_cutlass_mxfp8_gemm.to_fp8#L37-L43","kind":"function","name":"to_fp8","path":"tests/python/direct/test_cutlass_mxfp8_gemm.py","language":"python","start_line":37,"end_line":43,"context_start_line":17,"context_end_line":63,"code":"from python.direct_utils import (\n linear_to_swizzled_128_4,\n swizzled_to_linear_128_4,\n)\n\n\ndef dequantize_mxfp8(tensor_fp8, tensor_sf):\n \"\"\"Dequantize the fp8 tensor back to high precision.\"\"\"\n m, k = tensor_fp8.shape\n BLOCK_SIZE = 32\n tensor_sf_linear = swizzled_to_linear_128_4(tensor_sf, m, k)\n # Apply scale factor to all elements in the same block\n sf = tensor_sf_linear.repeat_interleave(BLOCK_SIZE, dim=1).to(torch.float32)\n dqx = tensor_fp8.to(torch.float32)\n # Account for padding of scale factor\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf\n return dequant.reshape(m, k)\n\n\ndef to_fp8(tensor: torch.Tensor) -> torch.Tensor:\n # The fn suffix means that fp8 is a finite type without infinite support.\n # Clamp values above 464 to avoid casting values to NaN.\n finfo = torch.finfo(torch.float8_e4m3fn)\n return torch.round(tensor.clamp(min=finfo.min, max=finfo.max)).to(\n dtype=torch.float8_e4m3fn\n )\n\n\ndef pytorch_mxfp8_quantize(a):\n BLOCK_SIZE = 32\n assert (\n a.size(-1) % BLOCK_SIZE == 0\n ), \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n # Find absolute maximum along blockwise dimension\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n\n # Get fp32 block scale factor for fp8\n FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n block_scale_fp32 = (max_abs / FLOAT8_E4M3_MAX).float()\n\n # Clamp scale factor within UE8M0\n FLOAT8_UE8M0_EPS = torch.finfo(torch.float8_e8m0fnu).tiny","source_hash":"3a28c1acbf10abb1306ae3e47420674aa8ed7be482fdfafde8924b8499b19e2e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_mxfp8_gemm.pytorch_mxfp8_quantize","uri":"program://Fuser/function/tests.python.direct.test_cutlass_mxfp8_gemm.pytorch_mxfp8_quantize#L46-L73","kind":"function","name":"pytorch_mxfp8_quantize","path":"tests/python/direct/test_cutlass_mxfp8_gemm.py","language":"python","start_line":46,"end_line":73,"context_start_line":26,"context_end_line":93,"code":" BLOCK_SIZE = 32\n tensor_sf_linear = swizzled_to_linear_128_4(tensor_sf, m, k)\n # Apply scale factor to all elements in the same block\n sf = tensor_sf_linear.repeat_interleave(BLOCK_SIZE, dim=1).to(torch.float32)\n dqx = tensor_fp8.to(torch.float32)\n # Account for padding of scale factor\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf\n return dequant.reshape(m, k)\n\n\ndef to_fp8(tensor: torch.Tensor) -> torch.Tensor:\n # The fn suffix means that fp8 is a finite type without infinite support.\n # Clamp values above 464 to avoid casting values to NaN.\n finfo = torch.finfo(torch.float8_e4m3fn)\n return torch.round(tensor.clamp(min=finfo.min, max=finfo.max)).to(\n dtype=torch.float8_e4m3fn\n )\n\n\ndef pytorch_mxfp8_quantize(a):\n BLOCK_SIZE = 32\n assert (\n a.size(-1) % BLOCK_SIZE == 0\n ), \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n # Find absolute maximum along blockwise dimension\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n\n # Get fp32 block scale factor for fp8\n FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n block_scale_fp32 = (max_abs / FLOAT8_E4M3_MAX).float()\n\n # Clamp scale factor within UE8M0\n FLOAT8_UE8M0_EPS = torch.finfo(torch.float8_e8m0fnu).tiny\n FLOAT8_UE8M0_MAX = torch.finfo(torch.float8_e8m0fnu).max\n block_scale_fp32 = torch.clamp(\n block_scale_fp32, min=FLOAT8_UE8M0_EPS, max=FLOAT8_UE8M0_MAX\n )\n\n # Apply block conversion factor\n a_scaled = a_fp32 / block_scale_fp32.unsqueeze(-1)\n a_scaled = a_scaled.view(original_shape)\n\n return to_fp8(a_scaled), block_scale_fp32.to(torch.float8_e8m0fnu)\n\n\ndef get_ref_results(\n a_fp8,\n b_fp8,\n a_sf,\n b_sf,\n m,\n n,\n):\n _, m_k = a_fp8.shape\n _, n_k = b_fp8.shape\n assert m_k == n_k\n a_in_dtype = dequantize_mxfp8(a_fp8, a_sf)\n b_in_dtype = dequantize_mxfp8(b_fp8, b_sf)\n return torch.matmul(a_in_dtype, b_in_dtype.t())\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(","source_hash":"3a28c1acbf10abb1306ae3e47420674aa8ed7be482fdfafde8924b8499b19e2e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_mxfp8_gemm.get_ref_results","uri":"program://Fuser/function/tests.python.direct.test_cutlass_mxfp8_gemm.get_ref_results#L76-L89","kind":"function","name":"get_ref_results","path":"tests/python/direct/test_cutlass_mxfp8_gemm.py","language":"python","start_line":76,"end_line":89,"context_start_line":56,"context_end_line":109,"code":" max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n\n # Get fp32 block scale factor for fp8\n FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n block_scale_fp32 = (max_abs / FLOAT8_E4M3_MAX).float()\n\n # Clamp scale factor within UE8M0\n FLOAT8_UE8M0_EPS = torch.finfo(torch.float8_e8m0fnu).tiny\n FLOAT8_UE8M0_MAX = torch.finfo(torch.float8_e8m0fnu).max\n block_scale_fp32 = torch.clamp(\n block_scale_fp32, min=FLOAT8_UE8M0_EPS, max=FLOAT8_UE8M0_MAX\n )\n\n # Apply block conversion factor\n a_scaled = a_fp32 / block_scale_fp32.unsqueeze(-1)\n a_scaled = a_scaled.view(original_shape)\n\n return to_fp8(a_scaled), block_scale_fp32.to(torch.float8_e8m0fnu)\n\n\ndef get_ref_results(\n a_fp8,\n b_fp8,\n a_sf,\n b_sf,\n m,\n n,\n):\n _, m_k = a_fp8.shape\n _, n_k = b_fp8.shape\n assert m_k == n_k\n a_in_dtype = dequantize_mxfp8(a_fp8, a_sf)\n b_in_dtype = dequantize_mxfp8(b_fp8, b_sf)\n return torch.matmul(a_in_dtype, b_in_dtype.t())\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(\n \"shape\", [(128, 128, 128), (128, 128, 256), (256, 128, 128), (128, 256, 256)]\n)\n@torch.inference_mode()\ndef test_mxfp8_gemm(\n dtype: torch.dtype,\n shape: tuple[int, int, int],\n) -> None:\n m, n, k = shape\n block_size = 32\n a_dtype = torch.randn((m, k), dtype=dtype, device=\"cuda\")\n b_dtype = torch.randn((n, k), dtype=dtype, device=\"cuda\")\n\n alpha = torch.tensor(1.0, device=\"cuda\")\n a_fp8, a_scale_linear = pytorch_mxfp8_quantize(a_dtype)\n b_fp8, b_scale_linear = pytorch_mxfp8_quantize(b_dtype)\n a_scale_interleaved = linear_to_swizzled_128_4(a_scale_linear)","source_hash":"3a28c1acbf10abb1306ae3e47420674aa8ed7be482fdfafde8924b8499b19e2e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_mxfp8_gemm.test_mxfp8_gemm","uri":"program://Fuser/function/tests.python.direct.test_cutlass_mxfp8_gemm.test_mxfp8_gemm#L97-L124","kind":"function","name":"test_mxfp8_gemm","path":"tests/python/direct/test_cutlass_mxfp8_gemm.py","language":"python","start_line":97,"end_line":124,"context_start_line":77,"context_end_line":124,"code":" a_fp8,\n b_fp8,\n a_sf,\n b_sf,\n m,\n n,\n):\n _, m_k = a_fp8.shape\n _, n_k = b_fp8.shape\n assert m_k == n_k\n a_in_dtype = dequantize_mxfp8(a_fp8, a_sf)\n b_in_dtype = dequantize_mxfp8(b_fp8, b_sf)\n return torch.matmul(a_in_dtype, b_in_dtype.t())\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(\n \"shape\", [(128, 128, 128), (128, 128, 256), (256, 128, 128), (128, 256, 256)]\n)\n@torch.inference_mode()\ndef test_mxfp8_gemm(\n dtype: torch.dtype,\n shape: tuple[int, int, int],\n) -> None:\n m, n, k = shape\n block_size = 32\n a_dtype = torch.randn((m, k), dtype=dtype, device=\"cuda\")\n b_dtype = torch.randn((n, k), dtype=dtype, device=\"cuda\")\n\n alpha = torch.tensor(1.0, device=\"cuda\")\n a_fp8, a_scale_linear = pytorch_mxfp8_quantize(a_dtype)\n b_fp8, b_scale_linear = pytorch_mxfp8_quantize(b_dtype)\n a_scale_interleaved = linear_to_swizzled_128_4(a_scale_linear)\n b_scale_interleaved = linear_to_swizzled_128_4(b_scale_linear)\n\n expected_out = get_ref_results(\n a_fp8,\n b_fp8,\n a_scale_interleaved,\n b_scale_interleaved,\n m,\n n,\n )\n out = nvf_cutlass.mxfp8_scaled_mm(\n a_fp8, b_fp8, a_scale_interleaved, b_scale_interleaved, alpha, dtype\n )\n\n torch.testing.assert_close(out, expected_out.to(dtype=dtype))","source_hash":"3a28c1acbf10abb1306ae3e47420674aa8ed7be482fdfafde8924b8499b19e2e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_gemm","uri":"program://Fuser/module/tests.python.direct.test_cutlass_gemm#L1-L70","kind":"module","name":"tests.python.direct.test_cutlass_gemm","path":"tests/python/direct/test_cutlass_gemm.py","language":"python","start_line":1,"end_line":70,"context_start_line":1,"context_end_line":70,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom python.direct_utils import microarchitecture_is\nfrom nvfuser_direct import nvf_cutlass\n\n\n# GPU Compute Capability: https://developer.nvidia.com/cuda/gpus\n# tested on blackwell compute 10.0 (B200 and GB200)\n# doesn't support 12.0 (RTX PRO 6000 and RTX 50XX)\n# Not tested on 10.3 (B300 and GB300)\n# Not tested on 12.1 (DGX Spark)\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0),\n reason=\"Does not support blackwell compute 12.0, other arches are not tested.\",\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256], [267, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8], [5, 7, 9]])\n@pytest.mark.parametrize(\"tensor_dtype\", [torch.bfloat16, torch.float16])\ndef test_grouped_mm(\n config,\n tokens_per_expert_neg_one,\n tensor_dtype,\n):\n # k dimension is multiple of 128 to avoid padding\n m, n, k = config\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1 = torch.testing.make_tensor((m, k), dtype=tensor_dtype, device=\"cuda:0\")\n mat2 = torch.testing.make_tensor((g, n, k), dtype=tensor_dtype, device=\"cuda:0\")\n ab_strides = torch.full((g,), k, dtype=torch.int64, device=\"cuda:0\")\n c_strides = torch.full((g,), n, dtype=torch.int64, device=\"cuda:0\")\n\n # offsets represents the lhs of slice in nvfuser\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n # aten_offsets represents the rhs of slice of torch._grouped_mm(A[m,k], B[g, n, k])\n aten_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n\n accumulated_tokens = 0\n # Use tokens_per_expert to calculate offsets into m dimension of input tensor.\n for i in range(g):\n offsets[i] = accumulated_tokens\n accumulated_tokens += tokens_per_expert[i]\n aten_offsets[i] = accumulated_tokens\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n out = nvf_cutlass.grouped_mm(\n mat1,\n mat2,\n ab_strides,\n c_strides,\n problem_sizes,\n offsets,\n )\n\n # Create pytorch expected output reference\n # For each expert, apply gemm. Slice the input matrix given the tokens_per_expert.\n # C[start:stop] = A[start:stop] @ B[expert].\n out_ref = torch._grouped_mm(mat1, mat2.transpose(-1, -2), aten_offsets)\n torch.testing.assert_close(out_ref, out, atol=1e-2, rtol=1e-2)","source_hash":"90fc66264118e872a194a187c8d092794c4dd284e5a5bc4745c17d955e6bcb2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_gemm.test_grouped_mm","uri":"program://Fuser/function/tests.python.direct.test_cutlass_gemm.test_grouped_mm#L24-L70","kind":"function","name":"test_grouped_mm","path":"tests/python/direct/test_cutlass_gemm.py","language":"python","start_line":24,"end_line":70,"context_start_line":4,"context_end_line":70,"code":"# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom python.direct_utils import microarchitecture_is\nfrom nvfuser_direct import nvf_cutlass\n\n\n# GPU Compute Capability: https://developer.nvidia.com/cuda/gpus\n# tested on blackwell compute 10.0 (B200 and GB200)\n# doesn't support 12.0 (RTX PRO 6000 and RTX 50XX)\n# Not tested on 10.3 (B300 and GB300)\n# Not tested on 12.1 (DGX Spark)\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0),\n reason=\"Does not support blackwell compute 12.0, other arches are not tested.\",\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256], [267, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8], [5, 7, 9]])\n@pytest.mark.parametrize(\"tensor_dtype\", [torch.bfloat16, torch.float16])\ndef test_grouped_mm(\n config,\n tokens_per_expert_neg_one,\n tensor_dtype,\n):\n # k dimension is multiple of 128 to avoid padding\n m, n, k = config\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1 = torch.testing.make_tensor((m, k), dtype=tensor_dtype, device=\"cuda:0\")\n mat2 = torch.testing.make_tensor((g, n, k), dtype=tensor_dtype, device=\"cuda:0\")\n ab_strides = torch.full((g,), k, dtype=torch.int64, device=\"cuda:0\")\n c_strides = torch.full((g,), n, dtype=torch.int64, device=\"cuda:0\")\n\n # offsets represents the lhs of slice in nvfuser\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n # aten_offsets represents the rhs of slice of torch._grouped_mm(A[m,k], B[g, n, k])\n aten_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n\n accumulated_tokens = 0\n # Use tokens_per_expert to calculate offsets into m dimension of input tensor.\n for i in range(g):\n offsets[i] = accumulated_tokens\n accumulated_tokens += tokens_per_expert[i]\n aten_offsets[i] = accumulated_tokens\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n out = nvf_cutlass.grouped_mm(\n mat1,\n mat2,\n ab_strides,\n c_strides,\n problem_sizes,\n offsets,\n )\n\n # Create pytorch expected output reference\n # For each expert, apply gemm. Slice the input matrix given the tokens_per_expert.\n # C[start:stop] = A[start:stop] @ B[expert].\n out_ref = torch._grouped_mm(mat1, mat2.transpose(-1, -2), aten_offsets)\n torch.testing.assert_close(out_ref, out, atol=1e-2, rtol=1e-2)","source_hash":"90fc66264118e872a194a187c8d092794c4dd284e5a5bc4745c17d955e6bcb2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_stream","uri":"program://Fuser/module/tests.python.direct.test_stream#L1-L159","kind":"module","name":"tests.python.direct.test_stream","path":"tests/python/direct/test_stream.py","language":"python","start_line":1,"end_line":159,"context_start_line":1,"context_end_line":159,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nfrom nvfuser_direct import FusionDefinition, ParallelType, DataType\n\n\ndef test_matmul():\n c = 3\n\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out = fd.ops.matmul(inp, w)\n fd.add_output(out)\n\n out.outer_split(1, c)\n out.axis(1).parallelize(ParallelType.stream)\n # With NVFUSER_DUMP=host_ir, you'll see the host IR container like the\n # following:\n #\n # %HostIrContainer { (T0_g_float[iS0{i0}, iS1{i2}], T1_g_float[istreamIdx7{3}, iS11{i2}, iS8{( ceilDiv(i4, 3) )}]) -> (T2_g_float[istreamIdx9{3}, iS4{i0}, iS10{( ceilDiv(i4, 3) )}, rS6{i2}]) :\n # FOR i18 from 0 to 3:\n # T2_g_float[istreamIdx9{3}, iS4{i0}, iS10{( ceilDiv(i4, 3) )}, rS6{i2}]\n # = matmul(T0_g_float[iS0{i0}, iS1{i2}],\n # T1_g_float[istreamIdx7{3}, iS11{i2}, iS8{( ceilDiv(i4, 3) )}])\n # } // %HostIrContainer\n\n inp = torch.testing.make_tensor(5, 7, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w = torch.testing.make_tensor(7, c * 2, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n ref = torch.matmul(inp, w)\n\n with torch.profiler.profile(record_shapes=True) as profile:\n (out,) = fd.execute(\n [inp, w],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n torch.testing.assert_close(out, ref)\n\n matmul_events = [event for event in profile.events() if event.name == \"aten::mm\"]\n assert len(matmul_events) == c\n for event in matmul_events:\n assert event.input_shapes == [[5, 7], [7, 2], [5, 2]]\n\n\ndef test_two_matmuls_inlinable():\n c = 3\n\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w1 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w2 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out = fd.ops.matmul(inp, w1)\n out = fd.ops.matmul(out, w2)\n fd.add_output(out)\n\n inp.outer_split(0, c)\n inp.axis(0).parallelize(ParallelType.stream)\n # With NVFUSER_DUMP=host_ir, you'll see the host IR container like the\n # following:\n #\n # %HostIrContainer { (T0_g_float[istreamIdx12{3}, iS13{( ceilDiv(i0, 3) )}, iS1{i2}], T1_g_float[iS14{i2}, iS3{i4}], T2_g_float[iS15{i4}, iS5{i6}]) -> (T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}]) :\n # T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}] = ALLOCATE(buffer=T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}], mem_type=global, size=( i0 * i6 ), zero_init=false, resets_to_zero=false)\n # FOR i99 from 0 to 3:\n # T5_l_float[istreamIdx22{3}, iS23{( ceilDiv(i0, 3) )}, iS21{i2}] = ShardByStream(T0_g_float[istreamIdx12{3}, iS13{( ceilDiv(i0, 3) )}, iS1{i2}], stream_index = i99)\n # T3_g_float[istreamIdx16{3}, iS17{( ceilDiv(i0, 3) )}, iS7{i4}, rS8{i2}]\n # = matmul(T5_l_float[istreamIdx22{3}, iS23{( ceilDiv(i0, 3) )}, iS21{i2}],\n # T1_g_float[iS14{i2}, iS3{i4}])\n # T6_l_float[istreamIdx26{3}, iS27{( ceilDiv(i0, 3) )}, iS25{i6}] = ShardByStream(T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}], stream_index = i99)\n # T6_l_float[istreamIdx26{3}, iS27{( ceilDiv(i0, 3) )}, iS25{i6}]\n # = matmul(T3_g_float[istreamIdx16{3}, iS17{( ceilDiv(i0, 3) )}, iS7{i4}, rS8{i2}],\n # T2_g_float[iS15{i4}, iS5{i6}])\n # } // %HostIrContainer\n\n inp = torch.testing.make_tensor(c * 2, 3, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w1 = torch.testing.make_tensor(3, 5, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w2 = torch.testing.make_tensor(5, 3, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n ref = torch.matmul(torch.matmul(inp, w1), w2)\n\n with torch.profiler.profile(record_shapes=True) as profile:\n (out,) = fd.execute(\n [inp, w1, w2],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n torch.testing.assert_close(out, ref)\n\n matmul_events = [event for event in profile.events() if event.name == \"aten::mm\"]\n assert len(matmul_events) == c * 2\n for event in matmul_events:\n # The `m` dimension is split into `c` chunks, so each chunk will have `m == 2`.\n assert event.input_shapes[0][0] == 2\n\n\ndef test_two_matmuls_not_inlinable():\n c = 3\n\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w1 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w2 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out = fd.ops.matmul(inp, w1)\n out = fd.ops.matmul(out, w2)\n fd.add_output(out)\n\n w1.split(1, c, inner_split=False)\n w1.axis(1).parallelize(ParallelType.stream)\n out.split(0, c, inner_split=False)\n out.axis(0).parallelize(ParallelType.stream)\n\n # After sharding propagation, the IR looks like the following:\n #\n # in: [m, k] w1: [k, n]\n # /\\\n # c\n # |\n # | matmul\n # v\n # [m, n] w2: [n, k]\n # /\\\n # c\n # |\n # | matmul\n # v\n # out: [m, k]\n # /\\\n # c\n #\n # The first matmul is column-wise (dimension n) parallel, and the second\n # row-wise (dimension m) parallel. They have to stay in different loops.\n # Therefore, the output of the first matmul (of shape [m, n]) has to be\n # fully allocated.\n\n inp = torch.testing.make_tensor(c * 2, 3, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w1 = torch.testing.make_tensor(3, c * 5, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w2 = torch.testing.make_tensor(c * 5, 3, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n ref = torch.matmul(torch.matmul(inp, w1), w2)\n\n (out,) = fd.execute([inp, w1, w2], _enable_options=[\"host_ir_lowering\"])\n torch.testing.assert_close(out, ref)","source_hash":"cdc184c555d84abe002bbfc0df03863e1dadcdd4755f0092c3a3e7568d5751af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_stream.test_matmul","uri":"program://Fuser/function/tests.python.direct.test_stream.test_matmul#L10-L50","kind":"function","name":"test_matmul","path":"tests/python/direct/test_stream.py","language":"python","start_line":10,"end_line":50,"context_start_line":1,"context_end_line":70,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nfrom nvfuser_direct import FusionDefinition, ParallelType, DataType\n\n\ndef test_matmul():\n c = 3\n\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out = fd.ops.matmul(inp, w)\n fd.add_output(out)\n\n out.outer_split(1, c)\n out.axis(1).parallelize(ParallelType.stream)\n # With NVFUSER_DUMP=host_ir, you'll see the host IR container like the\n # following:\n #\n # %HostIrContainer { (T0_g_float[iS0{i0}, iS1{i2}], T1_g_float[istreamIdx7{3}, iS11{i2}, iS8{( ceilDiv(i4, 3) )}]) -> (T2_g_float[istreamIdx9{3}, iS4{i0}, iS10{( ceilDiv(i4, 3) )}, rS6{i2}]) :\n # FOR i18 from 0 to 3:\n # T2_g_float[istreamIdx9{3}, iS4{i0}, iS10{( ceilDiv(i4, 3) )}, rS6{i2}]\n # = matmul(T0_g_float[iS0{i0}, iS1{i2}],\n # T1_g_float[istreamIdx7{3}, iS11{i2}, iS8{( ceilDiv(i4, 3) )}])\n # } // %HostIrContainer\n\n inp = torch.testing.make_tensor(5, 7, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w = torch.testing.make_tensor(7, c * 2, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n ref = torch.matmul(inp, w)\n\n with torch.profiler.profile(record_shapes=True) as profile:\n (out,) = fd.execute(\n [inp, w],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n torch.testing.assert_close(out, ref)\n\n matmul_events = [event for event in profile.events() if event.name == \"aten::mm\"]\n assert len(matmul_events) == c\n for event in matmul_events:\n assert event.input_shapes == [[5, 7], [7, 2], [5, 2]]\n\n\ndef test_two_matmuls_inlinable():\n c = 3\n\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w1 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w2 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out = fd.ops.matmul(inp, w1)\n out = fd.ops.matmul(out, w2)\n fd.add_output(out)\n\n inp.outer_split(0, c)\n inp.axis(0).parallelize(ParallelType.stream)\n # With NVFUSER_DUMP=host_ir, you'll see the host IR container like the\n # following:\n #\n # %HostIrContainer { (T0_g_float[istreamIdx12{3}, iS13{( ceilDiv(i0, 3) )}, iS1{i2}], T1_g_float[iS14{i2}, iS3{i4}], T2_g_float[iS15{i4}, iS5{i6}]) -> (T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}]) :\n # T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}] = ALLOCATE(buffer=T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}], mem_type=global, size=( i0 * i6 ), zero_init=false, resets_to_zero=false)","source_hash":"cdc184c555d84abe002bbfc0df03863e1dadcdd4755f0092c3a3e7568d5751af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_stream.test_two_matmuls_inlinable","uri":"program://Fuser/function/tests.python.direct.test_stream.test_two_matmuls_inlinable#L53-L105","kind":"function","name":"test_two_matmuls_inlinable","path":"tests/python/direct/test_stream.py","language":"python","start_line":53,"end_line":105,"context_start_line":33,"context_end_line":125,"code":" )\n w = torch.testing.make_tensor(7, c * 2, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n ref = torch.matmul(inp, w)\n\n with torch.profiler.profile(record_shapes=True) as profile:\n (out,) = fd.execute(\n [inp, w],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n torch.testing.assert_close(out, ref)\n\n matmul_events = [event for event in profile.events() if event.name == \"aten::mm\"]\n assert len(matmul_events) == c\n for event in matmul_events:\n assert event.input_shapes == [[5, 7], [7, 2], [5, 2]]\n\n\ndef test_two_matmuls_inlinable():\n c = 3\n\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w1 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w2 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out = fd.ops.matmul(inp, w1)\n out = fd.ops.matmul(out, w2)\n fd.add_output(out)\n\n inp.outer_split(0, c)\n inp.axis(0).parallelize(ParallelType.stream)\n # With NVFUSER_DUMP=host_ir, you'll see the host IR container like the\n # following:\n #\n # %HostIrContainer { (T0_g_float[istreamIdx12{3}, iS13{( ceilDiv(i0, 3) )}, iS1{i2}], T1_g_float[iS14{i2}, iS3{i4}], T2_g_float[iS15{i4}, iS5{i6}]) -> (T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}]) :\n # T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}] = ALLOCATE(buffer=T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}], mem_type=global, size=( i0 * i6 ), zero_init=false, resets_to_zero=false)\n # FOR i99 from 0 to 3:\n # T5_l_float[istreamIdx22{3}, iS23{( ceilDiv(i0, 3) )}, iS21{i2}] = ShardByStream(T0_g_float[istreamIdx12{3}, iS13{( ceilDiv(i0, 3) )}, iS1{i2}], stream_index = i99)\n # T3_g_float[istreamIdx16{3}, iS17{( ceilDiv(i0, 3) )}, iS7{i4}, rS8{i2}]\n # = matmul(T5_l_float[istreamIdx22{3}, iS23{( ceilDiv(i0, 3) )}, iS21{i2}],\n # T1_g_float[iS14{i2}, iS3{i4}])\n # T6_l_float[istreamIdx26{3}, iS27{( ceilDiv(i0, 3) )}, iS25{i6}] = ShardByStream(T4_g_float[istreamIdx18{3}, iS19{( ceilDiv(i0, 3) )}, iS10{i6}, rS11{i4}], stream_index = i99)\n # T6_l_float[istreamIdx26{3}, iS27{( ceilDiv(i0, 3) )}, iS25{i6}]\n # = matmul(T3_g_float[istreamIdx16{3}, iS17{( ceilDiv(i0, 3) )}, iS7{i4}, rS8{i2}],\n # T2_g_float[iS15{i4}, iS5{i6}])\n # } // %HostIrContainer\n\n inp = torch.testing.make_tensor(c * 2, 3, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w1 = torch.testing.make_tensor(3, 5, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w2 = torch.testing.make_tensor(5, 3, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n ref = torch.matmul(torch.matmul(inp, w1), w2)\n\n with torch.profiler.profile(record_shapes=True) as profile:\n (out,) = fd.execute(\n [inp, w1, w2],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n torch.testing.assert_close(out, ref)\n\n matmul_events = [event for event in profile.events() if event.name == \"aten::mm\"]\n assert len(matmul_events) == c * 2\n for event in matmul_events:\n # The `m` dimension is split into `c` chunks, so each chunk will have `m == 2`.\n assert event.input_shapes[0][0] == 2\n\n\ndef test_two_matmuls_not_inlinable():\n c = 3\n\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w1 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w2 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out = fd.ops.matmul(inp, w1)\n out = fd.ops.matmul(out, w2)\n fd.add_output(out)\n\n w1.split(1, c, inner_split=False)\n w1.axis(1).parallelize(ParallelType.stream)\n out.split(0, c, inner_split=False)\n out.axis(0).parallelize(ParallelType.stream)\n\n # After sharding propagation, the IR looks like the following:\n #","source_hash":"cdc184c555d84abe002bbfc0df03863e1dadcdd4755f0092c3a3e7568d5751af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_stream.test_two_matmuls_not_inlinable","uri":"program://Fuser/function/tests.python.direct.test_stream.test_two_matmuls_not_inlinable#L108-L159","kind":"function","name":"test_two_matmuls_not_inlinable","path":"tests/python/direct/test_stream.py","language":"python","start_line":108,"end_line":159,"context_start_line":88,"context_end_line":159,"code":" w2 = torch.testing.make_tensor(5, 3, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n ref = torch.matmul(torch.matmul(inp, w1), w2)\n\n with torch.profiler.profile(record_shapes=True) as profile:\n (out,) = fd.execute(\n [inp, w1, w2],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n torch.testing.assert_close(out, ref)\n\n matmul_events = [event for event in profile.events() if event.name == \"aten::mm\"]\n assert len(matmul_events) == c * 2\n for event in matmul_events:\n # The `m` dimension is split into `c` chunks, so each chunk will have `m == 2`.\n assert event.input_shapes[0][0] == 2\n\n\ndef test_two_matmuls_not_inlinable():\n c = 3\n\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w1 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w2 = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out = fd.ops.matmul(inp, w1)\n out = fd.ops.matmul(out, w2)\n fd.add_output(out)\n\n w1.split(1, c, inner_split=False)\n w1.axis(1).parallelize(ParallelType.stream)\n out.split(0, c, inner_split=False)\n out.axis(0).parallelize(ParallelType.stream)\n\n # After sharding propagation, the IR looks like the following:\n #\n # in: [m, k] w1: [k, n]\n # /\\\n # c\n # |\n # | matmul\n # v\n # [m, n] w2: [n, k]\n # /\\\n # c\n # |\n # | matmul\n # v\n # out: [m, k]\n # /\\\n # c\n #\n # The first matmul is column-wise (dimension n) parallel, and the second\n # row-wise (dimension m) parallel. They have to stay in different loops.\n # Therefore, the output of the first matmul (of shape [m, n]) has to be\n # fully allocated.\n\n inp = torch.testing.make_tensor(c * 2, 3, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w1 = torch.testing.make_tensor(3, c * 5, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n w2 = torch.testing.make_tensor(c * 5, 3, dtype=torch.int32, device=\"cuda\").to(\n torch.float32\n )\n ref = torch.matmul(torch.matmul(inp, w1), w2)\n\n (out,) = fd.execute([inp, w1, w2], _enable_options=[\"host_ir_lowering\"])\n torch.testing.assert_close(out, ref)","source_hash":"cdc184c555d84abe002bbfc0df03863e1dadcdd4755f0092c3a3e7568d5751af","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_sdpa","uri":"program://Fuser/module/tests.python.direct.test_sdpa#L1-L522","kind":"module","name":"tests.python.direct.test_sdpa","path":"tests/python/direct/test_sdpa.py","language":"python","start_line":1,"end_line":522,"context_start_line":1,"context_end_line":522,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport itertools\nimport math\nimport pytest\nimport torch\nimport torch.nn.functional as F\nfrom enum import Enum, auto\nfrom functools import partial\n\nfrom nvfuser_direct import (\n FusionDefinition,\n DataType,\n)\nfrom python.direct_utils import (\n is_pre_ampere,\n define_sdpa_rng_state,\n verify_stride_order,\n)\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\ndef test_softmax_logsumexp(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n dtype=DataType.BFloat16,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n dtype=DataType.BFloat16,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n dtype=DataType.BFloat16,\n )\n (\n _,\n lse,\n *_,\n ) = fd.ops.sdpfa_fwd(q, k, v, dropout_p=None, is_causal=None, scale=None)\n fd.add_output(lse)\n\n n, h, l, s, e = 1, 1, 4, 4, 8\n inputs = [\n torch.ones((n, h, l, e), dtype=torch.bfloat16, device=\"cuda\"),\n torch.ones((n, h, s, e), dtype=torch.bfloat16, device=\"cuda\"),\n torch.ones((n, h, s, e), dtype=torch.bfloat16, device=\"cuda\"),\n ]\n\n from torch.nn.attention import SDPBackend, sdpa_kernel\n\n with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func,\n inputs,\n )\n # Ignoring size-1 dimensions, `q @ k^T / sqrt(e)` generates a `l`x`s`\n # matrix full of `sqrt(e)`s. Therefore, the logsumexp of each row is\n # expected to be log(exp(sqrt(e)) * s) = log(s) + sqrt(e).\n torch.testing.assert_close(\n nvf_out[0].cpu(), torch.full((n, h, l), math.log(s) + e**0.5)\n )\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\ndef test_sdpa_fwd(nvfuser_direct_test):\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n dropout_p, is_causal, scale = None, None, None\n if has_dropout:\n dropout_p = fd.define_scalar(value=None, dtype=DataType.Double)\n if has_causal:\n is_causal = fd.define_scalar(value=None, dtype=DataType.Bool)\n if has_scale:\n scale = fd.define_scalar(value=None, dtype=DataType.Double)\n attn, *_ = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n fd.add_output(attn)\n\n N, H, L, S, E = 4, 8, 16, 16, 8\n qkv = [\n torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\"),\n torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\"),\n torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\"),\n ]\n\n dropout_vals = [None, 0.0, 0.2]\n is_causal_vals = [None, True, False]\n scale_vals = [None, 1 / E**0.5, 1e-3]\n # TODO: Try to move this to pytest_ops.py. Currently, it does not work since the API between nvFuser and torch differs.\n for dropout_p, is_causal, scale in itertools.product(\n dropout_vals, is_causal_vals, scale_vals\n ):\n with nvfuser_direct_test.subTest(\n dropout_p=dropout_p, is_causal=is_causal, scale=scale\n ):\n from torch.nn.attention import SDPBackend, sdpa_kernel\n\n has_dropout = True if dropout_p is not None else False\n has_causal = True if is_causal is not None else False\n has_scale = True if scale is not None else False\n inputs = [*qkv]\n for param in [dropout_p, is_causal, scale]:\n if param is not None:\n inputs.append(param)\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(\n fusion_func,\n has_dropout=has_dropout,\n has_causal=has_causal,\n has_scale=has_scale,\n ),\n inputs,\n new_fusion_expected=None,\n )\n\n # Torch does not accept NoneType dropout_p, is_causal.\n dropout_p = 0.0 if dropout_p is None else dropout_p\n is_causal = False if is_causal is None else is_causal\n\n with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n torch.manual_seed(0)\n ref_out = F.scaled_dot_product_attention(\n *qkv, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n torch.testing.assert_close(nvf_out[0], ref_out)\n\n\n# Memory layout of query, key, value and output tensors.\nclass Layout(Enum):\n NHSE = auto()\n NSHE = auto()\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"layout\", [Layout.NHSE, Layout.NSHE])\ndef test_sdpa_fwd_bias_mask(nvfuser_direct_test, layout: Layout):\n match layout:\n case Layout.NHSE:\n stride_order = [3, 2, 1, 0]\n case Layout.NSHE:\n stride_order = [3, 1, 2, 0]\n\n with FusionDefinition() as fd:\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n bias = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n )\n mask = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.Bool,\n )\n attn, *_ = fd.ops.sdpfa_fwd(q, k, v, bias=bias, mask=mask)\n fd.add_output(attn)\n\n N, H, L, S, E = 11, 7, 5, 3, 2\n match layout:\n case Layout.NHSE:\n q = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n k = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n v = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n case Layout.NSHE:\n q = torch.randn(\n (N, L, H, E), dtype=torch.bfloat16, device=\"cuda\"\n ).transpose(1, 2)\n k = torch.randn(\n (N, S, H, E), dtype=torch.bfloat16, device=\"cuda\"\n ).transpose(1, 2)\n v = torch.randn(\n (N, S, H, E), dtype=torch.bfloat16, device=\"cuda\"\n ).transpose(1, 2)\n bias = torch.randn((N, H, L, S), dtype=torch.bfloat16, device=\"cuda\")\n mask = torch.rand((N, H, L, S), device=\"cuda\") > 0.3\n\n (out,) = fd.execute([q, k, v, bias, mask])\n\n attn_mask = (bias + torch.where(mask, 0.0, float(\"-inf\"))).to(dtype=bias.dtype)\n ref_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, attn_mask=attn_mask\n )\n torch.testing.assert_close(out, ref_out)\n verify_stride_order(out.stride(), stride_order)\n\n\ndef test_sdpa_bwd(nvfuser_direct_test):\n N, H, L, S, E = 4, 8, 16, 16, 8\n\n grad_output = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n q = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n k = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n v = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n\n dropout_vals = [None, 0.0, 0.2]\n is_causal_vals = [None, True, False]\n scale_vals = [None, 1 / E**0.5, 1e-3]\n\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n grad_output = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n output = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n logsumexp = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n )\n philox_seed, philox_offset = define_sdpa_rng_state(fd)\n\n dropout_p, is_causal, scale = None, None, None\n if has_dropout:\n dropout_p = fd.define_scalar(value=None, dtype=DataType.Double)\n if has_causal:\n is_causal = fd.define_scalar(value=None, dtype=DataType.Bool)\n if has_scale:\n scale = fd.define_scalar(value=None, dtype=DataType.Double)\n\n grad_query, grad_key, grad_value = fd.ops.sdpfa_bwd(\n grad_output,\n q,\n k,\n v,\n output,\n logsumexp,\n dropout_p,\n is_causal,\n philox_seed,\n philox_offset,\n scale,\n )\n fd.add_output(grad_query)\n fd.add_output(grad_key)\n fd.add_output(grad_value)\n\n for dropout_p, is_causal, scale in itertools.product(\n dropout_vals, is_causal_vals, scale_vals\n ):\n with nvfuser_direct_test.subTest(\n dropout_p=dropout_p, is_causal=is_causal, scale=scale\n ):\n # Torch does not accept NoneType dropout_p, is_causal.\n at_dropout_p = 0.0 if dropout_p is None else dropout_p\n at_is_causal = False if is_causal is None else is_causal\n\n (\n output,\n logsumexp,\n cum_seq_q,\n cum_seq_k,\n query_seq_len,\n key_seq_len,\n philox_seed,\n philox_offset,\n _,\n ) = torch.ops.aten._scaled_dot_product_flash_attention(\n q,\n k,\n v,\n at_dropout_p,\n at_is_causal,\n return_debug_mask=False,\n scale=scale,\n )\n ref_grad = torch.ops.aten._scaled_dot_product_flash_attention_backward(\n grad_output,\n q,\n k,\n v,\n output,\n logsumexp,\n cum_seq_q,\n cum_seq_k,\n query_seq_len,\n key_seq_len,\n at_dropout_p,\n at_is_causal,\n philox_seed,\n philox_offset,\n scale=scale,\n )\n\n has_dropout = True if dropout_p is not None else False\n has_causal = True if is_causal is not None else False\n has_scale = True if scale is not None else False\n\n inputs = [\n grad_output,\n q,\n k,\n v,\n output,\n logsumexp,\n philox_seed,\n philox_offset,\n ]\n for param in [dropout_p, is_causal, scale]:\n if param is not None:\n inputs.append(param)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(\n fusion_func,\n has_dropout=has_dropout,\n has_causal=has_causal,\n has_scale=has_scale,\n ),\n inputs,\n new_fusion_expected=None,\n )\n torch.testing.assert_close(nvf_out[0], ref_grad[0])\n torch.testing.assert_close(nvf_out[1], ref_grad[1])\n torch.testing.assert_close(nvf_out[2], ref_grad[2])\n\n\ndef test_sdpa_fwd_bwd(nvfuser_direct_test):\n N, H, L, S, E = 4, 8, 16, 16, 8\n\n dropout_vals = [None, 0.0, 0.2]\n is_causal_vals = [None, True, False]\n scale_vals = [None, 1 / E**0.5, 1e-3]\n\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n grad_out = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n\n dropout_p, is_causal, scale = None, None, None\n if has_dropout:\n dropout_p = fd.define_scalar(value=None, dtype=DataType.Double)\n if has_causal:\n is_causal = fd.define_scalar(value=None, dtype=DataType.Bool)\n if has_scale:\n scale = fd.define_scalar(value=None, dtype=DataType.Double)\n\n output, logsumexp, philox_seed, philox_offset = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n grad_query, grad_key, grad_value = fd.ops.sdpfa_bwd(\n grad_out,\n q,\n k,\n v,\n output,\n logsumexp,\n dropout_p,\n is_causal,\n philox_seed,\n philox_offset,\n scale,\n )\n\n fd.add_output(output)\n fd.add_output(grad_query)\n fd.add_output(grad_key)\n fd.add_output(grad_value)\n\n for dropout_p, is_causal, scale in itertools.product(\n dropout_vals, is_causal_vals, scale_vals\n ):\n with nvfuser_direct_test.subTest(\n dropout_p=dropout_p, is_causal=is_causal, scale=scale\n ):\n from torch.nn.attention import SDPBackend, sdpa_kernel\n\n q = torch.randn(\n (N, H, L, E),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=True,\n )\n k = torch.randn(\n (N, H, S, E),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=True,\n )\n v = torch.randn(\n (N, H, S, E),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=True,\n )\n grad_output = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n\n has_dropout = True if dropout_p is not None else False\n has_causal = True if is_causal is not None else False\n has_scale = True if scale is not None else False\n\n inputs = [q, k, v, grad_output]\n for param in [dropout_p, is_causal, scale]:\n if param is not None:\n inputs.append(param)\n\n # Torch does not accept NoneType dropout_p, is_causal.\n dropout_p = 0.0 if dropout_p is None else dropout_p\n is_causal = False if is_causal is None else is_causal\n\n with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n torch.manual_seed(0)\n ref_out = F.scaled_dot_product_attention(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n ref_out.backward(grad_output)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(\n fusion_func,\n has_dropout=has_dropout,\n has_causal=has_causal,\n has_scale=has_scale,\n ),\n inputs,\n new_fusion_expected=None,\n )\n torch.testing.assert_close(nvf_out[0], ref_out)\n torch.testing.assert_close(nvf_out[1], q.grad)\n torch.testing.assert_close(nvf_out[2], k.grad)\n torch.testing.assert_close(nvf_out[3], v.grad)","source_hash":"587a5c41942d1189804c29b016e7fadd5af5634c6898654314b71364cdf3c2e6","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_sdpa.test_softmax_logsumexp","uri":"program://Fuser/function/tests.python.direct.test_sdpa.test_softmax_logsumexp#L29-L69","kind":"function","name":"test_softmax_logsumexp","path":"tests/python/direct/test_sdpa.py","language":"python","start_line":29,"end_line":69,"context_start_line":9,"context_end_line":89,"code":"import torch\nimport torch.nn.functional as F\nfrom enum import Enum, auto\nfrom functools import partial\n\nfrom nvfuser_direct import (\n FusionDefinition,\n DataType,\n)\nfrom python.direct_utils import (\n is_pre_ampere,\n define_sdpa_rng_state,\n verify_stride_order,\n)\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\ndef test_softmax_logsumexp(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n dtype=DataType.BFloat16,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n dtype=DataType.BFloat16,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n dtype=DataType.BFloat16,\n )\n (\n _,\n lse,\n *_,\n ) = fd.ops.sdpfa_fwd(q, k, v, dropout_p=None, is_causal=None, scale=None)\n fd.add_output(lse)\n\n n, h, l, s, e = 1, 1, 4, 4, 8\n inputs = [\n torch.ones((n, h, l, e), dtype=torch.bfloat16, device=\"cuda\"),\n torch.ones((n, h, s, e), dtype=torch.bfloat16, device=\"cuda\"),\n torch.ones((n, h, s, e), dtype=torch.bfloat16, device=\"cuda\"),\n ]\n\n from torch.nn.attention import SDPBackend, sdpa_kernel\n\n with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func,\n inputs,\n )\n # Ignoring size-1 dimensions, `q @ k^T / sqrt(e)` generates a `l`x`s`\n # matrix full of `sqrt(e)`s. Therefore, the logsumexp of each row is\n # expected to be log(exp(sqrt(e)) * s) = log(s) + sqrt(e).\n torch.testing.assert_close(\n nvf_out[0].cpu(), torch.full((n, h, l), math.log(s) + e**0.5)\n )\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\ndef test_sdpa_fwd(nvfuser_direct_test):\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,","source_hash":"587a5c41942d1189804c29b016e7fadd5af5634c6898654314b71364cdf3c2e6","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_sdpa.test_sdpa_fwd","uri":"program://Fuser/function/tests.python.direct.test_sdpa.test_sdpa_fwd#L76-L156","kind":"function","name":"test_sdpa_fwd","path":"tests/python/direct/test_sdpa.py","language":"python","start_line":76,"end_line":156,"context_start_line":56,"context_end_line":176,"code":"\n from torch.nn.attention import SDPBackend, sdpa_kernel\n\n with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func,\n inputs,\n )\n # Ignoring size-1 dimensions, `q @ k^T / sqrt(e)` generates a `l`x`s`\n # matrix full of `sqrt(e)`s. Therefore, the logsumexp of each row is\n # expected to be log(exp(sqrt(e)) * s) = log(s) + sqrt(e).\n torch.testing.assert_close(\n nvf_out[0].cpu(), torch.full((n, h, l), math.log(s) + e**0.5)\n )\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\ndef test_sdpa_fwd(nvfuser_direct_test):\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n dropout_p, is_causal, scale = None, None, None\n if has_dropout:\n dropout_p = fd.define_scalar(value=None, dtype=DataType.Double)\n if has_causal:\n is_causal = fd.define_scalar(value=None, dtype=DataType.Bool)\n if has_scale:\n scale = fd.define_scalar(value=None, dtype=DataType.Double)\n attn, *_ = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n fd.add_output(attn)\n\n N, H, L, S, E = 4, 8, 16, 16, 8\n qkv = [\n torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\"),\n torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\"),\n torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\"),\n ]\n\n dropout_vals = [None, 0.0, 0.2]\n is_causal_vals = [None, True, False]\n scale_vals = [None, 1 / E**0.5, 1e-3]\n # TODO: Try to move this to pytest_ops.py. Currently, it does not work since the API between nvFuser and torch differs.\n for dropout_p, is_causal, scale in itertools.product(\n dropout_vals, is_causal_vals, scale_vals\n ):\n with nvfuser_direct_test.subTest(\n dropout_p=dropout_p, is_causal=is_causal, scale=scale\n ):\n from torch.nn.attention import SDPBackend, sdpa_kernel\n\n has_dropout = True if dropout_p is not None else False\n has_causal = True if is_causal is not None else False\n has_scale = True if scale is not None else False\n inputs = [*qkv]\n for param in [dropout_p, is_causal, scale]:\n if param is not None:\n inputs.append(param)\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(\n fusion_func,\n has_dropout=has_dropout,\n has_causal=has_causal,\n has_scale=has_scale,\n ),\n inputs,\n new_fusion_expected=None,\n )\n\n # Torch does not accept NoneType dropout_p, is_causal.\n dropout_p = 0.0 if dropout_p is None else dropout_p\n is_causal = False if is_causal is None else is_causal\n\n with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n torch.manual_seed(0)\n ref_out = F.scaled_dot_product_attention(\n *qkv, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n torch.testing.assert_close(nvf_out[0], ref_out)\n\n\n# Memory layout of query, key, value and output tensors.\nclass Layout(Enum):\n NHSE = auto()\n NSHE = auto()\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"layout\", [Layout.NHSE, Layout.NSHE])\ndef test_sdpa_fwd_bias_mask(nvfuser_direct_test, layout: Layout):\n match layout:\n case Layout.NHSE:\n stride_order = [3, 2, 1, 0]\n case Layout.NSHE:\n stride_order = [3, 1, 2, 0]\n","source_hash":"587a5c41942d1189804c29b016e7fadd5af5634c6898654314b71364cdf3c2e6","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_sdpa.Layout","uri":"program://Fuser/class/tests.python.direct.test_sdpa.Layout#L160-L162","kind":"class","name":"Layout","path":"tests/python/direct/test_sdpa.py","language":"python","start_line":160,"end_line":162,"context_start_line":140,"context_end_line":182,"code":" has_causal=has_causal,\n has_scale=has_scale,\n ),\n inputs,\n new_fusion_expected=None,\n )\n\n # Torch does not accept NoneType dropout_p, is_causal.\n dropout_p = 0.0 if dropout_p is None else dropout_p\n is_causal = False if is_causal is None else is_causal\n\n with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n torch.manual_seed(0)\n ref_out = F.scaled_dot_product_attention(\n *qkv, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n torch.testing.assert_close(nvf_out[0], ref_out)\n\n\n# Memory layout of query, key, value and output tensors.\nclass Layout(Enum):\n NHSE = auto()\n NSHE = auto()\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"layout\", [Layout.NHSE, Layout.NSHE])\ndef test_sdpa_fwd_bias_mask(nvfuser_direct_test, layout: Layout):\n match layout:\n case Layout.NHSE:\n stride_order = [3, 2, 1, 0]\n case Layout.NSHE:\n stride_order = [3, 1, 2, 0]\n\n with FusionDefinition() as fd:\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n stride_order=stride_order,","source_hash":"587a5c41942d1189804c29b016e7fadd5af5634c6898654314b71364cdf3c2e6","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_sdpa.test_sdpa_fwd_bias_mask","uri":"program://Fuser/function/tests.python.direct.test_sdpa.test_sdpa_fwd_bias_mask#L170-L235","kind":"function","name":"test_sdpa_fwd_bias_mask","path":"tests/python/direct/test_sdpa.py","language":"python","start_line":170,"end_line":235,"context_start_line":150,"context_end_line":255,"code":"\n with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n torch.manual_seed(0)\n ref_out = F.scaled_dot_product_attention(\n *qkv, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n torch.testing.assert_close(nvf_out[0], ref_out)\n\n\n# Memory layout of query, key, value and output tensors.\nclass Layout(Enum):\n NHSE = auto()\n NSHE = auto()\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"layout\", [Layout.NHSE, Layout.NSHE])\ndef test_sdpa_fwd_bias_mask(nvfuser_direct_test, layout: Layout):\n match layout:\n case Layout.NHSE:\n stride_order = [3, 2, 1, 0]\n case Layout.NSHE:\n stride_order = [3, 1, 2, 0]\n\n with FusionDefinition() as fd:\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n bias = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n )\n mask = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.Bool,\n )\n attn, *_ = fd.ops.sdpfa_fwd(q, k, v, bias=bias, mask=mask)\n fd.add_output(attn)\n\n N, H, L, S, E = 11, 7, 5, 3, 2\n match layout:\n case Layout.NHSE:\n q = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n k = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n v = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n case Layout.NSHE:\n q = torch.randn(\n (N, L, H, E), dtype=torch.bfloat16, device=\"cuda\"\n ).transpose(1, 2)\n k = torch.randn(\n (N, S, H, E), dtype=torch.bfloat16, device=\"cuda\"\n ).transpose(1, 2)\n v = torch.randn(\n (N, S, H, E), dtype=torch.bfloat16, device=\"cuda\"\n ).transpose(1, 2)\n bias = torch.randn((N, H, L, S), dtype=torch.bfloat16, device=\"cuda\")\n mask = torch.rand((N, H, L, S), device=\"cuda\") > 0.3\n\n (out,) = fd.execute([q, k, v, bias, mask])\n\n attn_mask = (bias + torch.where(mask, 0.0, float(\"-inf\"))).to(dtype=bias.dtype)\n ref_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, attn_mask=attn_mask\n )\n torch.testing.assert_close(out, ref_out)\n verify_stride_order(out.stride(), stride_order)\n\n\ndef test_sdpa_bwd(nvfuser_direct_test):\n N, H, L, S, E = 4, 8, 16, 16, 8\n\n grad_output = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n q = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n k = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n v = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n\n dropout_vals = [None, 0.0, 0.2]\n is_causal_vals = [None, True, False]\n scale_vals = [None, 1 / E**0.5, 1e-3]\n\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n grad_output = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,","source_hash":"587a5c41942d1189804c29b016e7fadd5af5634c6898654314b71364cdf3c2e6","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_sdpa.test_sdpa_bwd","uri":"program://Fuser/function/tests.python.direct.test_sdpa.test_sdpa_bwd#L238-L393","kind":"function","name":"test_sdpa_bwd","path":"tests/python/direct/test_sdpa.py","language":"python","start_line":238,"end_line":393,"context_start_line":218,"context_end_line":413,"code":" ).transpose(1, 2)\n k = torch.randn(\n (N, S, H, E), dtype=torch.bfloat16, device=\"cuda\"\n ).transpose(1, 2)\n v = torch.randn(\n (N, S, H, E), dtype=torch.bfloat16, device=\"cuda\"\n ).transpose(1, 2)\n bias = torch.randn((N, H, L, S), dtype=torch.bfloat16, device=\"cuda\")\n mask = torch.rand((N, H, L, S), device=\"cuda\") > 0.3\n\n (out,) = fd.execute([q, k, v, bias, mask])\n\n attn_mask = (bias + torch.where(mask, 0.0, float(\"-inf\"))).to(dtype=bias.dtype)\n ref_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, attn_mask=attn_mask\n )\n torch.testing.assert_close(out, ref_out)\n verify_stride_order(out.stride(), stride_order)\n\n\ndef test_sdpa_bwd(nvfuser_direct_test):\n N, H, L, S, E = 4, 8, 16, 16, 8\n\n grad_output = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n q = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n k = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n v = torch.randn((N, H, S, E), dtype=torch.bfloat16, device=\"cuda\")\n\n dropout_vals = [None, 0.0, 0.2]\n is_causal_vals = [None, True, False]\n scale_vals = [None, 1 / E**0.5, 1e-3]\n\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n grad_output = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n output = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n logsumexp = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n )\n philox_seed, philox_offset = define_sdpa_rng_state(fd)\n\n dropout_p, is_causal, scale = None, None, None\n if has_dropout:\n dropout_p = fd.define_scalar(value=None, dtype=DataType.Double)\n if has_causal:\n is_causal = fd.define_scalar(value=None, dtype=DataType.Bool)\n if has_scale:\n scale = fd.define_scalar(value=None, dtype=DataType.Double)\n\n grad_query, grad_key, grad_value = fd.ops.sdpfa_bwd(\n grad_output,\n q,\n k,\n v,\n output,\n logsumexp,\n dropout_p,\n is_causal,\n philox_seed,\n philox_offset,\n scale,\n )\n fd.add_output(grad_query)\n fd.add_output(grad_key)\n fd.add_output(grad_value)\n\n for dropout_p, is_causal, scale in itertools.product(\n dropout_vals, is_causal_vals, scale_vals\n ):\n with nvfuser_direct_test.subTest(\n dropout_p=dropout_p, is_causal=is_causal, scale=scale\n ):\n # Torch does not accept NoneType dropout_p, is_causal.\n at_dropout_p = 0.0 if dropout_p is None else dropout_p\n at_is_causal = False if is_causal is None else is_causal\n\n (\n output,\n logsumexp,\n cum_seq_q,\n cum_seq_k,\n query_seq_len,\n key_seq_len,\n philox_seed,\n philox_offset,\n _,\n ) = torch.ops.aten._scaled_dot_product_flash_attention(\n q,\n k,\n v,\n at_dropout_p,\n at_is_causal,\n return_debug_mask=False,\n scale=scale,\n )\n ref_grad = torch.ops.aten._scaled_dot_product_flash_attention_backward(\n grad_output,\n q,\n k,\n v,\n output,\n logsumexp,\n cum_seq_q,\n cum_seq_k,\n query_seq_len,\n key_seq_len,\n at_dropout_p,\n at_is_causal,\n philox_seed,\n philox_offset,\n scale=scale,\n )\n\n has_dropout = True if dropout_p is not None else False\n has_causal = True if is_causal is not None else False\n has_scale = True if scale is not None else False\n\n inputs = [\n grad_output,\n q,\n k,\n v,\n output,\n logsumexp,\n philox_seed,\n philox_offset,\n ]\n for param in [dropout_p, is_causal, scale]:\n if param is not None:\n inputs.append(param)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(\n fusion_func,\n has_dropout=has_dropout,\n has_causal=has_causal,\n has_scale=has_scale,\n ),\n inputs,\n new_fusion_expected=None,\n )\n torch.testing.assert_close(nvf_out[0], ref_grad[0])\n torch.testing.assert_close(nvf_out[1], ref_grad[1])\n torch.testing.assert_close(nvf_out[2], ref_grad[2])\n\n\ndef test_sdpa_fwd_bwd(nvfuser_direct_test):\n N, H, L, S, E = 4, 8, 16, 16, 8\n\n dropout_vals = [None, 0.0, 0.2]\n is_causal_vals = [None, True, False]\n scale_vals = [None, 1 / E**0.5, 1e-3]\n\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],","source_hash":"587a5c41942d1189804c29b016e7fadd5af5634c6898654314b71364cdf3c2e6","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_sdpa.test_sdpa_fwd_bwd","uri":"program://Fuser/function/tests.python.direct.test_sdpa.test_sdpa_fwd_bwd#L396-L522","kind":"function","name":"test_sdpa_fwd_bwd","path":"tests/python/direct/test_sdpa.py","language":"python","start_line":396,"end_line":522,"context_start_line":376,"context_end_line":522,"code":" ]\n for param in [dropout_p, is_causal, scale]:\n if param is not None:\n inputs.append(param)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(\n fusion_func,\n has_dropout=has_dropout,\n has_causal=has_causal,\n has_scale=has_scale,\n ),\n inputs,\n new_fusion_expected=None,\n )\n torch.testing.assert_close(nvf_out[0], ref_grad[0])\n torch.testing.assert_close(nvf_out[1], ref_grad[1])\n torch.testing.assert_close(nvf_out[2], ref_grad[2])\n\n\ndef test_sdpa_fwd_bwd(nvfuser_direct_test):\n N, H, L, S, E = 4, 8, 16, 16, 8\n\n dropout_vals = [None, 0.0, 0.2]\n is_causal_vals = [None, True, False]\n scale_vals = [None, 1 / E**0.5, 1e-3]\n\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n grad_out = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n\n dropout_p, is_causal, scale = None, None, None\n if has_dropout:\n dropout_p = fd.define_scalar(value=None, dtype=DataType.Double)\n if has_causal:\n is_causal = fd.define_scalar(value=None, dtype=DataType.Bool)\n if has_scale:\n scale = fd.define_scalar(value=None, dtype=DataType.Double)\n\n output, logsumexp, philox_seed, philox_offset = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n grad_query, grad_key, grad_value = fd.ops.sdpfa_bwd(\n grad_out,\n q,\n k,\n v,\n output,\n logsumexp,\n dropout_p,\n is_causal,\n philox_seed,\n philox_offset,\n scale,\n )\n\n fd.add_output(output)\n fd.add_output(grad_query)\n fd.add_output(grad_key)\n fd.add_output(grad_value)\n\n for dropout_p, is_causal, scale in itertools.product(\n dropout_vals, is_causal_vals, scale_vals\n ):\n with nvfuser_direct_test.subTest(\n dropout_p=dropout_p, is_causal=is_causal, scale=scale\n ):\n from torch.nn.attention import SDPBackend, sdpa_kernel\n\n q = torch.randn(\n (N, H, L, E),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=True,\n )\n k = torch.randn(\n (N, H, S, E),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=True,\n )\n v = torch.randn(\n (N, H, S, E),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=True,\n )\n grad_output = torch.randn((N, H, L, E), dtype=torch.bfloat16, device=\"cuda\")\n\n has_dropout = True if dropout_p is not None else False\n has_causal = True if is_causal is not None else False\n has_scale = True if scale is not None else False\n\n inputs = [q, k, v, grad_output]\n for param in [dropout_p, is_causal, scale]:\n if param is not None:\n inputs.append(param)\n\n # Torch does not accept NoneType dropout_p, is_causal.\n dropout_p = 0.0 if dropout_p is None else dropout_p\n is_causal = False if is_causal is None else is_causal\n\n with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n torch.manual_seed(0)\n ref_out = F.scaled_dot_product_attention(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n ref_out.backward(grad_output)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(\n fusion_func,\n has_dropout=has_dropout,\n has_causal=has_causal,\n has_scale=has_scale,\n ),\n inputs,\n new_fusion_expected=None,\n )\n torch.testing.assert_close(nvf_out[0], ref_out)\n torch.testing.assert_close(nvf_out[1], q.grad)\n torch.testing.assert_close(nvf_out[2], k.grad)\n torch.testing.assert_close(nvf_out[3], v.grad)","source_hash":"587a5c41942d1189804c29b016e7fadd5af5634c6898654314b71364cdf3c2e6","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_sdpa.fusion_func","uri":"program://Fuser/function/tests.python.direct.test_sdpa.fusion_func#L403-L459","kind":"function","name":"fusion_func","path":"tests/python/direct/test_sdpa.py","language":"python","start_line":403,"end_line":459,"context_start_line":383,"context_end_line":479,"code":" fusion_func,\n has_dropout=has_dropout,\n has_causal=has_causal,\n has_scale=has_scale,\n ),\n inputs,\n new_fusion_expected=None,\n )\n torch.testing.assert_close(nvf_out[0], ref_grad[0])\n torch.testing.assert_close(nvf_out[1], ref_grad[1])\n torch.testing.assert_close(nvf_out[2], ref_grad[2])\n\n\ndef test_sdpa_fwd_bwd(nvfuser_direct_test):\n N, H, L, S, E = 4, 8, 16, 16, 8\n\n dropout_vals = [None, 0.0, 0.2]\n is_causal_vals = [None, True, False]\n scale_vals = [None, 1 / E**0.5, 1e-3]\n\n def fusion_func(\n fd: FusionDefinition, has_dropout: bool, has_causal: bool, has_scale: bool\n ):\n q = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n k = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n v = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n grad_out = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n\n dropout_p, is_causal, scale = None, None, None\n if has_dropout:\n dropout_p = fd.define_scalar(value=None, dtype=DataType.Double)\n if has_causal:\n is_causal = fd.define_scalar(value=None, dtype=DataType.Bool)\n if has_scale:\n scale = fd.define_scalar(value=None, dtype=DataType.Double)\n\n output, logsumexp, philox_seed, philox_offset = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal, scale=scale\n )\n grad_query, grad_key, grad_value = fd.ops.sdpfa_bwd(\n grad_out,\n q,\n k,\n v,\n output,\n logsumexp,\n dropout_p,\n is_causal,\n philox_seed,\n philox_offset,\n scale,\n )\n\n fd.add_output(output)\n fd.add_output(grad_query)\n fd.add_output(grad_key)\n fd.add_output(grad_value)\n\n for dropout_p, is_causal, scale in itertools.product(\n dropout_vals, is_causal_vals, scale_vals\n ):\n with nvfuser_direct_test.subTest(\n dropout_p=dropout_p, is_causal=is_causal, scale=scale\n ):\n from torch.nn.attention import SDPBackend, sdpa_kernel\n\n q = torch.randn(\n (N, H, L, E),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=True,\n )\n k = torch.randn(\n (N, H, S, E),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=True,","source_hash":"587a5c41942d1189804c29b016e7fadd5af5634c6898654314b71364cdf3c2e6","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend","uri":"program://Fuser/module/tests.python.direct.test_python_frontend#L1-L2861","kind":"module","name":"tests.python.direct.test_python_frontend","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1,"end_line":2861,"context_start_line":1,"context_end_line":2861,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport torch._refs as refs\nimport torch._prims as prims\n\nfrom nvfuser_direct import (\n FusionDefinition,\n DataType,\n compute_tensor_descriptor,\n)\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\n\nimport pytest\nimport itertools\nfrom python.direct_utils import (\n is_pre_ampere,\n is_pre_hopper,\n is_pre_blackwell,\n verify_stride_order,\n)\n\nfrom python.direct_utils.narrow_precision import (\n pytorch_nvfp4_quantize,\n fp4_to_fp32,\n unpack_fp4,\n)\n\n\ndef test_basic(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\"),\n torch.ones(2, 4, 8, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Float)\n\n fd.add_output(t4)\n\n # Check that keepdim argument is not in fd_str\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv2 = fd.ops.add(tv0, tv1)\n tv3 = fd.ops.mul(tv2, 3.00000)\n tv4 = fd.ops.sum(tv3, dims=[2], dtype=DataType.Float)\n fd.add_output(tv4)\"\"\"\n\n # t0 and t1 are ones(2, 4, 8) tensors.\n # t2 = t0 + t1 = twos(2, 4, 8)\n # t3 = t2 * 3.0 = sixes(2,4,8)\n # t4 = sum(t3, dim=-1) = forty-eights(2, 4)\n # The expected output is a tensor of 48's.\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3.0, dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_basic_fp16(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.float16),\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.float16),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Float)\n\n t5 = fd.ops.cast(t4, DataType.Half)\n fd.add_output(t5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3.0, dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_define_contiguous_tensor(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([2, 3], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(2, 3, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_noncontiguous_tensor(nvfuser_direct_test):\n in_tensor = torch.randn(8, device=\"cuda\").as_strided([2, 3], [4, 1])\n\n def fusion_func(fd: FusionDefinition):\n inp = fd.from_pytorch(in_tensor)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_broadcast_tensor(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2, 1], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, 1, device=\"cuda\").as_strided([1, 2, 1], [0, 1, 0])\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_tensor_contiguity_with_stride_order(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2], contiguity=True, stride_order=[0, 1])\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_cast_scalar(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.int32),\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.int32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n c1 = fd.ops.cast(c0, DataType.Int32)\n t3 = fd.ops.mul(t2, c1)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Int32)\n\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3, dim=-1, dtype=torch.int32)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_cast_double_to_half(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0h = fd.ops.cast(t0, DataType.Half)\n t1h = fd.ops.cast(t1, DataType.Half)\n t2 = fd.ops.add(t0h, t1h)\n t3 = fd.ops.relu(t2)\n t4 = fd.ops.cast(t3, DataType.Half)\n\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0].to(torch.half) + inputs[1].to(torch.half))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_cast_fp8(nvfuser_direct_test):\n def fn(in_type, out_type):\n inputs = [\n torch.randn([5, 5], device=\"cuda\").to(in_type),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.cast(T0, dtype=torch_dtype_to_nvfuser_dtype(out_type))\n fd.add_output(T1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0].to(out_type)\n if in_type == torch.float8_e8m0fnu or out_type == torch.float8_e8m0fnu:\n # Eager mode uses manual bit manipulation, and nvFuser uses\n # hardware instructions. Unfortunately, these implementations\n # do not match exactly. e8m0 can only represent 2^x, so we are\n # asserting that the x of the two results are off by at most 1.\n nvf_out_fp32 = nvf_out[0].to(torch.float32)\n eager_out_fp32 = eager_out.to(torch.float32)\n rel_err = eager_out_fp32.div(nvf_out_fp32).max().item()\n nvfuser_direct_test.assertTrue(rel_err <= 2 and rel_err >= 0.5)\n else:\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n for type0 in [torch.double, torch.float32, torch.float16, torch.bfloat16]:\n type1_list = [torch.float8_e4m3fn, torch.float8_e5m2]\n if not is_pre_blackwell():\n type1_list.append(torch.float8_e8m0fnu)\n for type1 in type1_list:\n fn(type0, type1)\n fn(type1, type0)\n\n\ndef test_promote_to_double(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float16),\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t2 = fd.ops.add(t0, t1)\n t5 = fd.ops.relu(t2)\n\n fd.add_output(t5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0] + inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_broadcast(nvfuser_direct_test):\n inputs = [\n torch.randn(3, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast(t0, [True, False, True])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [1]), inputs[1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_implicit_broadcast_input(nvfuser_direct_test):\n inputs = [\n torch.randn(3, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, [2, 3, 4], [1])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [1]), inputs[1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_explicit_broadcast_input(nvfuser_direct_test):\n inputs = [\n torch.randn(1, 1, 4, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, inputs[1].size(), [0, 1, 2])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [0, 1, 2]), inputs[1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_broadcast_mixing(nvfuser_direct_test):\n inputs = [\n torch.randn(3, 1, device=\"cuda\"),\n torch.randn(3, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, [3, 3], [0])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(inputs[0], prims.broadcast_in_dim(inputs[1], [3, 3], [0]))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_dynamic_bcast_in_dim(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n tv0 = fd.define_tensor(\n shape=[1, -1], contiguity=[None, True], dtype=DataType.Float, is_cpu=False\n )\n c4 = fd.define_scalar(None, dtype=DataType.Int)\n c5 = fd.define_scalar(None, dtype=DataType.Int)\n tv1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n tv3 = fd.ops.broadcast_in_dim(tv0, (c4, c5), (0, 1))\n tv4 = fd.ops.add(tv3, tv1)\n fd.add_output(tv4)\n\n t0 = torch.randn([1, 10], dtype=torch.float32, device=\"cuda:0\")\n c4 = 5\n c5 = 10\n t1 = torch.randn([5, 10], dtype=torch.float32, device=\"cuda:0\")\n inputs = [t0, c4, c5, t1]\n out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, validate_results=True\n )\n\n\ndef test_dynamic_full(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n c4 = fd.define_scalar(None, dtype=DataType.Int)\n c5 = fd.define_scalar(None, dtype=DataType.Int)\n c6 = fd.define_scalar(None, dtype=DataType.Float)\n tv1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n tv3 = fd.ops.full((c4, c5), c6, DataType.Float)\n tv4 = fd.ops.add(tv3, tv1)\n fd.add_output(tv4)\n\n c4 = 5\n c5 = 10\n c6 = 2.5\n t1 = torch.randn([5, 10], dtype=torch.float32, device=\"cuda:0\")\n inputs = [c4, c5, c6, t1]\n out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, validate_results=True\n )\n\n\ndef test_tensor_ndim(nvfuser_direct_test):\n shape = [2 for i in range(12)]\n new_shape = shape[:9]\n new_shape.append(8)\n\n inputs = [torch.randn(shape, device=\"cuda\"), new_shape]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n n_shape = fd.define_vector(10)\n\n t1 = fd.ops.reshape(t0, n_shape)\n t2 = fd.ops.sum(t1, dims=[3])\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum(inputs[0].reshape(new_shape), dim=3)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_execute_with_tuple_and_list(nvfuser_direct_test):\n shape = [2, 3, 4]\n new_shape = [6, 4]\n\n tensor = torch.randn(shape, device=\"cuda\")\n inputs_with_list = [tensor, new_shape]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs_with_list[0])\n n_shape = fd.define_vector(2)\n\n t1 = fd.ops.reshape(t0, n_shape)\n t2 = fd.ops.sum(t1, dims=[0])\n\n fd.add_output(t2)\n\n eager_out = torch.sum(inputs_with_list[0].reshape(new_shape), dim=0)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs_with_list)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n inputs_with_tuple = [tensor, tuple(new_shape)]\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs_with_tuple, new_fusion_expected=False\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_dynamic_reshape(nvfuser_direct_test):\n def dynamic_reshape(fd: FusionDefinition) -> None:\n x = fd.define_tensor([-1, -1], [True, True])\n d0 = fd.ops.size(x, 0)\n d1 = fd.define_scalar(dtype=DataType.Int32)\n d2 = fd.define_scalar(dtype=DataType.Int32)\n y = fd.ops.reshape(x, [d0, d1, d2])\n fd.add_output(y)\n\n x = torch.rand(3, 4, device=\"cuda\")\n ys, _ = nvfuser_direct_test.exec_nvfuser(dynamic_reshape, [x, 2, 2])\n nvfuser_direct_test.assertEqual(len(ys), 1)\n y = ys[0]\n\n nvfuser_direct_test.assertEqual(y.shape, torch.Size([3, 2, 2]))\n nvfuser_direct_test.assertEqual(x.flatten(), y.flatten())\n\n\ndef test_reshape_dynamic(nvfuser_direct_test):\n inputs = [\n 32,\n torch.randn((192,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4, 8, 6), (48, 6, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Int)\n T1 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n S2 = fd.define_scalar(1, dtype=DataType.Int)\n S3 = fd.ops.mul(S2, S0)\n S4 = fd.ops.signbit(S3)\n S5 = fd.define_scalar(False, dtype=DataType.Bool)\n S6 = fd.ops.ne(S4, S5)\n S7 = fd.define_scalar(192, dtype=DataType.Int)\n S8 = fd.ops.fmod(S7, S3)\n S9 = fd.ops.cast(S8, dtype=DataType.Int)\n S10 = fd.define_scalar(0, dtype=DataType.Int)\n S11 = fd.ops.ne(S9, S10)\n S12 = fd.ops.bitwise_and(S6, S11)\n S13 = fd.define_scalar(192, dtype=DataType.Int)\n S14 = fd.ops.reciprocal(S3)\n S15 = fd.ops.mul(S13, S14)\n S16 = fd.ops.cast(S12, dtype=DataType.Int)\n S17 = fd.ops.sub(S15, S16)\n T19 = fd.ops.reshape(T1, new_shape=[S0, S17])\n T20 = fd.ops.sum(T19, dims=[1], keepdim=False, dtype=DataType.Null)\n fd.add_output(T20)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\n# Test empty symbolic tensors can be reshaped\n# See https://github.com/NVIDIA/Fuser/issues/2362\ndef test_empty_reshape(nvfuser_direct_test):\n inputs = [torch.randint(0, 10, (0, 1, 2, 3, 4), dtype=torch.int64, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1, -1, -1, -1],\n contiguity=[False, None, True, True, True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[4, 3, 2, 1, 0],\n )\n S2 = fd.define_scalar(5, dtype=DataType.Int)\n S3 = fd.define_scalar(0, dtype=DataType.Int)\n T5 = fd.ops.reshape(T0, new_shape=[S2, S3])\n fd.add_output(T5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_squeeze(nvfuser_direct_test):\n t0_sizes = [4]\n t1_sizes = [1, 4, 1]\n t2_sizes = [2, 1, 4]\n inputs = [\n torch.randn(*t0_sizes, device=\"cuda\"),\n torch.randn(*t1_sizes, device=\"cuda\"),\n torch.randn(*t2_sizes, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1], contiguity=[True])\n t1 = fd.define_tensor(sizes=t1_sizes, strides=[4, 1, 1])\n t2 = fd.define_tensor(sizes=t2_sizes, strides=[4, 4, 1])\n t3 = fd.ops.squeeze(t1, [0, -1])\n t4 = fd.ops.squeeze(t2, [-2])\n t5 = fd.ops.sum(t4, [0])\n t6 = fd.ops.mul(t0, t3)\n t7 = fd.ops.mul(t6, t5)\n fd.add_output(t7)\n\n # Check that squeeze does not print default argument: squeeze_expanded\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False)\n tv1 = fd.define_tensor(shape=[1, -1, 1], contiguity=[None, True, None], dtype=DataType.Float, is_cpu=False)\n tv2 = fd.define_tensor(shape=[-1, 1, -1], contiguity=[True, None, True], dtype=DataType.Float, is_cpu=False)\n tv3 = fd.ops.squeeze(tv1, dims=[0, 2])\n tv6 = fd.ops.mul(tv0, tv3)\n tv4 = fd.ops.squeeze(tv2, dims=[1])\n tv5 = fd.ops.sum(tv4, dims=[0], dtype=DataType.Float)\n tv7 = fd.ops.mul(tv6, tv5)\n fd.add_output(tv7)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n\n v1 = torch.sum(inputs[1], [0, -1])\n v2 = torch.sum(inputs[2], [0, 1])\n eager_out = inputs[0] * v1 * v2\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n# Test that expanded dimensions can be reduced properly\n# See https://github.com/NVIDIA/Fuser/issues/1678\ndef test_expanded_reduction(nvfuser_direct_test):\n inputs = [torch.tensor(1.0, device=\"cuda\").as_strided((2, 3), (0, 0))]\n\n for keepdim in [False, True]:\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[None, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.sum(T0, dims=[0], keepdim=keepdim, dtype=DataType.Null)\n fd.add_output(T1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(\n nvf_out[0], inputs[0].sum(dim=0, keepdim=keepdim)\n )\n\n\ndef test_expand(nvfuser_direct_test):\n inputs = [\n torch.randn(1, 1, 4, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.expand(t0, inputs[1].size())\n t2 = fd.ops.mul(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0].expand(inputs[1].size()) * inputs[1]\n nvfuser_direct_test.assertEqual(eager\n# ... truncated ...","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_basic","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_basic#L33-L68","kind":"function","name":"test_basic","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":33,"end_line":68,"context_start_line":13,"context_end_line":88,"code":" compute_tensor_descriptor,\n)\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\n\nimport pytest\nimport itertools\nfrom python.direct_utils import (\n is_pre_ampere,\n is_pre_hopper,\n is_pre_blackwell,\n verify_stride_order,\n)\n\nfrom python.direct_utils.narrow_precision import (\n pytorch_nvfp4_quantize,\n fp4_to_fp32,\n unpack_fp4,\n)\n\n\ndef test_basic(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\"),\n torch.ones(2, 4, 8, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Float)\n\n fd.add_output(t4)\n\n # Check that keepdim argument is not in fd_str\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv2 = fd.ops.add(tv0, tv1)\n tv3 = fd.ops.mul(tv2, 3.00000)\n tv4 = fd.ops.sum(tv3, dims=[2], dtype=DataType.Float)\n fd.add_output(tv4)\"\"\"\n\n # t0 and t1 are ones(2, 4, 8) tensors.\n # t2 = t0 + t1 = twos(2, 4, 8)\n # t3 = t2 * 3.0 = sixes(2,4,8)\n # t4 = sum(t3, dim=-1) = forty-eights(2, 4)\n # The expected output is a tensor of 48's.\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3.0, dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_basic_fp16(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.float16),\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.float16),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Float)\n\n t5 = fd.ops.cast(t4, DataType.Half)\n fd.add_output(t5)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_basic_fp16","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_basic_fp16#L71-L91","kind":"function","name":"test_basic_fp16","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":71,"end_line":91,"context_start_line":51,"context_end_line":111,"code":" fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv2 = fd.ops.add(tv0, tv1)\n tv3 = fd.ops.mul(tv2, 3.00000)\n tv4 = fd.ops.sum(tv3, dims=[2], dtype=DataType.Float)\n fd.add_output(tv4)\"\"\"\n\n # t0 and t1 are ones(2, 4, 8) tensors.\n # t2 = t0 + t1 = twos(2, 4, 8)\n # t3 = t2 * 3.0 = sixes(2,4,8)\n # t4 = sum(t3, dim=-1) = forty-eights(2, 4)\n # The expected output is a tensor of 48's.\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3.0, dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_basic_fp16(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.float16),\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.float16),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Float)\n\n t5 = fd.ops.cast(t4, DataType.Half)\n fd.add_output(t5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3.0, dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_define_contiguous_tensor(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([2, 3], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(2, 3, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_noncontiguous_tensor(nvfuser_direct_test):\n in_tensor = torch.randn(8, device=\"cuda\").as_strided([2, 3], [4, 1])\n\n def fusion_func(fd: FusionDefinition):\n inp = fd.from_pytorch(in_tensor)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_define_contiguous_tensor","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_define_contiguous_tensor#L94-L102","kind":"function","name":"test_define_contiguous_tensor","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":94,"end_line":102,"context_start_line":74,"context_end_line":122,"code":" torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.float16),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Float)\n\n t5 = fd.ops.cast(t4, DataType.Half)\n fd.add_output(t5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3.0, dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_define_contiguous_tensor(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([2, 3], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(2, 3, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_noncontiguous_tensor(nvfuser_direct_test):\n in_tensor = torch.randn(8, device=\"cuda\").as_strided([2, 3], [4, 1])\n\n def fusion_func(fd: FusionDefinition):\n inp = fd.from_pytorch(in_tensor)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_broadcast_tensor(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2, 1], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_define_noncontiguous_tensor","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_define_noncontiguous_tensor#L105-L114","kind":"function","name":"test_define_noncontiguous_tensor","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":105,"end_line":114,"context_start_line":85,"context_end_line":134,"code":"\n t5 = fd.ops.cast(t4, DataType.Half)\n fd.add_output(t5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3.0, dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_define_contiguous_tensor(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([2, 3], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(2, 3, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_noncontiguous_tensor(nvfuser_direct_test):\n in_tensor = torch.randn(8, device=\"cuda\").as_strided([2, 3], [4, 1])\n\n def fusion_func(fd: FusionDefinition):\n inp = fd.from_pytorch(in_tensor)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_broadcast_tensor(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2, 1], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, 1, device=\"cuda\").as_strided([1, 2, 1], [0, 1, 0])\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_tensor_contiguity_with_stride_order(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2], contiguity=True, stride_order=[0, 1])\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, device=\"cuda\")","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_define_broadcast_tensor","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_define_broadcast_tensor#L117-L125","kind":"function","name":"test_define_broadcast_tensor","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":117,"end_line":125,"context_start_line":97,"context_end_line":145,"code":" out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(2, 3, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_noncontiguous_tensor(nvfuser_direct_test):\n in_tensor = torch.randn(8, device=\"cuda\").as_strided([2, 3], [4, 1])\n\n def fusion_func(fd: FusionDefinition):\n inp = fd.from_pytorch(in_tensor)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_broadcast_tensor(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2, 1], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, 1, device=\"cuda\").as_strided([1, 2, 1], [0, 1, 0])\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_tensor_contiguity_with_stride_order(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2], contiguity=True, stride_order=[0, 1])\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_cast_scalar(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.int32),\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.int32),\n ]\n\n def fusion_func(fd: FusionDefinition):","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_define_tensor_contiguity_with_stride_order","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_define_tensor_contiguity_with_stride_order#L128-L136","kind":"function","name":"test_define_tensor_contiguity_with_stride_order","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":128,"end_line":136,"context_start_line":108,"context_end_line":156,"code":" def fusion_func(fd: FusionDefinition):\n inp = fd.from_pytorch(in_tensor)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_broadcast_tensor(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2, 1], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, 1, device=\"cuda\").as_strided([1, 2, 1], [0, 1, 0])\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_tensor_contiguity_with_stride_order(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2], contiguity=True, stride_order=[0, 1])\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_cast_scalar(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.int32),\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.int32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n c1 = fd.ops.cast(c0, DataType.Int32)\n t3 = fd.ops.mul(t2, c1)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Int32)\n\n fd.add_output(t4)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_cast_scalar","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_cast_scalar#L139-L159","kind":"function","name":"test_cast_scalar","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":139,"end_line":159,"context_start_line":119,"context_end_line":179,"code":" inp = fd.define_tensor([1, 2, 1], contiguity=True)\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, 1, device=\"cuda\").as_strided([1, 2, 1], [0, 1, 0])\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_define_tensor_contiguity_with_stride_order(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 2], contiguity=True, stride_order=[0, 1])\n out = fd.ops.add(inp, inp)\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 2, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(out_tensors[0], in_tensor * 2)\n\n\ndef test_cast_scalar(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.int32),\n torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.int32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n c1 = fd.ops.cast(c0, DataType.Int32)\n t3 = fd.ops.mul(t2, c1)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Int32)\n\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3, dim=-1, dtype=torch.int32)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_cast_double_to_half(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0h = fd.ops.cast(t0, DataType.Half)\n t1h = fd.ops.cast(t1, DataType.Half)\n t2 = fd.ops.add(t0h, t1h)\n t3 = fd.ops.relu(t2)\n t4 = fd.ops.cast(t3, DataType.Half)\n\n fd.add_output(t4)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_cast_double_to_half","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_cast_double_to_half#L162-L182","kind":"function","name":"test_cast_double_to_half","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":162,"end_line":182,"context_start_line":142,"context_end_line":202,"code":" torch.ones(2, 4, 8, device=\"cuda\", dtype=torch.int32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n c1 = fd.ops.cast(c0, DataType.Int32)\n t3 = fd.ops.mul(t2, c1)\n t4 = fd.ops.sum(t3, [-1], False, DataType.Int32)\n\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum((inputs[0] + inputs[1]) * 3, dim=-1, dtype=torch.int32)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_cast_double_to_half(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0h = fd.ops.cast(t0, DataType.Half)\n t1h = fd.ops.cast(t1, DataType.Half)\n t2 = fd.ops.add(t0h, t1h)\n t3 = fd.ops.relu(t2)\n t4 = fd.ops.cast(t3, DataType.Half)\n\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0].to(torch.half) + inputs[1].to(torch.half))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_cast_fp8(nvfuser_direct_test):\n def fn(in_type, out_type):\n inputs = [\n torch.randn([5, 5], device=\"cuda\").to(in_type),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.cast(T0, dtype=torch_dtype_to_nvfuser_dtype(out_type))\n fd.add_output(T1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0].to(out_type)\n if in_type == torch.float8_e8m0fnu or out_type == torch.float8_e8m0fnu:\n # Eager mode uses manual bit manipulation, and nvFuser uses","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_cast_fp8","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_cast_fp8#L188-L219","kind":"function","name":"test_cast_fp8","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":188,"end_line":219,"context_start_line":168,"context_end_line":239,"code":" def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0h = fd.ops.cast(t0, DataType.Half)\n t1h = fd.ops.cast(t1, DataType.Half)\n t2 = fd.ops.add(t0h, t1h)\n t3 = fd.ops.relu(t2)\n t4 = fd.ops.cast(t3, DataType.Half)\n\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0].to(torch.half) + inputs[1].to(torch.half))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_cast_fp8(nvfuser_direct_test):\n def fn(in_type, out_type):\n inputs = [\n torch.randn([5, 5], device=\"cuda\").to(in_type),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.cast(T0, dtype=torch_dtype_to_nvfuser_dtype(out_type))\n fd.add_output(T1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0].to(out_type)\n if in_type == torch.float8_e8m0fnu or out_type == torch.float8_e8m0fnu:\n # Eager mode uses manual bit manipulation, and nvFuser uses\n # hardware instructions. Unfortunately, these implementations\n # do not match exactly. e8m0 can only represent 2^x, so we are\n # asserting that the x of the two results are off by at most 1.\n nvf_out_fp32 = nvf_out[0].to(torch.float32)\n eager_out_fp32 = eager_out.to(torch.float32)\n rel_err = eager_out_fp32.div(nvf_out_fp32).max().item()\n nvfuser_direct_test.assertTrue(rel_err <= 2 and rel_err >= 0.5)\n else:\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n for type0 in [torch.double, torch.float32, torch.float16, torch.bfloat16]:\n type1_list = [torch.float8_e4m3fn, torch.float8_e5m2]\n if not is_pre_blackwell():\n type1_list.append(torch.float8_e8m0fnu)\n for type1 in type1_list:\n fn(type0, type1)\n fn(type1, type0)\n\n\ndef test_promote_to_double(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float16),\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t2 = fd.ops.add(t0, t1)\n t5 = fd.ops.relu(t2)\n\n fd.add_output(t5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0] + inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_promote_to_double","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_promote_to_double#L222-L239","kind":"function","name":"test_promote_to_double","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":222,"end_line":239,"context_start_line":202,"context_end_line":259,"code":" # Eager mode uses manual bit manipulation, and nvFuser uses\n # hardware instructions. Unfortunately, these implementations\n # do not match exactly. e8m0 can only represent 2^x, so we are\n # asserting that the x of the two results are off by at most 1.\n nvf_out_fp32 = nvf_out[0].to(torch.float32)\n eager_out_fp32 = eager_out.to(torch.float32)\n rel_err = eager_out_fp32.div(nvf_out_fp32).max().item()\n nvfuser_direct_test.assertTrue(rel_err <= 2 and rel_err >= 0.5)\n else:\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n for type0 in [torch.double, torch.float32, torch.float16, torch.bfloat16]:\n type1_list = [torch.float8_e4m3fn, torch.float8_e5m2]\n if not is_pre_blackwell():\n type1_list.append(torch.float8_e8m0fnu)\n for type1 in type1_list:\n fn(type0, type1)\n fn(type1, type0)\n\n\ndef test_promote_to_double(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float16),\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t2 = fd.ops.add(t0, t1)\n t5 = fd.ops.relu(t2)\n\n fd.add_output(t5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0] + inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_broadcast(nvfuser_direct_test):\n inputs = [\n torch.randn(3, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast(t0, [True, False, True])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [1]), inputs[1]","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_broadcast","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_broadcast#L242-L261","kind":"function","name":"test_broadcast","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":242,"end_line":261,"context_start_line":222,"context_end_line":281,"code":"def test_promote_to_double(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float16),\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t2 = fd.ops.add(t0, t1)\n t5 = fd.ops.relu(t2)\n\n fd.add_output(t5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0] + inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_broadcast(nvfuser_direct_test):\n inputs = [\n torch.randn(3, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast(t0, [True, False, True])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [1]), inputs[1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_implicit_broadcast_input(nvfuser_direct_test):\n inputs = [\n torch.randn(3, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, [2, 3, 4], [1])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [1]), inputs[1]","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_implicit_broadcast_input","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_implicit_broadcast_input#L264-L283","kind":"function","name":"test_implicit_broadcast_input","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":264,"end_line":283,"context_start_line":244,"context_end_line":303,"code":" torch.randn(3, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast(t0, [True, False, True])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [1]), inputs[1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_implicit_broadcast_input(nvfuser_direct_test):\n inputs = [\n torch.randn(3, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, [2, 3, 4], [1])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [1]), inputs[1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_explicit_broadcast_input(nvfuser_direct_test):\n inputs = [\n torch.randn(1, 1, 4, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, inputs[1].size(), [0, 1, 2])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [0, 1, 2]), inputs[1]","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_explicit_broadcast_input","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_explicit_broadcast_input#L286-L305","kind":"function","name":"test_explicit_broadcast_input","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":286,"end_line":305,"context_start_line":266,"context_end_line":325,"code":" torch.randn(3, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, [2, 3, 4], [1])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [1]), inputs[1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_explicit_broadcast_input(nvfuser_direct_test):\n inputs = [\n torch.randn(1, 1, 4, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, inputs[1].size(), [0, 1, 2])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [0, 1, 2]), inputs[1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_broadcast_mixing(nvfuser_direct_test):\n inputs = [\n torch.randn(3, 1, device=\"cuda\"),\n torch.randn(3, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, [3, 3], [0])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(inputs[0], prims.broadcast_in_dim(inputs[1], [3, 3], [0]))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_broadcast_mixing","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_broadcast_mixing#L308-L325","kind":"function","name":"test_broadcast_mixing","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":308,"end_line":325,"context_start_line":288,"context_end_line":345,"code":" torch.randn(1, 1, 4, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, inputs[1].size(), [0, 1, 2])\n t2 = fd.ops.add(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(inputs[0], inputs[1].size(), [0, 1, 2]), inputs[1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_broadcast_mixing(nvfuser_direct_test):\n inputs = [\n torch.randn(3, 1, device=\"cuda\"),\n torch.randn(3, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, [3, 3], [0])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(inputs[0], prims.broadcast_in_dim(inputs[1], [3, 3], [0]))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_dynamic_bcast_in_dim(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n tv0 = fd.define_tensor(\n shape=[1, -1], contiguity=[None, True], dtype=DataType.Float, is_cpu=False\n )\n c4 = fd.define_scalar(None, dtype=DataType.Int)\n c5 = fd.define_scalar(None, dtype=DataType.Int)\n tv1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n tv3 = fd.ops.broadcast_in_dim(tv0, (c4, c5), (0, 1))\n tv4 = fd.ops.add(tv3, tv1)\n fd.add_output(tv4)\n\n t0 = torch.randn([1, 10], dtype=torch.float32, device=\"cuda:0\")\n c4 = 5\n c5 = 10\n t1 = torch.randn([5, 10], dtype=torch.float32, device=\"cuda:0\")","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_dynamic_bcast_in_dim","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_dynamic_bcast_in_dim#L328-L349","kind":"function","name":"test_dynamic_bcast_in_dim","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":328,"end_line":349,"context_start_line":308,"context_end_line":369,"code":"def test_broadcast_mixing(nvfuser_direct_test):\n inputs = [\n torch.randn(3, 1, device=\"cuda\"),\n torch.randn(3, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, [3, 3], [0])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(inputs[0], prims.broadcast_in_dim(inputs[1], [3, 3], [0]))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_dynamic_bcast_in_dim(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n tv0 = fd.define_tensor(\n shape=[1, -1], contiguity=[None, True], dtype=DataType.Float, is_cpu=False\n )\n c4 = fd.define_scalar(None, dtype=DataType.Int)\n c5 = fd.define_scalar(None, dtype=DataType.Int)\n tv1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n tv3 = fd.ops.broadcast_in_dim(tv0, (c4, c5), (0, 1))\n tv4 = fd.ops.add(tv3, tv1)\n fd.add_output(tv4)\n\n t0 = torch.randn([1, 10], dtype=torch.float32, device=\"cuda:0\")\n c4 = 5\n c5 = 10\n t1 = torch.randn([5, 10], dtype=torch.float32, device=\"cuda:0\")\n inputs = [t0, c4, c5, t1]\n out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, validate_results=True\n )\n\n\ndef test_dynamic_full(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n c4 = fd.define_scalar(None, dtype=DataType.Int)\n c5 = fd.define_scalar(None, dtype=DataType.Int)\n c6 = fd.define_scalar(None, dtype=DataType.Float)\n tv1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n tv3 = fd.ops.full((c4, c5), c6, DataType.Float)\n tv4 = fd.ops.add(tv3, tv1)\n fd.add_output(tv4)\n\n c4 = 5\n c5 = 10\n c6 = 2.5\n t1 = torch.randn([5, 10], dtype=torch.float32, device=\"cuda:0\")\n inputs = [c4, c5, c6, t1]\n out, _ = nvfuser_direct_test.exec_nvfuser(","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_dynamic_full","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_dynamic_full#L352-L371","kind":"function","name":"test_dynamic_full","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":352,"end_line":371,"context_start_line":332,"context_end_line":391,"code":" )\n c4 = fd.define_scalar(None, dtype=DataType.Int)\n c5 = fd.define_scalar(None, dtype=DataType.Int)\n tv1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n tv3 = fd.ops.broadcast_in_dim(tv0, (c4, c5), (0, 1))\n tv4 = fd.ops.add(tv3, tv1)\n fd.add_output(tv4)\n\n t0 = torch.randn([1, 10], dtype=torch.float32, device=\"cuda:0\")\n c4 = 5\n c5 = 10\n t1 = torch.randn([5, 10], dtype=torch.float32, device=\"cuda:0\")\n inputs = [t0, c4, c5, t1]\n out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, validate_results=True\n )\n\n\ndef test_dynamic_full(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n c4 = fd.define_scalar(None, dtype=DataType.Int)\n c5 = fd.define_scalar(None, dtype=DataType.Int)\n c6 = fd.define_scalar(None, dtype=DataType.Float)\n tv1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n tv3 = fd.ops.full((c4, c5), c6, DataType.Float)\n tv4 = fd.ops.add(tv3, tv1)\n fd.add_output(tv4)\n\n c4 = 5\n c5 = 10\n c6 = 2.5\n t1 = torch.randn([5, 10], dtype=torch.float32, device=\"cuda:0\")\n inputs = [c4, c5, c6, t1]\n out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, validate_results=True\n )\n\n\ndef test_tensor_ndim(nvfuser_direct_test):\n shape = [2 for i in range(12)]\n new_shape = shape[:9]\n new_shape.append(8)\n\n inputs = [torch.randn(shape, device=\"cuda\"), new_shape]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n n_shape = fd.define_vector(10)\n\n t1 = fd.ops.reshape(t0, n_shape)\n t2 = fd.ops.sum(t1, dims=[3])\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum(inputs[0].reshape(new_shape), dim=3)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_tensor_ndim","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_tensor_ndim#L374-L392","kind":"function","name":"test_tensor_ndim","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":374,"end_line":392,"context_start_line":354,"context_end_line":412,"code":" c4 = fd.define_scalar(None, dtype=DataType.Int)\n c5 = fd.define_scalar(None, dtype=DataType.Int)\n c6 = fd.define_scalar(None, dtype=DataType.Float)\n tv1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n tv3 = fd.ops.full((c4, c5), c6, DataType.Float)\n tv4 = fd.ops.add(tv3, tv1)\n fd.add_output(tv4)\n\n c4 = 5\n c5 = 10\n c6 = 2.5\n t1 = torch.randn([5, 10], dtype=torch.float32, device=\"cuda:0\")\n inputs = [c4, c5, c6, t1]\n out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, validate_results=True\n )\n\n\ndef test_tensor_ndim(nvfuser_direct_test):\n shape = [2 for i in range(12)]\n new_shape = shape[:9]\n new_shape.append(8)\n\n inputs = [torch.randn(shape, device=\"cuda\"), new_shape]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n n_shape = fd.define_vector(10)\n\n t1 = fd.ops.reshape(t0, n_shape)\n t2 = fd.ops.sum(t1, dims=[3])\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum(inputs[0].reshape(new_shape), dim=3)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_execute_with_tuple_and_list(nvfuser_direct_test):\n shape = [2, 3, 4]\n new_shape = [6, 4]\n\n tensor = torch.randn(shape, device=\"cuda\")\n inputs_with_list = [tensor, new_shape]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs_with_list[0])\n n_shape = fd.define_vector(2)\n\n t1 = fd.ops.reshape(t0, n_shape)\n t2 = fd.ops.sum(t1, dims=[0])\n\n fd.add_output(t2)\n\n eager_out = torch.sum(inputs_with_list[0].reshape(new_shape), dim=0)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_execute_with_tuple_and_list","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_execute_with_tuple_and_list#L395-L420","kind":"function","name":"test_execute_with_tuple_and_list","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":395,"end_line":420,"context_start_line":375,"context_end_line":440,"code":" shape = [2 for i in range(12)]\n new_shape = shape[:9]\n new_shape.append(8)\n\n inputs = [torch.randn(shape, device=\"cuda\"), new_shape]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n n_shape = fd.define_vector(10)\n\n t1 = fd.ops.reshape(t0, n_shape)\n t2 = fd.ops.sum(t1, dims=[3])\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum(inputs[0].reshape(new_shape), dim=3)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_execute_with_tuple_and_list(nvfuser_direct_test):\n shape = [2, 3, 4]\n new_shape = [6, 4]\n\n tensor = torch.randn(shape, device=\"cuda\")\n inputs_with_list = [tensor, new_shape]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs_with_list[0])\n n_shape = fd.define_vector(2)\n\n t1 = fd.ops.reshape(t0, n_shape)\n t2 = fd.ops.sum(t1, dims=[0])\n\n fd.add_output(t2)\n\n eager_out = torch.sum(inputs_with_list[0].reshape(new_shape), dim=0)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs_with_list)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n inputs_with_tuple = [tensor, tuple(new_shape)]\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs_with_tuple, new_fusion_expected=False\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_dynamic_reshape(nvfuser_direct_test):\n def dynamic_reshape(fd: FusionDefinition) -> None:\n x = fd.define_tensor([-1, -1], [True, True])\n d0 = fd.ops.size(x, 0)\n d1 = fd.define_scalar(dtype=DataType.Int32)\n d2 = fd.define_scalar(dtype=DataType.Int32)\n y = fd.ops.reshape(x, [d0, d1, d2])\n fd.add_output(y)\n\n x = torch.rand(3, 4, device=\"cuda\")\n ys, _ = nvfuser_direct_test.exec_nvfuser(dynamic_reshape, [x, 2, 2])\n nvfuser_direct_test.assertEqual(len(ys), 1)\n y = ys[0]\n\n nvfuser_direct_test.assertEqual(y.shape, torch.Size([3, 2, 2]))\n nvfuser_direct_test.assertEqual(x.flatten(), y.flatten())\n\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_dynamic_reshape","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_dynamic_reshape#L423-L438","kind":"function","name":"test_dynamic_reshape","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":423,"end_line":438,"context_start_line":403,"context_end_line":458,"code":" t0 = fd.from_pytorch(inputs_with_list[0])\n n_shape = fd.define_vector(2)\n\n t1 = fd.ops.reshape(t0, n_shape)\n t2 = fd.ops.sum(t1, dims=[0])\n\n fd.add_output(t2)\n\n eager_out = torch.sum(inputs_with_list[0].reshape(new_shape), dim=0)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs_with_list)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n inputs_with_tuple = [tensor, tuple(new_shape)]\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs_with_tuple, new_fusion_expected=False\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_dynamic_reshape(nvfuser_direct_test):\n def dynamic_reshape(fd: FusionDefinition) -> None:\n x = fd.define_tensor([-1, -1], [True, True])\n d0 = fd.ops.size(x, 0)\n d1 = fd.define_scalar(dtype=DataType.Int32)\n d2 = fd.define_scalar(dtype=DataType.Int32)\n y = fd.ops.reshape(x, [d0, d1, d2])\n fd.add_output(y)\n\n x = torch.rand(3, 4, device=\"cuda\")\n ys, _ = nvfuser_direct_test.exec_nvfuser(dynamic_reshape, [x, 2, 2])\n nvfuser_direct_test.assertEqual(len(ys), 1)\n y = ys[0]\n\n nvfuser_direct_test.assertEqual(y.shape, torch.Size([3, 2, 2]))\n nvfuser_direct_test.assertEqual(x.flatten(), y.flatten())\n\n\ndef test_reshape_dynamic(nvfuser_direct_test):\n inputs = [\n 32,\n torch.randn((192,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4, 8, 6), (48, 6, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Int)\n T1 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n S2 = fd.define_scalar(1, dtype=DataType.Int)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_reshape_dynamic","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_reshape_dynamic#L441-L478","kind":"function","name":"test_reshape_dynamic","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":441,"end_line":478,"context_start_line":421,"context_end_line":498,"code":"\n\ndef test_dynamic_reshape(nvfuser_direct_test):\n def dynamic_reshape(fd: FusionDefinition) -> None:\n x = fd.define_tensor([-1, -1], [True, True])\n d0 = fd.ops.size(x, 0)\n d1 = fd.define_scalar(dtype=DataType.Int32)\n d2 = fd.define_scalar(dtype=DataType.Int32)\n y = fd.ops.reshape(x, [d0, d1, d2])\n fd.add_output(y)\n\n x = torch.rand(3, 4, device=\"cuda\")\n ys, _ = nvfuser_direct_test.exec_nvfuser(dynamic_reshape, [x, 2, 2])\n nvfuser_direct_test.assertEqual(len(ys), 1)\n y = ys[0]\n\n nvfuser_direct_test.assertEqual(y.shape, torch.Size([3, 2, 2]))\n nvfuser_direct_test.assertEqual(x.flatten(), y.flatten())\n\n\ndef test_reshape_dynamic(nvfuser_direct_test):\n inputs = [\n 32,\n torch.randn((192,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4, 8, 6), (48, 6, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Int)\n T1 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n S2 = fd.define_scalar(1, dtype=DataType.Int)\n S3 = fd.ops.mul(S2, S0)\n S4 = fd.ops.signbit(S3)\n S5 = fd.define_scalar(False, dtype=DataType.Bool)\n S6 = fd.ops.ne(S4, S5)\n S7 = fd.define_scalar(192, dtype=DataType.Int)\n S8 = fd.ops.fmod(S7, S3)\n S9 = fd.ops.cast(S8, dtype=DataType.Int)\n S10 = fd.define_scalar(0, dtype=DataType.Int)\n S11 = fd.ops.ne(S9, S10)\n S12 = fd.ops.bitwise_and(S6, S11)\n S13 = fd.define_scalar(192, dtype=DataType.Int)\n S14 = fd.ops.reciprocal(S3)\n S15 = fd.ops.mul(S13, S14)\n S16 = fd.ops.cast(S12, dtype=DataType.Int)\n S17 = fd.ops.sub(S15, S16)\n T19 = fd.ops.reshape(T1, new_shape=[S0, S17])\n T20 = fd.ops.sum(T19, dims=[1], keepdim=False, dtype=DataType.Null)\n fd.add_output(T20)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\n# Test empty symbolic tensors can be reshaped\n# See https://github.com/NVIDIA/Fuser/issues/2362\ndef test_empty_reshape(nvfuser_direct_test):\n inputs = [torch.randint(0, 10, (0, 1, 2, 3, 4), dtype=torch.int64, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1, -1, -1, -1],\n contiguity=[False, None, True, True, True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[4, 3, 2, 1, 0],\n )\n S2 = fd.define_scalar(5, dtype=DataType.Int)\n S3 = fd.define_scalar(0, dtype=DataType.Int)\n T5 = fd.ops.reshape(T0, new_shape=[S2, S3])\n fd.add_output(T5)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_empty_reshape","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_empty_reshape#L483-L499","kind":"function","name":"test_empty_reshape","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":483,"end_line":499,"context_start_line":463,"context_end_line":519,"code":" S7 = fd.define_scalar(192, dtype=DataType.Int)\n S8 = fd.ops.fmod(S7, S3)\n S9 = fd.ops.cast(S8, dtype=DataType.Int)\n S10 = fd.define_scalar(0, dtype=DataType.Int)\n S11 = fd.ops.ne(S9, S10)\n S12 = fd.ops.bitwise_and(S6, S11)\n S13 = fd.define_scalar(192, dtype=DataType.Int)\n S14 = fd.ops.reciprocal(S3)\n S15 = fd.ops.mul(S13, S14)\n S16 = fd.ops.cast(S12, dtype=DataType.Int)\n S17 = fd.ops.sub(S15, S16)\n T19 = fd.ops.reshape(T1, new_shape=[S0, S17])\n T20 = fd.ops.sum(T19, dims=[1], keepdim=False, dtype=DataType.Null)\n fd.add_output(T20)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\n# Test empty symbolic tensors can be reshaped\n# See https://github.com/NVIDIA/Fuser/issues/2362\ndef test_empty_reshape(nvfuser_direct_test):\n inputs = [torch.randint(0, 10, (0, 1, 2, 3, 4), dtype=torch.int64, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1, -1, -1, -1],\n contiguity=[False, None, True, True, True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[4, 3, 2, 1, 0],\n )\n S2 = fd.define_scalar(5, dtype=DataType.Int)\n S3 = fd.define_scalar(0, dtype=DataType.Int)\n T5 = fd.ops.reshape(T0, new_shape=[S2, S3])\n fd.add_output(T5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_squeeze(nvfuser_direct_test):\n t0_sizes = [4]\n t1_sizes = [1, 4, 1]\n t2_sizes = [2, 1, 4]\n inputs = [\n torch.randn(*t0_sizes, device=\"cuda\"),\n torch.randn(*t1_sizes, device=\"cuda\"),\n torch.randn(*t2_sizes, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1], contiguity=[True])\n t1 = fd.define_tensor(sizes=t1_sizes, strides=[4, 1, 1])\n t2 = fd.define_tensor(sizes=t2_sizes, strides=[4, 4, 1])\n t3 = fd.ops.squeeze(t1, [0, -1])\n t4 = fd.ops.squeeze(t2, [-2])\n t5 = fd.ops.sum(t4, [0])\n t6 = fd.ops.mul(t0, t3)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_squeeze","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_squeeze#L502-L542","kind":"function","name":"test_squeeze","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":502,"end_line":542,"context_start_line":482,"context_end_line":562,"code":"# See https://github.com/NVIDIA/Fuser/issues/2362\ndef test_empty_reshape(nvfuser_direct_test):\n inputs = [torch.randint(0, 10, (0, 1, 2, 3, 4), dtype=torch.int64, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1, -1, -1, -1],\n contiguity=[False, None, True, True, True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[4, 3, 2, 1, 0],\n )\n S2 = fd.define_scalar(5, dtype=DataType.Int)\n S3 = fd.define_scalar(0, dtype=DataType.Int)\n T5 = fd.ops.reshape(T0, new_shape=[S2, S3])\n fd.add_output(T5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_squeeze(nvfuser_direct_test):\n t0_sizes = [4]\n t1_sizes = [1, 4, 1]\n t2_sizes = [2, 1, 4]\n inputs = [\n torch.randn(*t0_sizes, device=\"cuda\"),\n torch.randn(*t1_sizes, device=\"cuda\"),\n torch.randn(*t2_sizes, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1], contiguity=[True])\n t1 = fd.define_tensor(sizes=t1_sizes, strides=[4, 1, 1])\n t2 = fd.define_tensor(sizes=t2_sizes, strides=[4, 4, 1])\n t3 = fd.ops.squeeze(t1, [0, -1])\n t4 = fd.ops.squeeze(t2, [-2])\n t5 = fd.ops.sum(t4, [0])\n t6 = fd.ops.mul(t0, t3)\n t7 = fd.ops.mul(t6, t5)\n fd.add_output(t7)\n\n # Check that squeeze does not print default argument: squeeze_expanded\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False)\n tv1 = fd.define_tensor(shape=[1, -1, 1], contiguity=[None, True, None], dtype=DataType.Float, is_cpu=False)\n tv2 = fd.define_tensor(shape=[-1, 1, -1], contiguity=[True, None, True], dtype=DataType.Float, is_cpu=False)\n tv3 = fd.ops.squeeze(tv1, dims=[0, 2])\n tv6 = fd.ops.mul(tv0, tv3)\n tv4 = fd.ops.squeeze(tv2, dims=[1])\n tv5 = fd.ops.sum(tv4, dims=[0], dtype=DataType.Float)\n tv7 = fd.ops.mul(tv6, tv5)\n fd.add_output(tv7)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n\n v1 = torch.sum(inputs[1], [0, -1])\n v2 = torch.sum(inputs[2], [0, 1])\n eager_out = inputs[0] * v1 * v2\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n# Test that expanded dimensions can be reduced properly\n# See https://github.com/NVIDIA/Fuser/issues/1678\ndef test_expanded_reduction(nvfuser_direct_test):\n inputs = [torch.tensor(1.0, device=\"cuda\").as_strided((2, 3), (0, 0))]\n\n for keepdim in [False, True]:\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[None, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.sum(T0, dims=[0], keepdim=keepdim, dtype=DataType.Null)\n fd.add_output(T1)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_expanded_reduction","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_expanded_reduction#L547-L567","kind":"function","name":"test_expanded_reduction","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":547,"end_line":567,"context_start_line":527,"context_end_line":587,"code":" tv2 = fd.define_tensor(shape=[-1, 1, -1], contiguity=[True, None, True], dtype=DataType.Float, is_cpu=False)\n tv3 = fd.ops.squeeze(tv1, dims=[0, 2])\n tv6 = fd.ops.mul(tv0, tv3)\n tv4 = fd.ops.squeeze(tv2, dims=[1])\n tv5 = fd.ops.sum(tv4, dims=[0], dtype=DataType.Float)\n tv7 = fd.ops.mul(tv6, tv5)\n fd.add_output(tv7)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n\n v1 = torch.sum(inputs[1], [0, -1])\n v2 = torch.sum(inputs[2], [0, 1])\n eager_out = inputs[0] * v1 * v2\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n# Test that expanded dimensions can be reduced properly\n# See https://github.com/NVIDIA/Fuser/issues/1678\ndef test_expanded_reduction(nvfuser_direct_test):\n inputs = [torch.tensor(1.0, device=\"cuda\").as_strided((2, 3), (0, 0))]\n\n for keepdim in [False, True]:\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[None, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.sum(T0, dims=[0], keepdim=keepdim, dtype=DataType.Null)\n fd.add_output(T1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(\n nvf_out[0], inputs[0].sum(dim=0, keepdim=keepdim)\n )\n\n\ndef test_expand(nvfuser_direct_test):\n inputs = [\n torch.randn(1, 1, 4, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.expand(t0, inputs[1].size())\n t2 = fd.ops.mul(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0].expand(inputs[1].size()) * inputs[1]\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_expand","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_expand#L570-L587","kind":"function","name":"test_expand","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":570,"end_line":587,"context_start_line":550,"context_end_line":607,"code":" for keepdim in [False, True]:\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[None, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.sum(T0, dims=[0], keepdim=keepdim, dtype=DataType.Null)\n fd.add_output(T1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(\n nvf_out[0], inputs[0].sum(dim=0, keepdim=keepdim)\n )\n\n\ndef test_expand(nvfuser_direct_test):\n inputs = [\n torch.randn(1, 1, 4, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.expand(t0, inputs[1].size())\n t2 = fd.ops.mul(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0].expand(inputs[1].size()) * inputs[1]\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_index_select(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n torch.randn(8, 16, device=\"cuda\"),\n torch.randint(0, 8, (6,), device=\"cuda\").to(dtype=torch.long),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.add(t0, t1)\n t4 = fd.ops.index_select(t3, t2, dim)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_index_select","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_index_select#L590-L612","kind":"function","name":"test_index_select","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":590,"end_line":612,"context_start_line":570,"context_end_line":632,"code":"def test_expand(nvfuser_direct_test):\n inputs = [\n torch.randn(1, 1, 4, device=\"cuda\"),\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.expand(t0, inputs[1].size())\n t2 = fd.ops.mul(t0_b, t1)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0].expand(inputs[1].size()) * inputs[1]\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_index_select(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n torch.randn(8, 16, device=\"cuda\"),\n torch.randint(0, 8, (6,), device=\"cuda\").to(dtype=torch.long),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.add(t0, t1)\n t4 = fd.ops.index_select(t3, t2, dim)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.index_select(inputs[0] + inputs[1], dim, inputs[2])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_index_select_scalar_indices(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n torch.tensor(2, device=\"cuda\").to(dtype=torch.long),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.index_select(t0, t1, dim)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.index_select(inputs[0], dim, inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_index_select_scalar_indices","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_index_select_scalar_indices#L615-L634","kind":"function","name":"test_index_select_scalar_indices","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":615,"end_line":634,"context_start_line":595,"context_end_line":654,"code":" ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.add(t0, t1)\n t4 = fd.ops.index_select(t3, t2, dim)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.index_select(inputs[0] + inputs[1], dim, inputs[2])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_index_select_scalar_indices(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n torch.tensor(2, device=\"cuda\").to(dtype=torch.long),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.index_select(t0, t1, dim)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.index_select(inputs[0], dim, inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_select(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n index := 2,\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s1 = fd.define_scalar(dtype=DataType.Int)\n t1 = fd.ops.select(t0, s1, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.select(inputs[0], dim, inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_select","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_select#L637-L656","kind":"function","name":"test_select","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":637,"end_line":656,"context_start_line":617,"context_end_line":676,"code":" torch.randn(8, 16, device=\"cuda\"),\n torch.tensor(2, device=\"cuda\").to(dtype=torch.long),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.index_select(t0, t1, dim)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.index_select(inputs[0], dim, inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_select(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n index := 2,\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s1 = fd.define_scalar(dtype=DataType.Int)\n t1 = fd.ops.select(t0, s1, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.select(inputs[0], dim, inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_take_along_axis(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n torch.randn(8, 16, device=\"cuda\"),\n torch.randint(0, 8, (8, 16), device=\"cuda\").to(dtype=torch.long),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.add(t0, t1)\n t4 = fd.ops.take_along_axis(t3, t2, dim)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_take_along_axis","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_take_along_axis#L659-L681","kind":"function","name":"test_take_along_axis","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":659,"end_line":681,"context_start_line":639,"context_end_line":701,"code":" torch.randn(8, 16, device=\"cuda\"),\n index := 2,\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s1 = fd.define_scalar(dtype=DataType.Int)\n t1 = fd.ops.select(t0, s1, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.select(inputs[0], dim, inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_take_along_axis(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n torch.randn(8, 16, device=\"cuda\"),\n torch.randint(0, 8, (8, 16), device=\"cuda\").to(dtype=torch.long),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.add(t0, t1)\n t4 = fd.ops.take_along_axis(t3, t2, dim)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.gather(inputs[0] + inputs[1], dim, inputs[2])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_cumsum(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cumsum(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cumsum(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_cumsum","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_cumsum#L684-L701","kind":"function","name":"test_cumsum","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":684,"end_line":701,"context_start_line":664,"context_end_line":721,"code":" ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.add(t0, t1)\n t4 = fd.ops.take_along_axis(t3, t2, dim)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.gather(inputs[0] + inputs[1], dim, inputs[2])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_cumsum(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cumsum(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cumsum(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_cumprod(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cumprod(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cumprod(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_cumprod","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_cumprod#L704-L721","kind":"function","name":"test_cumprod","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":704,"end_line":721,"context_start_line":684,"context_end_line":741,"code":"def test_cumsum(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cumsum(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cumsum(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_cumprod(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cumprod(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cumprod(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_cummin(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cummin(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cummin(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out[0], nvf_out[0])\n\n test_fn(0)\n test_fn(1)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_cummin","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_cummin#L724-L741","kind":"function","name":"test_cummin","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":724,"end_line":741,"context_start_line":704,"context_end_line":761,"code":"def test_cumprod(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cumprod(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cumprod(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_cummin(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cummin(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cummin(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out[0], nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_cummax(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cummax(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cummax(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out[0], nvf_out[0])\n\n test_fn(0)\n test_fn(1)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_cummax","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_cummax#L744-L761","kind":"function","name":"test_cummax","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":744,"end_line":761,"context_start_line":724,"context_end_line":781,"code":"def test_cummin(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cummin(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cummin(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out[0], nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_cummax(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cummax(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cummax(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out[0], nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_where(nvfuser_direct_test):\n # nvfuser_where is a decorator function. It takes the input arguments\n # and creates a function that builds a FusionDefinition.\n def nvfuser_where(pred, a, b):\n def fusion_func(fd: FusionDefinition):\n nv_pred = fd.define_tensor(\n sizes=pred.shape, strides=pred.stride(), dtype=DataType.Bool\n )\n nv_a = fd.define_tensor(\n sizes=a.shape,\n strides=a.stride(),\n dtype=torch_dtype_to_nvfuser_dtype(a.dtype),\n )\n nv_b = fd.define_tensor(\n sizes=b.shape,\n strides=b.stride(),\n dtype=torch_dtype_to_nvfuser_dtype(b.dtype),\n )","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_where","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_where#L764-L799","kind":"function","name":"test_where","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":764,"end_line":799,"context_start_line":744,"context_end_line":819,"code":"def test_cummax(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cummax(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cummax(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out[0], nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_where(nvfuser_direct_test):\n # nvfuser_where is a decorator function. It takes the input arguments\n # and creates a function that builds a FusionDefinition.\n def nvfuser_where(pred, a, b):\n def fusion_func(fd: FusionDefinition):\n nv_pred = fd.define_tensor(\n sizes=pred.shape, strides=pred.stride(), dtype=DataType.Bool\n )\n nv_a = fd.define_tensor(\n sizes=a.shape,\n strides=a.stride(),\n dtype=torch_dtype_to_nvfuser_dtype(a.dtype),\n )\n nv_b = fd.define_tensor(\n sizes=b.shape,\n strides=b.stride(),\n dtype=torch_dtype_to_nvfuser_dtype(b.dtype),\n )\n result = fd.ops.where(nv_pred, nv_a, nv_b)\n fd.add_output(result)\n\n return fusion_func\n\n # get list of dtypes to test with\n list_of_dtype = [torch.float16, torch.float32]\n if not is_pre_ampere():\n list_of_dtype.append(torch.bfloat16)\n\n pred = torch.testing.make_tensor((5,), device=\"cuda\", dtype=torch.bool)\n for atype, btype in itertools.product(list_of_dtype, list_of_dtype):\n a = torch.randn((5,), device=\"cuda\", dtype=atype)\n b = torch.randn((5,), device=\"cuda\", dtype=btype)\n fusion_func = nvfuser_where(pred, a, b)\n nv_result, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [pred, a, b])\n torch_result = torch.where(pred, a, b)\n nvfuser_direct_test.assertEqual(nv_result[0], torch_result)\n\n\ndef test_where_dtypes(nvfuser_direct_test):\n inputs = [\n torch.arange(2, device=\"cuda\").type(torch.bool),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n\n c0 = fd.define_scalar(3.0)\n c1 = fd.define_scalar(5.0)\n t1 = fd.ops.where(t0, c0, c1) # DataType.Double\n fd.add_output(t1)\n\n c0f = fd.define_scalar(3.0, DataType.Float)\n c1f = fd.define_scalar(5.0, DataType.Float)\n t1f = fd.ops.where(t0, c0f, c1f) # DataType.Float\n fd.add_output(t1f)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_where_dtypes","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_where_dtypes#L802-L880","kind":"function","name":"test_where_dtypes","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":802,"end_line":880,"context_start_line":782,"context_end_line":900,"code":" result = fd.ops.where(nv_pred, nv_a, nv_b)\n fd.add_output(result)\n\n return fusion_func\n\n # get list of dtypes to test with\n list_of_dtype = [torch.float16, torch.float32]\n if not is_pre_ampere():\n list_of_dtype.append(torch.bfloat16)\n\n pred = torch.testing.make_tensor((5,), device=\"cuda\", dtype=torch.bool)\n for atype, btype in itertools.product(list_of_dtype, list_of_dtype):\n a = torch.randn((5,), device=\"cuda\", dtype=atype)\n b = torch.randn((5,), device=\"cuda\", dtype=btype)\n fusion_func = nvfuser_where(pred, a, b)\n nv_result, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [pred, a, b])\n torch_result = torch.where(pred, a, b)\n nvfuser_direct_test.assertEqual(nv_result[0], torch_result)\n\n\ndef test_where_dtypes(nvfuser_direct_test):\n inputs = [\n torch.arange(2, device=\"cuda\").type(torch.bool),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n\n c0 = fd.define_scalar(3.0)\n c1 = fd.define_scalar(5.0)\n t1 = fd.ops.where(t0, c0, c1) # DataType.Double\n fd.add_output(t1)\n\n c0f = fd.define_scalar(3.0, DataType.Float)\n c1f = fd.define_scalar(5.0, DataType.Float)\n t1f = fd.ops.where(t0, c0f, c1f) # DataType.Float\n fd.add_output(t1f)\n\n c0d = fd.define_scalar(3.0, DataType.Double)\n c1d = fd.define_scalar(5.0, DataType.Double)\n t1d = fd.ops.where(t0, c0d, c1d) # DataType.Double\n fd.add_output(t1d)\n\n c0i = fd.define_scalar(3, DataType.Int32)\n c1i = fd.define_scalar(5, DataType.Int32)\n t1i = fd.ops.where(t0, c0i, c1i) # DataType.Int32\n fd.add_output(t1i)\n\n c0l = fd.define_scalar(3)\n c1l = fd.define_scalar(5)\n t1l = fd.ops.where(t0, c0l, c1l) # DataType.Int\n fd.add_output(t1l)\n\n c0c = fd.define_scalar(complex(3.0))\n c1c = fd.define_scalar(complex(5.0))\n t1c = fd.ops.where(t0, c0c, c1c) # DataType.ComplexDouble\n fd.add_output(t1c)\n\n c0cf = fd.define_scalar(3.0 + 0j, DataType.ComplexFloat)\n c1cf = fd.define_scalar(5.0 + 0j, DataType.ComplexFloat)\n t1cf = fd.ops.where(t0, c0cf, c1cf) # DataType.ComplexFloat\n fd.add_output(t1cf)\n\n c0cd = fd.define_scalar(3.0 + 0j, DataType.ComplexDouble)\n c1cd = fd.define_scalar(5.0 + 0j, DataType.ComplexDouble)\n t1cd = fd.ops.where(t0, c0cd, c1cd) # DataType.ComplexDouble\n fd.add_output(t1cd)\n\n c0b = fd.define_scalar(True, DataType.Bool)\n c1b = fd.define_scalar(False, DataType.Bool)\n t1b = fd.ops.where(t0, c0b, c1b) # DataType.Bool\n fd.add_output(t1b)\n\n (\n n,\n nf,\n nd,\n ni,\n nl,\n nc,\n ncf,\n ncd,\n nb,\n ), _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.where(inputs[0], 3.0, 5.0)\n\n # explicit Float dtype matches torch.where behavior\n nvfuser_direct_test.assertEqual(eager_out, nf)\n\n assert n.dtype == torch.float64\n assert nf.dtype == torch.float32\n assert nd.dtype == torch.float64\n assert ni.dtype == torch.int32\n assert nl.dtype == torch.int64\n assert nc.dtype == torch.complex128\n assert ncf.dtype == torch.complex64\n assert ncd.dtype == torch.complex128\n assert nb.dtype == torch.bool\n\n\ndef test_addcmul(nvfuser_direct_test):\n inputs = [\n torch.randn(4, device=\"cuda\", dtype=torch.float32),\n torch.randn(4, device=\"cuda\", dtype=torch.float32),\n torch.randn(4, device=\"cuda\", dtype=torch.float32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n c0 = fd.define_scalar(0.1)\n\n t3 = fd.ops.addcmul(t0, t1, t2, c0)\n\n fd.add_output(t3)\n\n nvfout, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_addcmul","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_addcmul#L883-L904","kind":"function","name":"test_addcmul","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":883,"end_line":904,"context_start_line":863,"context_end_line":924,"code":" ncd,\n nb,\n ), _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.where(inputs[0], 3.0, 5.0)\n\n # explicit Float dtype matches torch.where behavior\n nvfuser_direct_test.assertEqual(eager_out, nf)\n\n assert n.dtype == torch.float64\n assert nf.dtype == torch.float32\n assert nd.dtype == torch.float64\n assert ni.dtype == torch.int32\n assert nl.dtype == torch.int64\n assert nc.dtype == torch.complex128\n assert ncf.dtype == torch.complex64\n assert ncd.dtype == torch.complex128\n assert nb.dtype == torch.bool\n\n\ndef test_addcmul(nvfuser_direct_test):\n inputs = [\n torch.randn(4, device=\"cuda\", dtype=torch.float32),\n torch.randn(4, device=\"cuda\", dtype=torch.float32),\n torch.randn(4, device=\"cuda\", dtype=torch.float32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n c0 = fd.define_scalar(0.1)\n\n t3 = fd.ops.addcmul(t0, t1, t2, c0)\n\n fd.add_output(t3)\n\n nvfout, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n torch_out = torch.addcmul(*inputs, value=0.1)\n\n nvfuser_direct_test.assertEqual(nvfout[0], torch_out)\n\n\ndef test_slice(nvfuser_direct_test):\n x = torch.randn((2, 5, 10), dtype=torch.float32, device=\"cuda:0\")\n\n offset = (0, 1, 2)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.ops.slice(\n T0, start_indices=offset, end_indices=(2, 5, 10), strides=(1, 1, 1)\n )\n fd.add_output(T1)\n V_start = list(offset)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_slice","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_slice#L907-L937","kind":"function","name":"test_slice","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":907,"end_line":937,"context_start_line":887,"context_end_line":957,"code":" torch.randn(4, device=\"cuda\", dtype=torch.float32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n c0 = fd.define_scalar(0.1)\n\n t3 = fd.ops.addcmul(t0, t1, t2, c0)\n\n fd.add_output(t3)\n\n nvfout, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n torch_out = torch.addcmul(*inputs, value=0.1)\n\n nvfuser_direct_test.assertEqual(nvfout[0], torch_out)\n\n\ndef test_slice(nvfuser_direct_test):\n x = torch.randn((2, 5, 10), dtype=torch.float32, device=\"cuda:0\")\n\n offset = (0, 1, 2)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.ops.slice(\n T0, start_indices=offset, end_indices=(2, 5, 10), strides=(1, 1, 1)\n )\n fd.add_output(T1)\n V_start = list(offset)\n V_end = T0.shape()\n T2 = fd.ops.slice(T0, V_start, V_end)\n fd.add_output(T2)\n dynamic_start = fd.define_vector(3)\n dynamic_end = fd.define_vector(3)\n T3 = fd.ops.slice(T0, dynamic_start, dynamic_end)\n fd.add_output(T3)\n\n inputs = [x, *offset, *x.shape]\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n for out in nvf_out:\n torch.testing.assert_close(out, x[:, 1:, 2:])\n\n\ndef test_iota(nvfuser_direct_test):\n inputs = [\n (2, 0, 2, DataType.Int),\n (3, 100, 1, DataType.Int32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n for input in inputs:\n c0 = fd.define_scalar(input[0])\n c1 = None if input[1] is None else fd.define_scalar(input[1])\n c2 = None if input[2] is None else fd.define_scalar(input[2])\n dt = input[3]\n t3 = fd.ops.iota(c0, c1, c2, dt)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [])\n\n eager_out1 = torch.tensor([0, 2], dtype=torch.long, device=\"cuda\")","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_iota","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_iota#L940-L960","kind":"function","name":"test_iota","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":940,"end_line":960,"context_start_line":920,"context_end_line":980,"code":" T1 = fd.ops.slice(\n T0, start_indices=offset, end_indices=(2, 5, 10), strides=(1, 1, 1)\n )\n fd.add_output(T1)\n V_start = list(offset)\n V_end = T0.shape()\n T2 = fd.ops.slice(T0, V_start, V_end)\n fd.add_output(T2)\n dynamic_start = fd.define_vector(3)\n dynamic_end = fd.define_vector(3)\n T3 = fd.ops.slice(T0, dynamic_start, dynamic_end)\n fd.add_output(T3)\n\n inputs = [x, *offset, *x.shape]\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n for out in nvf_out:\n torch.testing.assert_close(out, x[:, 1:, 2:])\n\n\ndef test_iota(nvfuser_direct_test):\n inputs = [\n (2, 0, 2, DataType.Int),\n (3, 100, 1, DataType.Int32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n for input in inputs:\n c0 = fd.define_scalar(input[0])\n c1 = None if input[1] is None else fd.define_scalar(input[1])\n c2 = None if input[2] is None else fd.define_scalar(input[2])\n dt = input[3]\n t3 = fd.ops.iota(c0, c1, c2, dt)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [])\n\n eager_out1 = torch.tensor([0, 2], dtype=torch.long, device=\"cuda\")\n eager_out2 = torch.tensor([100, 101, 102], dtype=torch.int, device=\"cuda\")\n nvfuser_direct_test.assertEqual(eager_out1, nvf_out[0])\n nvfuser_direct_test.assertEqual(eager_out2, nvf_out[1])\n\n\ndef test_scalar_only_inputs(nvfuser_direct_test):\n # We don't allow scalar outputs, currently,\n # so a tensor has to be returned\n def fusion_func(fd: FusionDefinition):\n s0 = fd.define_scalar()\n s1 = fd.define_scalar()\n s2 = fd.ops.add(s0, s1)\n c0 = fd.define_scalar(1.0, DataType.Float)\n t3 = fd.ops.full(shape=[2, 2], fill_value=c0, dtype=DataType.Float)\n t4 = fd.ops.mul(t3, s2)\n fd.add_output(t4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [2.0, 3.0])\n eager_out = torch.full([2, 2], 1.0) * 5.0\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_scalar_only_inputs","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_scalar_only_inputs#L963-L980","kind":"function","name":"test_scalar_only_inputs","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":963,"end_line":980,"context_start_line":943,"context_end_line":1000,"code":" (3, 100, 1, DataType.Int32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n for input in inputs:\n c0 = fd.define_scalar(input[0])\n c1 = None if input[1] is None else fd.define_scalar(input[1])\n c2 = None if input[2] is None else fd.define_scalar(input[2])\n dt = input[3]\n t3 = fd.ops.iota(c0, c1, c2, dt)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [])\n\n eager_out1 = torch.tensor([0, 2], dtype=torch.long, device=\"cuda\")\n eager_out2 = torch.tensor([100, 101, 102], dtype=torch.int, device=\"cuda\")\n nvfuser_direct_test.assertEqual(eager_out1, nvf_out[0])\n nvfuser_direct_test.assertEqual(eager_out2, nvf_out[1])\n\n\ndef test_scalar_only_inputs(nvfuser_direct_test):\n # We don't allow scalar outputs, currently,\n # so a tensor has to be returned\n def fusion_func(fd: FusionDefinition):\n s0 = fd.define_scalar()\n s1 = fd.define_scalar()\n s2 = fd.ops.add(s0, s1)\n c0 = fd.define_scalar(1.0, DataType.Float)\n t3 = fd.ops.full(shape=[2, 2], fill_value=c0, dtype=DataType.Float)\n t4 = fd.ops.mul(t3, s2)\n fd.add_output(t4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [2.0, 3.0])\n eager_out = torch.full([2, 2], 1.0) * 5.0\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_alias_output_to_input(nvfuser_direct_test):\n in_tensors = [\n torch.ones(4, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(in_tensors[0]) # = 1.0\n one = fd.define_scalar(1.0)\n two = fd.define_scalar(2.0)\n t1 = fd.ops.add(t0, one) # = t0 + 1.0 = 2.0\n t2 = fd.ops.add(t1, two) # = t1 + 2.0 = 4.0\n fd.add_output(t1, alias_input=t0)\n fd.add_output(t2)\n\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, in_tensors)\n\n # t1 is an alias and therefore is hidden.\n nvfuser_direct_test.assertEqual(len(out_tensors), 1)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_alias_output_to_input","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_alias_output_to_input#L983-L1006","kind":"function","name":"test_alias_output_to_input","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":983,"end_line":1006,"context_start_line":963,"context_end_line":1026,"code":"def test_scalar_only_inputs(nvfuser_direct_test):\n # We don't allow scalar outputs, currently,\n # so a tensor has to be returned\n def fusion_func(fd: FusionDefinition):\n s0 = fd.define_scalar()\n s1 = fd.define_scalar()\n s2 = fd.ops.add(s0, s1)\n c0 = fd.define_scalar(1.0, DataType.Float)\n t3 = fd.ops.full(shape=[2, 2], fill_value=c0, dtype=DataType.Float)\n t4 = fd.ops.mul(t3, s2)\n fd.add_output(t4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [2.0, 3.0])\n eager_out = torch.full([2, 2], 1.0) * 5.0\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_alias_output_to_input(nvfuser_direct_test):\n in_tensors = [\n torch.ones(4, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(in_tensors[0]) # = 1.0\n one = fd.define_scalar(1.0)\n two = fd.define_scalar(2.0)\n t1 = fd.ops.add(t0, one) # = t0 + 1.0 = 2.0\n t2 = fd.ops.add(t1, two) # = t1 + 2.0 = 4.0\n fd.add_output(t1, alias_input=t0)\n fd.add_output(t2)\n\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, in_tensors)\n\n # t1 is an alias and therefore is hidden.\n nvfuser_direct_test.assertEqual(len(out_tensors), 1)\n nvfuser_direct_test.assertEqual(\n out_tensors[0], torch.full((4, 4), 4.0, device=\"cuda\")\n )\n nvfuser_direct_test.assertEqual(\n in_tensors[0], torch.full((4, 4), 2.0, device=\"cuda\")\n )\n\n\ndef test_returning_aliased_outputs(nvfuser_direct_test):\n inputs = [torch.randn((1, 2, 3, 4), dtype=torch.float32, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n S1 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T2 = fd.ops.gt(T0, S1)\n S3 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T4 = fd.ops.where(T2, T0, S3)\n fd.add_output(T4)\n fd.add_output(T4, T0)\n fd.add_output(T4)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_returning_aliased_outputs","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_returning_aliased_outputs#L1009-L1033","kind":"function","name":"test_returning_aliased_outputs","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1009,"end_line":1033,"context_start_line":989,"context_end_line":1053,"code":" t0 = fd.from_pytorch(in_tensors[0]) # = 1.0\n one = fd.define_scalar(1.0)\n two = fd.define_scalar(2.0)\n t1 = fd.ops.add(t0, one) # = t0 + 1.0 = 2.0\n t2 = fd.ops.add(t1, two) # = t1 + 2.0 = 4.0\n fd.add_output(t1, alias_input=t0)\n fd.add_output(t2)\n\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, in_tensors)\n\n # t1 is an alias and therefore is hidden.\n nvfuser_direct_test.assertEqual(len(out_tensors), 1)\n nvfuser_direct_test.assertEqual(\n out_tensors[0], torch.full((4, 4), 4.0, device=\"cuda\")\n )\n nvfuser_direct_test.assertEqual(\n in_tensors[0], torch.full((4, 4), 2.0, device=\"cuda\")\n )\n\n\ndef test_returning_aliased_outputs(nvfuser_direct_test):\n inputs = [torch.randn((1, 2, 3, 4), dtype=torch.float32, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n S1 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T2 = fd.ops.gt(T0, S1)\n S3 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T4 = fd.ops.where(T2, T0, S3)\n fd.add_output(T4)\n fd.add_output(T4, T0)\n fd.add_output(T4)\n fd.add_output(T0)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n num_out = len(nvf_out)\n nvfuser_direct_test.assertEqual(num_out, 3)\n for i in range(num_out):\n nvfuser_direct_test.assertEqual(nvf_out[i].data_ptr(), inputs[0].data_ptr())\n\n\ndef test_welford(nvfuser_direct_test):\n inputs = [torch.randn(2, 2, device=\"cuda\")]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n mean, var_sum, n = fd.ops.welford(t0, [-1])\n var = fd.ops.div(var_sum, n)\n fd.add_output(var)\n fd.add_output(mean)\n\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_result = torch.var_mean(inputs[0], [-1], correction=0)\n nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_gather(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_welford","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_welford#L1036-L1048","kind":"function","name":"test_welford","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1036,"end_line":1048,"context_start_line":1016,"context_end_line":1068,"code":" dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n S1 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T2 = fd.ops.gt(T0, S1)\n S3 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T4 = fd.ops.where(T2, T0, S3)\n fd.add_output(T4)\n fd.add_output(T4, T0)\n fd.add_output(T4)\n fd.add_output(T0)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n num_out = len(nvf_out)\n nvfuser_direct_test.assertEqual(num_out, 3)\n for i in range(num_out):\n nvfuser_direct_test.assertEqual(nvf_out[i].data_ptr(), inputs[0].data_ptr())\n\n\ndef test_welford(nvfuser_direct_test):\n inputs = [torch.randn(2, 2, device=\"cuda\")]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n mean, var_sum, n = fd.ops.welford(t0, [-1])\n var = fd.ops.div(var_sum, n)\n fd.add_output(var)\n fd.add_output(mean)\n\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_result = torch.var_mean(inputs[0], [-1], correction=0)\n nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_gather(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n torch.randn(8, 16, device=\"cuda\"),\n torch.randint(0, 8, (4, 4), device=\"cuda\").to(dtype=torch.long),\n ]\n\n for dim in [0, 1]:\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.add(t0, t1)\n t4 = fd.ops.gather(t3, t2, dim)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_gather","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_gather#L1051-L1071","kind":"function","name":"test_gather","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1051,"end_line":1071,"context_start_line":1031,"context_end_line":1091,"code":" nvfuser_direct_test.assertEqual(num_out, 3)\n for i in range(num_out):\n nvfuser_direct_test.assertEqual(nvf_out[i].data_ptr(), inputs[0].data_ptr())\n\n\ndef test_welford(nvfuser_direct_test):\n inputs = [torch.randn(2, 2, device=\"cuda\")]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n mean, var_sum, n = fd.ops.welford(t0, [-1])\n var = fd.ops.div(var_sum, n)\n fd.add_output(var)\n fd.add_output(mean)\n\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_result = torch.var_mean(inputs[0], [-1], correction=0)\n nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_gather(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n torch.randn(8, 16, device=\"cuda\"),\n torch.randint(0, 8, (4, 4), device=\"cuda\").to(dtype=torch.long),\n ]\n\n for dim in [0, 1]:\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.add(t0, t1)\n t4 = fd.ops.gather(t3, t2, dim)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.gather(inputs[0] + inputs[1], dim, inputs[2])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_pad(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor((1, 2, 3), dtype=torch.float32, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n\n t1 = fd.ops.pad(t0, [1, 1, 1, 1])\n fd.add_output(t1)\n\n # zero padding in some dims\n t2 = fd.ops.pad(t0, [0, 0, 2, 3])\n fd.add_output(t2)\n\n # zero padding in all dims\n t3 = fd.ops.pad(t0, [0, 0, 0, 0])\n fd.add_output(t3)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_pad","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_pad#L1074-L1125","kind":"function","name":"test_pad","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1074,"end_line":1125,"context_start_line":1054,"context_end_line":1145,"code":" torch.randn(8, 16, device=\"cuda\"),\n torch.randint(0, 8, (4, 4), device=\"cuda\").to(dtype=torch.long),\n ]\n\n for dim in [0, 1]:\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.add(t0, t1)\n t4 = fd.ops.gather(t3, t2, dim)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.gather(inputs[0] + inputs[1], dim, inputs[2])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_pad(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor((1, 2, 3), dtype=torch.float32, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n\n t1 = fd.ops.pad(t0, [1, 1, 1, 1])\n fd.add_output(t1)\n\n # zero padding in some dims\n t2 = fd.ops.pad(t0, [0, 0, 2, 3])\n fd.add_output(t2)\n\n # zero padding in all dims\n t3 = fd.ops.pad(t0, [0, 0, 0, 0])\n fd.add_output(t3)\n\n # no padding provided in first dim\n t4 = fd.ops.pad(t0, [2, 3])\n fd.add_output(t4)\n\n # test padding with a value other than 0\n fill_val = fd.define_scalar(2.0)\n t5 = fd.ops.pad(t0, [2, 3], fill_val)\n fd.add_output(t5)\n\n # pad a broadcast dimension with a value other than 0\n t6 = fd.ops.pad(t0, [2, 3, 0, 0, 0, 0])\n fd.add_output(t6)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [1, 1, 1, 1]), nvf_out[0]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [0, 0, 2, 3]), nvf_out[1]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [0, 0, 0, 0]), nvf_out[2]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [2, 3]), nvf_out[3]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [2, 3], \"constant\", 2.0), nvf_out[4]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [2, 3, 0, 0, 0, 0]), nvf_out[5]\n )\n\n\ndef test_pad_dynamic(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor((1, 2, 3), dtype=torch.float32, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n\n S10 = fd.define_scalar(2.5, dtype=DataType.Float)\n S13 = fd.define_scalar(7, dtype=DataType.Int)\n S15 = fd.ops.mul(S10, S13)\n S16 = fd.ops.cast(S15, dtype=DataType.Int)\n t1 = fd.ops.pad(t0, [S16, S16, S16, S16])\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_pad_dynamic","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_pad_dynamic#L1128-L1147","kind":"function","name":"test_pad_dynamic","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1128,"end_line":1147,"context_start_line":1108,"context_end_line":1167,"code":" nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [1, 1, 1, 1]), nvf_out[0]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [0, 0, 2, 3]), nvf_out[1]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [0, 0, 0, 0]), nvf_out[2]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [2, 3]), nvf_out[3]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [2, 3], \"constant\", 2.0), nvf_out[4]\n )\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [2, 3, 0, 0, 0, 0]), nvf_out[5]\n )\n\n\ndef test_pad_dynamic(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor((1, 2, 3), dtype=torch.float32, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n\n S10 = fd.define_scalar(2.5, dtype=DataType.Float)\n S13 = fd.define_scalar(7, dtype=DataType.Int)\n S15 = fd.ops.mul(S10, S13)\n S16 = fd.ops.cast(S15, dtype=DataType.Int)\n t1 = fd.ops.pad(t0, [S16, S16, S16, S16])\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [17, 17, 17, 17]), nvf_out[0]\n )\n\n\ndef test_cat(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(2, 3, device=\"cuda\"),\n torch.randn(4, 4, device=\"cuda\"),\n torch.randn(0, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.from_pytorch(inputs[3])\n\n t3 = fd.ops.cat([t0, t1], 1)\n fd.add_output(t3)\n\n t4 = fd.ops.cat([t0, t2], 0)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_cat","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_cat#L1150-L1177","kind":"function","name":"test_cat","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1150,"end_line":1177,"context_start_line":1130,"context_end_line":1197,"code":" torch.testing.make_tensor((1, 2, 3), dtype=torch.float32, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n\n S10 = fd.define_scalar(2.5, dtype=DataType.Float)\n S13 = fd.define_scalar(7, dtype=DataType.Int)\n S15 = fd.ops.mul(S10, S13)\n S16 = fd.ops.cast(S15, dtype=DataType.Int)\n t1 = fd.ops.pad(t0, [S16, S16, S16, S16])\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(\n torch.nn.functional.pad(inputs[0], [17, 17, 17, 17]), nvf_out[0]\n )\n\n\ndef test_cat(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(2, 3, device=\"cuda\"),\n torch.randn(4, 4, device=\"cuda\"),\n torch.randn(0, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.from_pytorch(inputs[3])\n\n t3 = fd.ops.cat([t0, t1], 1)\n fd.add_output(t3)\n\n t4 = fd.ops.cat([t0, t2], 0)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(\n torch.cat([inputs[0], inputs[1]], dim=1), nvf_out[0]\n )\n nvfuser_direct_test.assertEqual(\n torch.cat([inputs[0], inputs[2]], dim=0), nvf_out[1]\n )\n\n\ndef test_normal(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, dtype=dtype),\n ]\n mean = 3.7\n std = 2.5\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s_mean = fd.define_scalar(mean)\n s_std = fd.define_scalar(std)\n t1 = fd.ops.normal(s_mean, s_std, t0.shape(), dtype=DataType.Double)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_normal","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_normal#L1180-L1215","kind":"function","name":"test_normal","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1180,"end_line":1215,"context_start_line":1160,"context_end_line":1235,"code":" t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.from_pytorch(inputs[3])\n\n t3 = fd.ops.cat([t0, t1], 1)\n fd.add_output(t3)\n\n t4 = fd.ops.cat([t0, t2], 0)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(\n torch.cat([inputs[0], inputs[1]], dim=1), nvf_out[0]\n )\n nvfuser_direct_test.assertEqual(\n torch.cat([inputs[0], inputs[2]], dim=0), nvf_out[1]\n )\n\n\ndef test_normal(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, dtype=dtype),\n ]\n mean = 3.7\n std = 2.5\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s_mean = fd.define_scalar(mean)\n s_std = fd.define_scalar(std)\n t1 = fd.ops.normal(s_mean, s_std, t0.shape(), dtype=DataType.Double)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n # Is there a better way to test distribution?!\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .mean()\n .cpu()\n .float()\n .isclose(torch.tensor(mean), rtol=1e-2, atol=1e-2)\n .item()\n )\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .std()\n .cpu()\n .float()\n .isclose(torch.tensor(std), rtol=1e-2, atol=1e-2)\n .item()\n )\n\n\ndef test_uniform(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, dtype=dtype),\n ]\n lo = 1.8\n hi = 1223.5\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s_lo = fd.define_scalar(lo)\n s_hi = fd.define_scalar(hi)\n t1 = fd.ops.uniform(s_lo, s_hi, t0.shape(), dtype=DataType.Double)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_uniform","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_uniform#L1218-L1261","kind":"function","name":"test_uniform","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1218,"end_line":1261,"context_start_line":1198,"context_end_line":1281,"code":"\n # Is there a better way to test distribution?!\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .mean()\n .cpu()\n .float()\n .isclose(torch.tensor(mean), rtol=1e-2, atol=1e-2)\n .item()\n )\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .std()\n .cpu()\n .float()\n .isclose(torch.tensor(std), rtol=1e-2, atol=1e-2)\n .item()\n )\n\n\ndef test_uniform(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, dtype=dtype),\n ]\n lo = 1.8\n hi = 1223.5\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s_lo = fd.define_scalar(lo)\n s_hi = fd.define_scalar(hi)\n t1 = fd.ops.uniform(s_lo, s_hi, t0.shape(), dtype=DataType.Double)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n # Is there a better way to test distribution?!\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .mean()\n .cpu()\n .float()\n .isclose(torch.tensor((hi - lo) / 2.0), rtol=1e-2, atol=1e-2)\n .item()\n )\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .min()\n .cpu()\n .float()\n .isclose(torch.tensor(lo), rtol=1e-2, atol=1e-2)\n .item()\n )\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .max()\n .cpu()\n .float()\n .isclose(torch.tensor(hi), rtol=1e-2, atol=1e-2)\n .item()\n )\n\n\ndef test_random_distinct_values(nvfuser_direct_test):\n dtypes = [DataType.Double, DataType.Float, DataType.Half, DataType.BFloat16]\n for dtype, rand_op_name in itertools.product(dtypes, [\"uniform\", \"normal\"]):\n\n def fusion_fn(fd: FusionDefinition):\n # generate 4 values and check that they are all distinct\n rand_op = getattr(fd.ops, rand_op_name)\n S0 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S1 = fd.define_scalar(1.00000, dtype=DataType.Double)\n output = rand_op(S0, S1, shape=[2, 2], dtype=dtype)\n fd.add_output(output)\n\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n for i in range(100):\n output = fd.execute([])[0]\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_random_distinct_values","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_random_distinct_values#L1264-L1292","kind":"function","name":"test_random_distinct_values","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1264,"end_line":1292,"context_start_line":1244,"context_end_line":1312,"code":" .item()\n )\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .min()\n .cpu()\n .float()\n .isclose(torch.tensor(lo), rtol=1e-2, atol=1e-2)\n .item()\n )\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .max()\n .cpu()\n .float()\n .isclose(torch.tensor(hi), rtol=1e-2, atol=1e-2)\n .item()\n )\n\n\ndef test_random_distinct_values(nvfuser_direct_test):\n dtypes = [DataType.Double, DataType.Float, DataType.Half, DataType.BFloat16]\n for dtype, rand_op_name in itertools.product(dtypes, [\"uniform\", \"normal\"]):\n\n def fusion_fn(fd: FusionDefinition):\n # generate 4 values and check that they are all distinct\n rand_op = getattr(fd.ops, rand_op_name)\n S0 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S1 = fd.define_scalar(1.00000, dtype=DataType.Double)\n output = rand_op(S0, S1, shape=[2, 2], dtype=dtype)\n fd.add_output(output)\n\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n for i in range(100):\n output = fd.execute([])[0]\n\n # Rarely we might have a pair of matching lower precision\n # samples. However, it is extremely rare that we would have a\n # set of three matching elements in only 100 repeats unless we\n # have a bug.\n\n match = output.flatten().unsqueeze(0) == output.flatten().unsqueeze(1)\n match_pairs = (\n match ^ torch.eye(4, dtype=torch.bool, device=\"cuda\")\n ).sum() // 2\n\n assert match_pairs.item() < 3, f\"At least three entries match in {output}\"\n\n\n@pytest.mark.parametrize(\"padding_idx\", [None, -2])\n@pytest.mark.parametrize(\"max_norm\", [None, 1e-5])\n@pytest.mark.parametrize(\"norm_type\", [None, 1.0])\n@pytest.mark.parametrize(\"scale_grad_by_freq\", [None, True])\n@pytest.mark.parametrize(\"sparse\", [None, True])\ndef test_embedding(\n padding_idx: None | int,\n max_norm: None | float,\n norm_type: None | float,\n scale_grad_by_freq: None | bool,\n sparse: None | bool,\n):\n def fusion_func(\n fd: FusionDefinition,\n has_optional_inputs: list[bool],\n optional_inputs_dtypes: list[DataType],\n ):\n input = fd.define_tensor(","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_embedding","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_embedding#L1300-L1371","kind":"function","name":"test_embedding","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1300,"end_line":1371,"context_start_line":1280,"context_end_line":1391,"code":" output = fd.execute([])[0]\n\n # Rarely we might have a pair of matching lower precision\n # samples. However, it is extremely rare that we would have a\n # set of three matching elements in only 100 repeats unless we\n # have a bug.\n\n match = output.flatten().unsqueeze(0) == output.flatten().unsqueeze(1)\n match_pairs = (\n match ^ torch.eye(4, dtype=torch.bool, device=\"cuda\")\n ).sum() // 2\n\n assert match_pairs.item() < 3, f\"At least three entries match in {output}\"\n\n\n@pytest.mark.parametrize(\"padding_idx\", [None, -2])\n@pytest.mark.parametrize(\"max_norm\", [None, 1e-5])\n@pytest.mark.parametrize(\"norm_type\", [None, 1.0])\n@pytest.mark.parametrize(\"scale_grad_by_freq\", [None, True])\n@pytest.mark.parametrize(\"sparse\", [None, True])\ndef test_embedding(\n padding_idx: None | int,\n max_norm: None | float,\n norm_type: None | float,\n scale_grad_by_freq: None | bool,\n sparse: None | bool,\n):\n def fusion_func(\n fd: FusionDefinition,\n has_optional_inputs: list[bool],\n optional_inputs_dtypes: list[DataType],\n ):\n input = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Int,\n is_cpu=False,\n )\n weight = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n # padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse\n optional_inputs = [None] * 5\n for idx in range(len(optional_inputs)):\n if has_optional_inputs[idx]:\n optional_inputs[idx] = fd.define_scalar(\n value=None, dtype=optional_inputs_dtypes[idx]\n )\n out = fd.ops.embedding_fwd(input, weight, *optional_inputs)\n fd.add_output(out)\n\n N, S = 10, 3\n input = torch.randint(\n N, (S,), dtype=torch.int64, device=\"cuda\", requires_grad=False\n )\n weight = torch.randn(N, S, dtype=torch.bfloat16, device=\"cuda\", requires_grad=True)\n optional_inputs_dtypes = [\n DataType.Int,\n DataType.Float,\n DataType.Float,\n DataType.Bool,\n DataType.Bool,\n ]\n\n # This is not in pytest_ops.py since the torch API does not accept None values for some arguments.\n # Different inputs for nvfuser and torch API cannot be handled within OpInfo\n optional_inputs = [padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse]\n has_optional_inputs = [None] * 5\n inputs = [input, weight]\n for idx, param in enumerate(optional_inputs):\n if param is not None:\n has_optional_inputs[idx] = True\n inputs.append(param)\n\n with FusionDefinition() as fd:\n fusion_func(\n fd,\n has_optional_inputs=has_optional_inputs,\n optional_inputs_dtypes=optional_inputs_dtypes,\n )\n nvf_out = fd.execute(inputs)\n\n norm_type = 2.0 if norm_type is None else norm_type\n scale_grad_by_freq = False if scale_grad_by_freq is None else scale_grad_by_freq\n sparse = False if sparse is None else sparse\n ref_out = torch.nn.functional.embedding(\n input, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse\n )\n torch.testing.assert_close(nvf_out[0], ref_out)\n\n\ndef test_stride_order_with_explicit_broadcast(nvfuser_direct_test):\n inputs = [\n torch.randn(3, device=\"cuda\").unsqueeze(-1),\n torch.randn(2, 3, device=\"cuda\").unsqueeze(-1).expand(2, 3, 4).transpose(2, 0),\n torch.randn(5 * 960, device=\"cuda\").as_strided(\n (5, 4, 1, 5, 16), (960, 48, 16, 192, 1)\n ),\n torch.randn(6, device=\"cuda\").as_strided((2, 16, 3), (3, 0, 1)),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.define_tensor(\n shape=[-1, 16, 3],\n contiguity=[None, True, True],\n dtype=DataType.Float,","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_stride_order_with_explicit_broadcast","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_stride_order_with_explicit_broadcast#L1374-L1410","kind":"function","name":"test_stride_order_with_explicit_broadcast","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1374,"end_line":1410,"context_start_line":1354,"context_end_line":1430,"code":" has_optional_inputs[idx] = True\n inputs.append(param)\n\n with FusionDefinition() as fd:\n fusion_func(\n fd,\n has_optional_inputs=has_optional_inputs,\n optional_inputs_dtypes=optional_inputs_dtypes,\n )\n nvf_out = fd.execute(inputs)\n\n norm_type = 2.0 if norm_type is None else norm_type\n scale_grad_by_freq = False if scale_grad_by_freq is None else scale_grad_by_freq\n sparse = False if sparse is None else sparse\n ref_out = torch.nn.functional.embedding(\n input, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse\n )\n torch.testing.assert_close(nvf_out[0], ref_out)\n\n\ndef test_stride_order_with_explicit_broadcast(nvfuser_direct_test):\n inputs = [\n torch.randn(3, device=\"cuda\").unsqueeze(-1),\n torch.randn(2, 3, device=\"cuda\").unsqueeze(-1).expand(2, 3, 4).transpose(2, 0),\n torch.randn(5 * 960, device=\"cuda\").as_strided(\n (5, 4, 1, 5, 16), (960, 48, 16, 192, 1)\n ),\n torch.randn(6, device=\"cuda\").as_strided((2, 16, 3), (3, 0, 1)),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.define_tensor(\n shape=[-1, 16, 3],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n stride_order=[1, 2, 0],\n is_cpu=False,\n )\n\n t0_b = fd.ops.broadcast(t0, [True, False, False])\n t4 = fd.ops.add(t0_b, t1)\n c0 = fd.define_scalar(3.0)\n t5 = fd.ops.add(t2, c0)\n t6 = fd.ops.mul(t3, c0)\n\n fd.add_output(t4)\n fd.add_output(t5)\n fd.add_output(t6)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0] + inputs[1]\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0] + inputs[1])\n nvfuser_direct_test.assertEqual(nvf_out[1], inputs[2] + 3.0)\n nvfuser_direct_test.assertEqual(nvf_out[2], inputs[3] * 3.0)\n\n\ndef test_output_stride_order(nvfuser_direct_test):\n inputs = [\n torch.arange(0, 24).reshape(2, 3, 4).cuda().float(),\n ]\n eager_out = inputs[0] + 3.0\n\n for perm in itertools.permutations(range(3), 3):\n # testing stride_order in set\n def fusion_set_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(3.0)\n t1 = fd.ops.add(t0, c0)\n t2 = fd.ops.stride_order(t1, perm)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_set_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_output_stride_order","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_output_stride_order#L1413-L1432","kind":"function","name":"test_output_stride_order","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1413,"end_line":1432,"context_start_line":1393,"context_end_line":1452,"code":" is_cpu=False,\n )\n\n t0_b = fd.ops.broadcast(t0, [True, False, False])\n t4 = fd.ops.add(t0_b, t1)\n c0 = fd.define_scalar(3.0)\n t5 = fd.ops.add(t2, c0)\n t6 = fd.ops.mul(t3, c0)\n\n fd.add_output(t4)\n fd.add_output(t5)\n fd.add_output(t6)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0] + inputs[1]\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0] + inputs[1])\n nvfuser_direct_test.assertEqual(nvf_out[1], inputs[2] + 3.0)\n nvfuser_direct_test.assertEqual(nvf_out[2], inputs[3] * 3.0)\n\n\ndef test_output_stride_order(nvfuser_direct_test):\n inputs = [\n torch.arange(0, 24).reshape(2, 3, 4).cuda().float(),\n ]\n eager_out = inputs[0] + 3.0\n\n for perm in itertools.permutations(range(3), 3):\n # testing stride_order in set\n def fusion_set_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(3.0)\n t1 = fd.ops.add(t0, c0)\n t2 = fd.ops.stride_order(t1, perm)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_set_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n nvf_stride = nvf_out[0].stride()\n verify_stride_order(nvf_stride, perm)\n\n\ndef test_output_stride_order_with_reduction(nvfuser_direct_test):\n inputs = [torch.randn(2, 3, 4, 5, device=\"cuda\", dtype=torch.float)]\n\n for stride_order in itertools.permutations(range(3), 3):\n\n def fusion_stride_order_op(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.sum(T0, dims=[2])\n T2 = fd.ops.stride_order(T1, stride_order)\n fd.add_output(T2)\n\n with FusionDefinition() as fd:\n fusion_stride_order_op(fd)\n\n out = fd.execute(inputs)[0]\n verify_stride_order(out.stride(), stride_order)\n\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_output_stride_order_with_reduction","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_output_stride_order_with_reduction#L1435-L1450","kind":"function","name":"test_output_stride_order_with_reduction","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1435,"end_line":1450,"context_start_line":1415,"context_end_line":1470,"code":" torch.arange(0, 24).reshape(2, 3, 4).cuda().float(),\n ]\n eager_out = inputs[0] + 3.0\n\n for perm in itertools.permutations(range(3), 3):\n # testing stride_order in set\n def fusion_set_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(3.0)\n t1 = fd.ops.add(t0, c0)\n t2 = fd.ops.stride_order(t1, perm)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_set_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n nvf_stride = nvf_out[0].stride()\n verify_stride_order(nvf_stride, perm)\n\n\ndef test_output_stride_order_with_reduction(nvfuser_direct_test):\n inputs = [torch.randn(2, 3, 4, 5, device=\"cuda\", dtype=torch.float)]\n\n for stride_order in itertools.permutations(range(3), 3):\n\n def fusion_stride_order_op(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.sum(T0, dims=[2])\n T2 = fd.ops.stride_order(T1, stride_order)\n fd.add_output(T2)\n\n with FusionDefinition() as fd:\n fusion_stride_order_op(fd)\n\n out = fd.execute(inputs)[0]\n verify_stride_order(out.stride(), stride_order)\n\n\ndef test_triu(nvfuser_direct_test):\n inputs = [\n torch.randn(4, 16, device=\"cuda\", dtype=torch.float16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.triu(t0, -1)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out0 = torch.triu(inputs[0], -1)\n nvfuser_direct_test.assertEqual(eager_out0, nvf_out[0])\n\n\ndef test_scatter_output_intermediate(nvfuser_direct_test):\n bsz = 128\n hidden = 1024","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_triu","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_triu#L1453-L1465","kind":"function","name":"test_triu","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1453,"end_line":1465,"context_start_line":1433,"context_end_line":1485,"code":"\n\ndef test_output_stride_order_with_reduction(nvfuser_direct_test):\n inputs = [torch.randn(2, 3, 4, 5, device=\"cuda\", dtype=torch.float)]\n\n for stride_order in itertools.permutations(range(3), 3):\n\n def fusion_stride_order_op(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.sum(T0, dims=[2])\n T2 = fd.ops.stride_order(T1, stride_order)\n fd.add_output(T2)\n\n with FusionDefinition() as fd:\n fusion_stride_order_op(fd)\n\n out = fd.execute(inputs)[0]\n verify_stride_order(out.stride(), stride_order)\n\n\ndef test_triu(nvfuser_direct_test):\n inputs = [\n torch.randn(4, 16, device=\"cuda\", dtype=torch.float16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.triu(t0, -1)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out0 = torch.triu(inputs[0], -1)\n nvfuser_direct_test.assertEqual(eager_out0, nvf_out[0])\n\n\ndef test_scatter_output_intermediate(nvfuser_direct_test):\n bsz = 128\n hidden = 1024\n scatter_size = 64\n scatter_dim = 0\n\n x = torch.randn([bsz, hidden], device=\"cuda\")\n _, ind = torch.topk(x, k=scatter_size, dim=scatter_dim)\n src = torch.randn(scatter_size, hidden, device=\"cuda\")\n inputs = [x, ind, src]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_scatter_output_intermediate","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_scatter_output_intermediate#L1468-L1507","kind":"function","name":"test_scatter_output_intermediate","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1468,"end_line":1507,"context_start_line":1448,"context_end_line":1527,"code":"\n out = fd.execute(inputs)[0]\n verify_stride_order(out.stride(), stride_order)\n\n\ndef test_triu(nvfuser_direct_test):\n inputs = [\n torch.randn(4, 16, device=\"cuda\", dtype=torch.float16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.triu(t0, -1)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out0 = torch.triu(inputs[0], -1)\n nvfuser_direct_test.assertEqual(eager_out0, nvf_out[0])\n\n\ndef test_scatter_output_intermediate(nvfuser_direct_test):\n bsz = 128\n hidden = 1024\n scatter_size = 64\n scatter_dim = 0\n\n x = torch.randn([bsz, hidden], device=\"cuda\")\n _, ind = torch.topk(x, k=scatter_size, dim=scatter_dim)\n src = torch.randn(scatter_size, hidden, device=\"cuda\")\n inputs = [x, ind, src]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.ops.scatter(T0, T1, T2, scatter_dim)\n T4 = fd.ops.sigmoid(T3)\n fd.add_output(T4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.sigmoid(torch.scatter(x, scatter_dim, ind, src))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_scatter_scalar_src(nvfuser_direct_test):\n bsz = 128\n hidden = 1024\n scatter_size = 64\n scatter_dim = 0\n\n x = torch.randn([bsz, hidden], device=\"cuda\")\n _, ind = torch.topk(x, k=scatter_size, dim=scatter_dim)\n src = 1.5\n inputs = [x, ind, src]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_scatter_scalar_src","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_scatter_scalar_src#L1510-L1542","kind":"function","name":"test_scatter_scalar_src","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1510,"end_line":1542,"context_start_line":1490,"context_end_line":1562,"code":" dtype=DataType.Int,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.ops.scatter(T0, T1, T2, scatter_dim)\n T4 = fd.ops.sigmoid(T3)\n fd.add_output(T4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.sigmoid(torch.scatter(x, scatter_dim, ind, src))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_scatter_scalar_src(nvfuser_direct_test):\n bsz = 128\n hidden = 1024\n scatter_size = 64\n scatter_dim = 0\n\n x = torch.randn([bsz, hidden], device=\"cuda\")\n _, ind = torch.topk(x, k=scatter_size, dim=scatter_dim)\n src = 1.5\n inputs = [x, ind, src]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[1, 0],\n )\n S2 = fd.define_scalar(None, dtype=DataType.Double)\n T3 = fd.ops.scatter(T0, T1, S2, scatter_dim)\n fd.add_output(T3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.scatter(x, scatter_dim, ind, src)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_compute_tensor_descriptor(nvfuser_direct_test):\n configs = (\n (\n # size\n [2, 1, 3, 1, 4, 3],\n # stride\n [12, 4, 4, 4, 1, 0],\n # expected contiguity\n [True, None, True, None, True, None],\n # expected stride_order\n [5, 4, 3, 2, 1, 0],\n ),\n (\n [2, 3, 1, 5, 4],\n [28, 4, 14, 0, 1],\n [False, None, True, None, True],\n [4, 2, 3, 1, 0],\n ),","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_compute_tensor_descriptor","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_compute_tensor_descriptor#L1545-L1600","kind":"function","name":"test_compute_tensor_descriptor","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1545,"end_line":1600,"context_start_line":1525,"context_end_line":1620,"code":" dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[1, 0],\n )\n S2 = fd.define_scalar(None, dtype=DataType.Double)\n T3 = fd.ops.scatter(T0, T1, S2, scatter_dim)\n fd.add_output(T3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.scatter(x, scatter_dim, ind, src)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_compute_tensor_descriptor(nvfuser_direct_test):\n configs = (\n (\n # size\n [2, 1, 3, 1, 4, 3],\n # stride\n [12, 4, 4, 4, 1, 0],\n # expected contiguity\n [True, None, True, None, True, None],\n # expected stride_order\n [5, 4, 3, 2, 1, 0],\n ),\n (\n [2, 3, 1, 5, 4],\n [28, 4, 14, 0, 1],\n [False, None, True, None, True],\n [4, 2, 3, 1, 0],\n ),\n (\n [2, 2, 1, 1, 2, 2, 2],\n [8, 4, 3, 9, 2, 0, 1],\n [None, True, True, None, True, None, True],\n [5, 4, 3, 6, 2, 1, 0],\n ),\n (\n [2, 2, 1, 2, 4, 2],\n [2, 32, 1, 8, 0, 4],\n [False, True, True, False, None, None],\n [2, 5, 0, 4, 1, 3],\n ),\n (\n [2, 2, 2, 2],\n [8, 4, 2, 1],\n [True, True, True, True],\n [3, 2, 1, 0],\n ),\n (\n [2, 1, 3, 1, 4],\n [24, 4, 8, 4, 2],\n [True, True, None, None, False],\n [4, 2, 3, 1, 0],\n ),\n (\n [2, 2, 2, 2],\n [8, 4, 0, 2],\n [True, True, None, False],\n [3, 2, 1, 0],\n ),\n )\n\n for sizes, strides, contiguity, stride_order in configs:\n computed_contiguity, computed_stride_order = compute_tensor_descriptor(\n sizes, strides\n )\n nvfuser_direct_test.assertEqual(computed_contiguity, contiguity)\n nvfuser_direct_test.assertEqual(computed_stride_order, stride_order)\n\n\ndef test_complex_constants(nvfuser_direct_test):\n inputs = [\n torch.arange(2, device=\"cuda\").type(torch.complex64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(complex(3.0, 0.5))\n t1 = fd.ops.mul(t0, c0)\n fd.add_output(t1)\n\n (n,), _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = inputs[0] * (3.0 + 0.5j)\n\n nvfuser_direct_test.assertEqual(eager_out, n)\n assert n.dtype == torch.complex64\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_complex_constants","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_complex_constants#L1603-L1619","kind":"function","name":"test_complex_constants","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1603,"end_line":1619,"context_start_line":1583,"context_end_line":1639,"code":" [24, 4, 8, 4, 2],\n [True, True, None, None, False],\n [4, 2, 3, 1, 0],\n ),\n (\n [2, 2, 2, 2],\n [8, 4, 0, 2],\n [True, True, None, False],\n [3, 2, 1, 0],\n ),\n )\n\n for sizes, strides, contiguity, stride_order in configs:\n computed_contiguity, computed_stride_order = compute_tensor_descriptor(\n sizes, strides\n )\n nvfuser_direct_test.assertEqual(computed_contiguity, contiguity)\n nvfuser_direct_test.assertEqual(computed_stride_order, stride_order)\n\n\ndef test_complex_constants(nvfuser_direct_test):\n inputs = [\n torch.arange(2, device=\"cuda\").type(torch.complex64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(complex(3.0, 0.5))\n t1 = fd.ops.mul(t0, c0)\n fd.add_output(t1)\n\n (n,), _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = inputs[0] * (3.0 + 0.5j)\n\n nvfuser_direct_test.assertEqual(eager_out, n)\n assert n.dtype == torch.complex64\n\n\ndef test_complex_rsqrt(nvfuser_direct_test):\n inputs = [\n torch.randn(4, device=\"cuda\", dtype=torch.complex64),\n torch.randn(4, device=\"cuda\", dtype=torch.complex128),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.rsqrt(t0)\n fd.add_output(t2)\n t3 = fd.ops.rsqrt(t1)\n fd.add_output(t3)\n\n (rfloat, rdouble), _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n at_rfloat = inputs[0].rsqrt()\n at_rdouble = inputs[1].rsqrt()","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_complex_rsqrt","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_complex_rsqrt#L1622-L1642","kind":"function","name":"test_complex_rsqrt","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1622,"end_line":1642,"context_start_line":1602,"context_end_line":1662,"code":"\ndef test_complex_constants(nvfuser_direct_test):\n inputs = [\n torch.arange(2, device=\"cuda\").type(torch.complex64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(complex(3.0, 0.5))\n t1 = fd.ops.mul(t0, c0)\n fd.add_output(t1)\n\n (n,), _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = inputs[0] * (3.0 + 0.5j)\n\n nvfuser_direct_test.assertEqual(eager_out, n)\n assert n.dtype == torch.complex64\n\n\ndef test_complex_rsqrt(nvfuser_direct_test):\n inputs = [\n torch.randn(4, device=\"cuda\", dtype=torch.complex64),\n torch.randn(4, device=\"cuda\", dtype=torch.complex128),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.rsqrt(t0)\n fd.add_output(t2)\n t3 = fd.ops.rsqrt(t1)\n fd.add_output(t3)\n\n (rfloat, rdouble), _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n at_rfloat = inputs[0].rsqrt()\n at_rdouble = inputs[1].rsqrt()\n\n nvfuser_direct_test.assertEqual(at_rfloat, rfloat)\n nvfuser_direct_test.assertEqual(at_rdouble, rdouble)\n\n\ndef test_constant_nans(nvfuser_direct_test):\n inputs = [\n torch.randn(4, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(float(\"nan\"))\n t1 = fd.ops.add(t0, c0)\n fd.add_output(t1)\n\n eager_out = inputs[0] + float(\"nan\")\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_gcd(nvfuser_direct_test):","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_constant_nans","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_constant_nans#L1645-L1659","kind":"function","name":"test_constant_nans","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1645,"end_line":1659,"context_start_line":1625,"context_end_line":1679,"code":" torch.randn(4, device=\"cuda\", dtype=torch.complex128),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.rsqrt(t0)\n fd.add_output(t2)\n t3 = fd.ops.rsqrt(t1)\n fd.add_output(t3)\n\n (rfloat, rdouble), _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n at_rfloat = inputs[0].rsqrt()\n at_rdouble = inputs[1].rsqrt()\n\n nvfuser_direct_test.assertEqual(at_rfloat, rfloat)\n nvfuser_direct_test.assertEqual(at_rdouble, rdouble)\n\n\ndef test_constant_nans(nvfuser_direct_test):\n inputs = [\n torch.randn(4, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(float(\"nan\"))\n t1 = fd.ops.add(t0, c0)\n fd.add_output(t1)\n\n eager_out = inputs[0] + float(\"nan\")\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_gcd(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.gcd(t0, t1)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch.gcd(inputs[0], inputs[1]))\n\n\ndef test_input_scalar(nvfuser_direct_test):\n inputs = [","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_gcd","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_gcd#L1662-L1675","kind":"function","name":"test_gcd","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1662,"end_line":1675,"context_start_line":1642,"context_end_line":1695,"code":" nvfuser_direct_test.assertEqual(at_rdouble, rdouble)\n\n\ndef test_constant_nans(nvfuser_direct_test):\n inputs = [\n torch.randn(4, 4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(float(\"nan\"))\n t1 = fd.ops.add(t0, c0)\n fd.add_output(t1)\n\n eager_out = inputs[0] + float(\"nan\")\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_gcd(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.gcd(t0, t1)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch.gcd(inputs[0], inputs[1]))\n\n\ndef test_input_scalar(nvfuser_direct_test):\n inputs = [\n torch.randn((3,), dtype=torch.float32, device=\"cuda:0\"),\n 0.1,\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n S1 = fd.define_scalar()\n T1 = fd.ops.mul(T0, S1)\n fd.add_output(T1)\n\n # Just test that this executes, not that it's correct\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_integer_division(nvfuser_direct_test):\n inputs = [","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_input_scalar","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_input_scalar#L1678-L1691","kind":"function","name":"test_input_scalar","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1678,"end_line":1691,"context_start_line":1658,"context_end_line":1711,"code":" nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_gcd(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.gcd(t0, t1)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch.gcd(inputs[0], inputs[1]))\n\n\ndef test_input_scalar(nvfuser_direct_test):\n inputs = [\n torch.randn((3,), dtype=torch.float32, device=\"cuda:0\"),\n 0.1,\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n S1 = fd.define_scalar()\n T1 = fd.ops.mul(T0, S1)\n fd.add_output(T1)\n\n # Just test that this executes, not that it's correct\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_integer_division(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n t3 = fd.ops.truediv(t0, t1)\n fd.add_output(t2)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(\n nvf_out[0], torch.div(inputs[0], inputs[1], rounding_mode=\"trunc\")\n )","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_integer_division","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_integer_division#L1694-L1712","kind":"function","name":"test_integer_division","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1694,"end_line":1712,"context_start_line":1674,"context_end_line":1732,"code":" nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch.gcd(inputs[0], inputs[1]))\n\n\ndef test_input_scalar(nvfuser_direct_test):\n inputs = [\n torch.randn((3,), dtype=torch.float32, device=\"cuda:0\"),\n 0.1,\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n S1 = fd.define_scalar()\n T1 = fd.ops.mul(T0, S1)\n fd.add_output(T1)\n\n # Just test that this executes, not that it's correct\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_integer_division(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n t3 = fd.ops.truediv(t0, t1)\n fd.add_output(t2)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(\n nvf_out[0], torch.div(inputs[0], inputs[1], rounding_mode=\"trunc\")\n )\n nvfuser_direct_test.assertEqual(nvf_out[1], torch.true_divide(inputs[0], inputs[1]))\n\n\ndef test_mark_alias_pass(nvfuser_direct_test):\n def reshape(fd: FusionDefinition) -> None:\n x = fd.define_tensor(\n [2, 3, 4], contiguity=[True, True, True], dtype=DataType.Float\n )\n y = fd.ops.reshape(x, [2, 12])\n fd.add_output(y)\n\n x = torch.rand(2, 3, 4, device=\"cuda\")\n ys, _ = nvfuser_direct_test.exec_nvfuser(reshape, [x])\n nvfuser_direct_test.assertEqual(len(ys), 1)\n y = ys[0]\n\n nvfuser_direct_test.assertEqual(y.data_ptr(), x.data_ptr())\n\n\ndef test_misaligned_add(nvfuser_direct_test):\n inputs = [","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_mark_alias_pass","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_mark_alias_pass#L1715-L1728","kind":"function","name":"test_mark_alias_pass","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1715,"end_line":1728,"context_start_line":1695,"context_end_line":1748,"code":" inputs = [\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n t3 = fd.ops.truediv(t0, t1)\n fd.add_output(t2)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(\n nvf_out[0], torch.div(inputs[0], inputs[1], rounding_mode=\"trunc\")\n )\n nvfuser_direct_test.assertEqual(nvf_out[1], torch.true_divide(inputs[0], inputs[1]))\n\n\ndef test_mark_alias_pass(nvfuser_direct_test):\n def reshape(fd: FusionDefinition) -> None:\n x = fd.define_tensor(\n [2, 3, 4], contiguity=[True, True, True], dtype=DataType.Float\n )\n y = fd.ops.reshape(x, [2, 12])\n fd.add_output(y)\n\n x = torch.rand(2, 3, 4, device=\"cuda\")\n ys, _ = nvfuser_direct_test.exec_nvfuser(reshape, [x])\n nvfuser_direct_test.assertEqual(len(ys), 1)\n y = ys[0]\n\n nvfuser_direct_test.assertEqual(y.data_ptr(), x.data_ptr())\n\n\ndef test_misaligned_add(nvfuser_direct_test):\n inputs = [\n torch.ones(2**20 + 1, device=\"cuda\")[1:], # cannot vectorize\n torch.ones(2**20, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n\n fd.add_output(t2)\n\n # Fails because vectorization 4 is set but only 1 supported\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_misaligned_add","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_misaligned_add#L1731-L1747","kind":"function","name":"test_misaligned_add","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1731,"end_line":1747,"context_start_line":1711,"context_end_line":1767,"code":" )\n nvfuser_direct_test.assertEqual(nvf_out[1], torch.true_divide(inputs[0], inputs[1]))\n\n\ndef test_mark_alias_pass(nvfuser_direct_test):\n def reshape(fd: FusionDefinition) -> None:\n x = fd.define_tensor(\n [2, 3, 4], contiguity=[True, True, True], dtype=DataType.Float\n )\n y = fd.ops.reshape(x, [2, 12])\n fd.add_output(y)\n\n x = torch.rand(2, 3, 4, device=\"cuda\")\n ys, _ = nvfuser_direct_test.exec_nvfuser(reshape, [x])\n nvfuser_direct_test.assertEqual(len(ys), 1)\n y = ys[0]\n\n nvfuser_direct_test.assertEqual(y.data_ptr(), x.data_ptr())\n\n\ndef test_misaligned_add(nvfuser_direct_test):\n inputs = [\n torch.ones(2**20 + 1, device=\"cuda\")[1:], # cannot vectorize\n torch.ones(2**20, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n\n fd.add_output(t2)\n\n # Fails because vectorization 4 is set but only 1 supported\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_nextafter(nvfuser_direct_test):\n inputs = [\n # torch.nextafter is only defined for float{32,64} tensor inputs\n torch.testing.make_tensor(4, device=\"cuda\", dtype=torch.float32),\n torch.testing.make_tensor(4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n s0 = fd.define_scalar(1.0, dtype=DataType.Float)\n s1 = fd.define_scalar(-1.0, dtype=DataType.Double)\n\n for a, b in itertools.product(\n [t0, t1, s0, s1],\n [t0, t1, s0, s1],\n ):","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_nextafter","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_nextafter#L1750-L1786","kind":"function","name":"test_nextafter","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1750,"end_line":1786,"context_start_line":1730,"context_end_line":1806,"code":"\ndef test_misaligned_add(nvfuser_direct_test):\n inputs = [\n torch.ones(2**20 + 1, device=\"cuda\")[1:], # cannot vectorize\n torch.ones(2**20, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n\n fd.add_output(t2)\n\n # Fails because vectorization 4 is set but only 1 supported\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_nextafter(nvfuser_direct_test):\n inputs = [\n # torch.nextafter is only defined for float{32,64} tensor inputs\n torch.testing.make_tensor(4, device=\"cuda\", dtype=torch.float32),\n torch.testing.make_tensor(4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n s0 = fd.define_scalar(1.0, dtype=DataType.Float)\n s1 = fd.define_scalar(-1.0, dtype=DataType.Double)\n\n for a, b in itertools.product(\n [t0, t1, s0, s1],\n [t0, t1, s0, s1],\n ):\n # always enter the fusion...\n t = fd.ops.nextafter(a, b)\n if t.is_tensor():\n # ...but skip outputting scalars, which we don't support\n fd.add_output(t)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n ab = [inputs[0], inputs[1], 1.0, -1.0]\n i = 0\n for a, b in itertools.product(ab, ab):\n if not (isinstance(a, torch.Tensor) or isinstance(b, torch.Tensor)):\n continue\n n = nvf_out[i]\n i += 1\n torch_out = torch.nextafter(\n torch.as_tensor(a, device=\"cuda\"), torch.as_tensor(b, device=\"cuda\")\n )\n nvfuser_direct_test.assertEqual(n, torch_out)\n\n\ndef test_prod(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n\n t1 = fd.ops.prod(t0, DataType.Float)\n t2 = fd.ops.prod(t0, 1, False, DataType.Float)\n t3 = fd.ops.prod(t0, 1, True, DataType.Float)\n t4 = fd.ops.prod(t0, [-1], False, DataType.Float)\n\n fd.add_output(t1)\n fd.add_output(t2)\n fd.add_output(t3)\n fd.add_output(t4)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_prod","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_prod#L1789-L1818","kind":"function","name":"test_prod","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1789,"end_line":1818,"context_start_line":1769,"context_end_line":1838,"code":" t = fd.ops.nextafter(a, b)\n if t.is_tensor():\n # ...but skip outputting scalars, which we don't support\n fd.add_output(t)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n ab = [inputs[0], inputs[1], 1.0, -1.0]\n i = 0\n for a, b in itertools.product(ab, ab):\n if not (isinstance(a, torch.Tensor) or isinstance(b, torch.Tensor)):\n continue\n n = nvf_out[i]\n i += 1\n torch_out = torch.nextafter(\n torch.as_tensor(a, device=\"cuda\"), torch.as_tensor(b, device=\"cuda\")\n )\n nvfuser_direct_test.assertEqual(n, torch_out)\n\n\ndef test_prod(nvfuser_direct_test):\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n\n t1 = fd.ops.prod(t0, DataType.Float)\n t2 = fd.ops.prod(t0, 1, False, DataType.Float)\n t3 = fd.ops.prod(t0, 1, True, DataType.Float)\n t4 = fd.ops.prod(t0, [-1], False, DataType.Float)\n\n fd.add_output(t1)\n fd.add_output(t2)\n fd.add_output(t3)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_outs = [\n torch.prod(inputs[0], dtype=torch.float32),\n torch.prod(inputs[0], 1, False, dtype=torch.float32),\n torch.prod(inputs[0], 1, True, dtype=torch.float32),\n torch.prod(inputs[0], -1, False, dtype=torch.float32),\n ]\n assert len(nvf_out) == len(eager_outs)\n\n for n, e in zip(nvf_out, eager_outs):\n nvfuser_direct_test.assertEqual(n, e)\n\n\ndef test_real_imag(nvfuser_direct_test):\n for dtype in [torch.complex128, torch.complex64]:\n inputs = [\n torch.randn(5, dtype=dtype, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n fd.add_output(fd.ops.real(t0))\n fd.add_output(fd.ops.imag(t0))\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(torch.real(inputs[0]), nvf_out[0])\n nvfuser_direct_test.assertEqual(torch.imag(inputs[0]), nvf_out[1])\n\n\ndef test_reduction_complex_number(nvfuser_direct_test):","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_real_imag","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_real_imag#L1821-L1835","kind":"function","name":"test_real_imag","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1821,"end_line":1835,"context_start_line":1801,"context_end_line":1855,"code":"\n fd.add_output(t1)\n fd.add_output(t2)\n fd.add_output(t3)\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_outs = [\n torch.prod(inputs[0], dtype=torch.float32),\n torch.prod(inputs[0], 1, False, dtype=torch.float32),\n torch.prod(inputs[0], 1, True, dtype=torch.float32),\n torch.prod(inputs[0], -1, False, dtype=torch.float32),\n ]\n assert len(nvf_out) == len(eager_outs)\n\n for n, e in zip(nvf_out, eager_outs):\n nvfuser_direct_test.assertEqual(n, e)\n\n\ndef test_real_imag(nvfuser_direct_test):\n for dtype in [torch.complex128, torch.complex64]:\n inputs = [\n torch.randn(5, dtype=dtype, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n fd.add_output(fd.ops.real(t0))\n fd.add_output(fd.ops.imag(t0))\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(torch.real(inputs[0]), nvf_out[0])\n nvfuser_direct_test.assertEqual(torch.imag(inputs[0]), nvf_out[1])\n\n\ndef test_reduction_complex_number(nvfuser_direct_test):\n def test_dtype(torch_dtype):\n inputs = [torch.randn(2, 32, device=\"cuda\", dtype=torch_dtype)]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.sum(t0, [-1], False, torch_dtype_to_nvfuser_dtype(torch_dtype))\n fd.add_output(t1)\n\n nvf_out1, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum(inputs[0], dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out1[0])\n\n list_of_dtype = [torch.complex64, torch.complex128]\n for torch_dtype in list_of_dtype:\n test_dtype(torch_dtype)\n\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_reduction_complex_number","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_reduction_complex_number#L1838-L1853","kind":"function","name":"test_reduction_complex_number","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1838,"end_line":1853,"context_start_line":1818,"context_end_line":1873,"code":" nvfuser_direct_test.assertEqual(n, e)\n\n\ndef test_real_imag(nvfuser_direct_test):\n for dtype in [torch.complex128, torch.complex64]:\n inputs = [\n torch.randn(5, dtype=dtype, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n fd.add_output(fd.ops.real(t0))\n fd.add_output(fd.ops.imag(t0))\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(torch.real(inputs[0]), nvf_out[0])\n nvfuser_direct_test.assertEqual(torch.imag(inputs[0]), nvf_out[1])\n\n\ndef test_reduction_complex_number(nvfuser_direct_test):\n def test_dtype(torch_dtype):\n inputs = [torch.randn(2, 32, device=\"cuda\", dtype=torch_dtype)]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.sum(t0, [-1], False, torch_dtype_to_nvfuser_dtype(torch_dtype))\n fd.add_output(t1)\n\n nvf_out1, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum(inputs[0], dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out1[0])\n\n list_of_dtype = [torch.complex64, torch.complex128]\n for torch_dtype in list_of_dtype:\n test_dtype(torch_dtype)\n\n\ndef test_right_shift_arithmetic(nvfuser_direct_test):\n inputs = [torch.tensor([-2147483648, 1073741824], dtype=torch.int32, device=\"cuda\")]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(3)\n t1 = fd.ops.bitwise_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out1, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out1 = torch.bitwise_right_shift(inputs[0], 3)\n nvfuser_direct_test.assertEqual(eager_out1, nvf_out1[0])\n\n\ndef test_segment_set(nvfuser_direct_test):\n inputs = [\n torch.randn(5, 5, 5, device=\"cuda\"),\n ]","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_right_shift_arithmetic","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_right_shift_arithmetic#L1856-L1867","kind":"function","name":"test_right_shift_arithmetic","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1856,"end_line":1867,"context_start_line":1836,"context_end_line":1887,"code":"\n\ndef test_reduction_complex_number(nvfuser_direct_test):\n def test_dtype(torch_dtype):\n inputs = [torch.randn(2, 32, device=\"cuda\", dtype=torch_dtype)]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.sum(t0, [-1], False, torch_dtype_to_nvfuser_dtype(torch_dtype))\n fd.add_output(t1)\n\n nvf_out1, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum(inputs[0], dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out1[0])\n\n list_of_dtype = [torch.complex64, torch.complex128]\n for torch_dtype in list_of_dtype:\n test_dtype(torch_dtype)\n\n\ndef test_right_shift_arithmetic(nvfuser_direct_test):\n inputs = [torch.tensor([-2147483648, 1073741824], dtype=torch.int32, device=\"cuda\")]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(3)\n t1 = fd.ops.bitwise_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out1, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out1 = torch.bitwise_right_shift(inputs[0], 3)\n nvfuser_direct_test.assertEqual(eager_out1, nvf_out1[0])\n\n\ndef test_segment_set(nvfuser_direct_test):\n inputs = [\n torch.randn(5, 5, 5, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.neg(T0)\n T2 = fd.ops.segment_set(T1)\n T3 = fd.ops.relu(T2)\n fd.add_output(T3)\n\n eager_out = inputs[0].neg().relu()\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_segment_set","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_segment_set#L1870-L1885","kind":"function","name":"test_segment_set","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1870,"end_line":1885,"context_start_line":1850,"context_end_line":1905,"code":"\n list_of_dtype = [torch.complex64, torch.complex128]\n for torch_dtype in list_of_dtype:\n test_dtype(torch_dtype)\n\n\ndef test_right_shift_arithmetic(nvfuser_direct_test):\n inputs = [torch.tensor([-2147483648, 1073741824], dtype=torch.int32, device=\"cuda\")]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(3)\n t1 = fd.ops.bitwise_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out1, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out1 = torch.bitwise_right_shift(inputs[0], 3)\n nvfuser_direct_test.assertEqual(eager_out1, nvf_out1[0])\n\n\ndef test_segment_set(nvfuser_direct_test):\n inputs = [\n torch.randn(5, 5, 5, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.neg(T0)\n T2 = fd.ops.segment_set(T1)\n T3 = fd.ops.relu(T2)\n fd.add_output(T3)\n\n eager_out = inputs[0].neg().relu()\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_signbit(nvfuser_direct_test):\n inputs = [\n torch.randn(3, 4, 5, device=\"cuda\", dtype=torch.float32),\n torch.randn(3, 4, 5, device=\"cuda\", dtype=torch.float32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.where(\n fd.ops.signbit(t0), fd.ops.neg(fd.ops.abs(t1)), fd.ops.abs(t1)\n )\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n at_out = torch.where(\n torch.signbit(inputs[0]), -torch.abs(inputs[1]), torch.abs(inputs[1])\n )","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_signbit","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_signbit#L1888-L1906","kind":"function","name":"test_signbit","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1888,"end_line":1906,"context_start_line":1868,"context_end_line":1926,"code":"\n\ndef test_segment_set(nvfuser_direct_test):\n inputs = [\n torch.randn(5, 5, 5, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.neg(T0)\n T2 = fd.ops.segment_set(T1)\n T3 = fd.ops.relu(T2)\n fd.add_output(T3)\n\n eager_out = inputs[0].neg().relu()\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_signbit(nvfuser_direct_test):\n inputs = [\n torch.randn(3, 4, 5, device=\"cuda\", dtype=torch.float32),\n torch.randn(3, 4, 5, device=\"cuda\", dtype=torch.float32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.where(\n fd.ops.signbit(t0), fd.ops.neg(fd.ops.abs(t1)), fd.ops.abs(t1)\n )\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n at_out = torch.where(\n torch.signbit(inputs[0]), -torch.abs(inputs[1]), torch.abs(inputs[1])\n )\n nvfuser_direct_test.assertEqual(at_out, nvf_out[0])\n\n\ndef test_tensor_shape(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [2])\n t2 = fd.ops.sub(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.sub(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_tensor_shape","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_tensor_shape#L1909-L1928","kind":"function","name":"test_tensor_shape","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1909,"end_line":1928,"context_start_line":1889,"context_end_line":1948,"code":" inputs = [\n torch.randn(3, 4, 5, device=\"cuda\", dtype=torch.float32),\n torch.randn(3, 4, 5, device=\"cuda\", dtype=torch.float32),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.where(\n fd.ops.signbit(t0), fd.ops.neg(fd.ops.abs(t1)), fd.ops.abs(t1)\n )\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n at_out = torch.where(\n torch.signbit(inputs[0]), -torch.abs(inputs[1]), torch.abs(inputs[1])\n )\n nvfuser_direct_test.assertEqual(at_out, nvf_out[0])\n\n\ndef test_tensor_shape(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [2])\n t2 = fd.ops.sub(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.sub(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_tensor_shape_expand_bcast(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1, 1, -1], contiguity=[True, None, True])\n t2 = fd.define_tensor(shape=[-1, 1, -1], contiguity=[True, None, True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [0, 1, 2])\n t2_b = fd.ops.broadcast_in_dim(t2, t1_b.shape(), [0, 1, 2])\n\n fd.add_output(t2_b)\n\n inputs = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(2, 1, 4, device=\"cuda\"),\n torch.randn(2, 1, 4, device=\"cuda\"),\n ]\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_tensor_shape_expand_bcast","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_tensor_shape_expand_bcast#L1931-L1951","kind":"function","name":"test_tensor_shape_expand_bcast","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1931,"end_line":1951,"context_start_line":1911,"context_end_line":1971,"code":" torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(4, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [2])\n t2 = fd.ops.sub(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.sub(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_tensor_shape_expand_bcast(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1, 1, -1], contiguity=[True, None, True])\n t2 = fd.define_tensor(shape=[-1, 1, -1], contiguity=[True, None, True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [0, 1, 2])\n t2_b = fd.ops.broadcast_in_dim(t2, t1_b.shape(), [0, 1, 2])\n\n fd.add_output(t2_b)\n\n inputs = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(2, 1, 4, device=\"cuda\"),\n torch.randn(2, 1, 4, device=\"cuda\"),\n ]\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out1 = prims.broadcast_in_dim(inputs[1], inputs[0].size(), [0, 1, 2])\n eager_out2 = prims.broadcast_in_dim(inputs[2], eager_out1.size(), [0, 1, 2])\n nvfuser_direct_test.assertEqual(eager_out2, nvf_out[0])\n\n\ndef test_tensor_shape_nobcast(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 3, device=\"cuda\"),\n torch.randn(2, 3, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [0, 1])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [0, 1])","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_tensor_shape_nobcast","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_tensor_shape_nobcast#L1954-L1973","kind":"function","name":"test_tensor_shape_nobcast","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1954,"end_line":1973,"context_start_line":1934,"context_end_line":1993,"code":" t1 = fd.define_tensor(shape=[-1, 1, -1], contiguity=[True, None, True])\n t2 = fd.define_tensor(shape=[-1, 1, -1], contiguity=[True, None, True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [0, 1, 2])\n t2_b = fd.ops.broadcast_in_dim(t2, t1_b.shape(), [0, 1, 2])\n\n fd.add_output(t2_b)\n\n inputs = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(2, 1, 4, device=\"cuda\"),\n torch.randn(2, 1, 4, device=\"cuda\"),\n ]\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out1 = prims.broadcast_in_dim(inputs[1], inputs[0].size(), [0, 1, 2])\n eager_out2 = prims.broadcast_in_dim(inputs[2], eager_out1.size(), [0, 1, 2])\n nvfuser_direct_test.assertEqual(eager_out2, nvf_out[0])\n\n\ndef test_tensor_shape_nobcast(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 3, device=\"cuda\"),\n torch.randn(2, 3, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [0, 1])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [0, 1])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_tensor_shape_with_output_bcast(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n\n t1 = fd.ops.sum(t0, dims=[2])\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [0, 1])\n\n fd.add_output(t1_b)\n\n inputs_1 = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n inputs_2 = [\n torch.randn(4, 5, 32, device=\"cuda\"),\n ]\n\n inputs = inputs_1","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_tensor_shape_with_output_bcast","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_tensor_shape_with_output_bcast#L1976-L2008","kind":"function","name":"test_tensor_shape_with_output_bcast","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1976,"end_line":2008,"context_start_line":1956,"context_end_line":2028,"code":" torch.randn(2, 3, device=\"cuda\"),\n torch.randn(2, 3, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [0, 1])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [0, 1])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_tensor_shape_with_output_bcast(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n\n t1 = fd.ops.sum(t0, dims=[2])\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [0, 1])\n\n fd.add_output(t1_b)\n\n inputs_1 = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n ]\n\n inputs_2 = [\n torch.randn(4, 5, 32, device=\"cuda\"),\n ]\n\n inputs = inputs_1\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = prims.broadcast_in_dim(\n torch.sum(inputs[0], dim=-1), inputs[0].size(), [0, 1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Testing Dynamic usage of same Fusion\n inputs = inputs_2\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, new_fusion_expected=False\n )\n eager_out = prims.broadcast_in_dim(\n torch.sum(inputs[0], dim=-1), inputs[0].size(), [0, 1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_tensor_size_both_args_bcast(nvfuser_direct_test):\n inputs = [\n torch.randn(1, 3, device=\"cuda\"),\n torch.randn(2, 1, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, [t1.size(0), t0.size(1)], [0, 1])\n t1_b = fd.ops.broadcast_in_dim(t1, [t1.size(0), t0.size(1)], [0, 1])\n t2 = fd.ops.add(t0_b, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_tensor_size_both_args_bcast","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_tensor_size_both_args_bcast#L2011-L2036","kind":"function","name":"test_tensor_size_both_args_bcast","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2011,"end_line":2036,"context_start_line":1991,"context_end_line":2056,"code":" ]\n\n inputs = inputs_1\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = prims.broadcast_in_dim(\n torch.sum(inputs[0], dim=-1), inputs[0].size(), [0, 1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Testing Dynamic usage of same Fusion\n inputs = inputs_2\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, new_fusion_expected=False\n )\n eager_out = prims.broadcast_in_dim(\n torch.sum(inputs[0], dim=-1), inputs[0].size(), [0, 1]\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_tensor_size_both_args_bcast(nvfuser_direct_test):\n inputs = [\n torch.randn(1, 3, device=\"cuda\"),\n torch.randn(2, 1, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, [t1.size(0), t0.size(1)], [0, 1])\n t1_b = fd.ops.broadcast_in_dim(t1, [t1.size(0), t0.size(1)], [0, 1])\n t2 = fd.ops.add(t0_b, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(\n inputs[0], [inputs[1].size()[0], inputs[0].size()[1]], [0, 1]\n ),\n prims.broadcast_in_dim(\n inputs[1], [inputs[1].size()[0], inputs[0].size()[1]], [0, 1]\n ),\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_var_correction(nvfuser_direct_test):\n num_elem = 2\n inputs = [torch.randn(2, num_elem, device=\"cuda\")]\n\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.var(t0, [-1], correction)\n fd.add_output(t1)\n\n return fusion_func\n\n # correction must be less than the reduction factor, which is the input\n # numel divided by output numel.\n for correction in range(num_elem):\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_var_correction","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_var_correction#L2039-L2059","kind":"function","name":"test_var_correction","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2039,"end_line":2059,"context_start_line":2019,"context_end_line":2079,"code":" t1 = fd.from_pytorch(inputs[1])\n\n t0_b = fd.ops.broadcast_in_dim(t0, [t1.size(0), t0.size(1)], [0, 1])\n t1_b = fd.ops.broadcast_in_dim(t1, [t1.size(0), t0.size(1)], [0, 1])\n t2 = fd.ops.add(t0_b, t1_b)\n\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = refs.add(\n prims.broadcast_in_dim(\n inputs[0], [inputs[1].size()[0], inputs[0].size()[1]], [0, 1]\n ),\n prims.broadcast_in_dim(\n inputs[1], [inputs[1].size()[0], inputs[0].size()[1]], [0, 1]\n ),\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_var_correction(nvfuser_direct_test):\n num_elem = 2\n inputs = [torch.randn(2, num_elem, device=\"cuda\")]\n\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.var(t0, [-1], correction)\n fd.add_output(t1)\n\n return fusion_func\n\n # correction must be less than the reduction factor, which is the input\n # numel divided by output numel.\n for correction in range(num_elem):\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs\n )\n torch_result = torch.var(inputs[0], [-1], correction=correction)\n nvfuser_direct_test.assertEqual(fuser_result[0], torch_result)\n\n\ndef test_var_mean_correction(nvfuser_direct_test):\n num_elem = 2\n inputs = [torch.randn(2, num_elem, device=\"cuda\")]\n\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1, t2 = fd.ops.var_mean(t0, [-1], correction)\n fd.add_output(t1)\n fd.add_output(t2)\n\n return fusion_func\n\n # correction must be less than the reduction factor, which is the input\n # numel divided by output numel.\n for correction in range(num_elem):\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_var_mean_correction","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_var_mean_correction#L2062-L2083","kind":"function","name":"test_var_mean_correction","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2062,"end_line":2083,"context_start_line":2042,"context_end_line":2103,"code":"\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.var(t0, [-1], correction)\n fd.add_output(t1)\n\n return fusion_func\n\n # correction must be less than the reduction factor, which is the input\n # numel divided by output numel.\n for correction in range(num_elem):\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs\n )\n torch_result = torch.var(inputs[0], [-1], correction=correction)\n nvfuser_direct_test.assertEqual(fuser_result[0], torch_result)\n\n\ndef test_var_mean_correction(nvfuser_direct_test):\n num_elem = 2\n inputs = [torch.randn(2, num_elem, device=\"cuda\")]\n\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1, t2 = fd.ops.var_mean(t0, [-1], correction)\n fd.add_output(t1)\n fd.add_output(t2)\n\n return fusion_func\n\n # correction must be less than the reduction factor, which is the input\n # numel divided by output numel.\n for correction in range(num_elem):\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs\n )\n torch_result = torch.var_mean(inputs[0], [-1], correction=correction)\n nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_zero_size_dim(nvfuser_direct_test):\n inputs = [\n torch.ones(0, 0, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(\n shape=[0, 0], contiguity=[True, True], dtype=DataType.Float\n )\n t1 = fd.ops.relu(t0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0])\n nvfuser_direct_test.assertEqual(eager_out.numel(), nvf_out[0].numel())\n\n\ndef test_allocation_domain_concretization(nvfuser_direct_test):","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_zero_size_dim","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_zero_size_dim#L2086-L2100","kind":"function","name":"test_zero_size_dim","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2086,"end_line":2100,"context_start_line":2066,"context_end_line":2120,"code":" # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1, t2 = fd.ops.var_mean(t0, [-1], correction)\n fd.add_output(t1)\n fd.add_output(t2)\n\n return fusion_func\n\n # correction must be less than the reduction factor, which is the input\n # numel divided by output numel.\n for correction in range(num_elem):\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs\n )\n torch_result = torch.var_mean(inputs[0], [-1], correction=correction)\n nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_zero_size_dim(nvfuser_direct_test):\n inputs = [\n torch.ones(0, 0, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(\n shape=[0, 0], contiguity=[True, True], dtype=DataType.Float\n )\n t1 = fd.ops.relu(t0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0])\n nvfuser_direct_test.assertEqual(eager_out.numel(), nvf_out[0].numel())\n\n\ndef test_allocation_domain_concretization(nvfuser_direct_test):\n inputs = [\n # we need an empty tensor here so we'll trigger `concretizeEmptyExtents`\n torch.randn((0,), dtype=torch.float64, device=\"cuda:0\").as_strided(\n (1, 0, 1, 1), (0, 1, 1, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[1, -1, 1, 1],\n contiguity=[True, None, None, None],\n dtype=DataType.Double,\n is_cpu=False,\n stride_order=[0, 3, 2, 1],\n )\n S1 = fd.define_scalar(2.0, dtype=DataType.Double)\n T2 = fd.ops.mul(T1, S1)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_allocation_domain_concretization","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_allocation_domain_concretization#L2103-L2125","kind":"function","name":"test_allocation_domain_concretization","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2103,"end_line":2125,"context_start_line":2083,"context_end_line":2145,"code":" nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_zero_size_dim(nvfuser_direct_test):\n inputs = [\n torch.ones(0, 0, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.define_tensor(\n shape=[0, 0], contiguity=[True, True], dtype=DataType.Float\n )\n t1 = fd.ops.relu(t0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0])\n nvfuser_direct_test.assertEqual(eager_out.numel(), nvf_out[0].numel())\n\n\ndef test_allocation_domain_concretization(nvfuser_direct_test):\n inputs = [\n # we need an empty tensor here so we'll trigger `concretizeEmptyExtents`\n torch.randn((0,), dtype=torch.float64, device=\"cuda:0\").as_strided(\n (1, 0, 1, 1), (0, 1, 1, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[1, -1, 1, 1],\n contiguity=[True, None, None, None],\n dtype=DataType.Double,\n is_cpu=False,\n stride_order=[0, 3, 2, 1],\n )\n S1 = fd.define_scalar(2.0, dtype=DataType.Double)\n T2 = fd.ops.mul(T1, S1)\n fd.add_output(T2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = inputs[0] * 2.0\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_allocation_domain_index_select(nvfuser_direct_test):\n inputs = [\n torch.randn((252,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (9, 28), (1, 9)\n ),\n torch.randint(0, 28, (4,), dtype=torch.int64, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0, 1],\n )\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Int, is_cpu=False","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_allocation_domain_index_select","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_allocation_domain_index_select#L2128-L2152","kind":"function","name":"test_allocation_domain_index_select","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2128,"end_line":2152,"context_start_line":2108,"context_end_line":2172,"code":" ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[1, -1, 1, 1],\n contiguity=[True, None, None, None],\n dtype=DataType.Double,\n is_cpu=False,\n stride_order=[0, 3, 2, 1],\n )\n S1 = fd.define_scalar(2.0, dtype=DataType.Double)\n T2 = fd.ops.mul(T1, S1)\n fd.add_output(T2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = inputs[0] * 2.0\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_allocation_domain_index_select(nvfuser_direct_test):\n inputs = [\n torch.randn((252,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (9, 28), (1, 9)\n ),\n torch.randint(0, 28, (4,), dtype=torch.int64, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0, 1],\n )\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Int, is_cpu=False\n )\n T3 = fd.ops.index_select(T1, T2, dim=1)\n fd.add_output(T3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = torch.index_select(inputs[0], 1, inputs[1])\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_expand_to_zero(nvfuser_direct_test):\n inputs = [\n # This is an actually empty tensor\n torch.zeros((1, 0), dtype=torch.float32, device=\"cuda:0\"),\n # This one is not actually empty, but should appear to be empty due to expand\n torch.zeros((1, 1), dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.broadcast_in_dim(T0, shape=[0, 0], broadcast_dims=[0, 1])\n T3 = fd.ops.broadcast_in_dim(T1, shape=[0, 0], broadcast_dims=[0, 1])\n fd.add_output(T2)\n fd.add_output(T3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_expand_to_zero","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_expand_to_zero#L2155-L2174","kind":"function","name":"test_expand_to_zero","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2155,"end_line":2174,"context_start_line":2135,"context_end_line":2194,"code":"\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0, 1],\n )\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Int, is_cpu=False\n )\n T3 = fd.ops.index_select(T1, T2, dim=1)\n fd.add_output(T3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = torch.index_select(inputs[0], 1, inputs[1])\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_expand_to_zero(nvfuser_direct_test):\n inputs = [\n # This is an actually empty tensor\n torch.zeros((1, 0), dtype=torch.float32, device=\"cuda:0\"),\n # This one is not actually empty, but should appear to be empty due to expand\n torch.zeros((1, 1), dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.broadcast_in_dim(T0, shape=[0, 0], broadcast_dims=[0, 1])\n T3 = fd.ops.broadcast_in_dim(T1, shape=[0, 0], broadcast_dims=[0, 1])\n fd.add_output(T2)\n fd.add_output(T3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(nvf_out[0].shape, (0, 0))\n nvfuser_direct_test.assertEqual(nvf_out[1].shape, (0, 0))\n\n\ndef test_expanded_bcast_tensor(nvfuser_direct_test):\n inputs = [\n torch.tensor(1.5, device=\"cuda\"),\n torch.randn(5, 5, 5, device=\"cuda\"),\n torch.randint(0, 1, (5, 5), device=\"cuda\").bool().unsqueeze(-1).expand(5, 5, 5),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.from_pytorch(inputs[2])\n T3 = fd.ops.add(T0, T1)\n T4 = fd.ops.add(T2, T3)\n fd.add_output(T4)\n\n eager_out = inputs[0] + inputs[1] + inputs[2]\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_expanded_bcast_tensor","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_expanded_bcast_tensor#L2177-L2195","kind":"function","name":"test_expanded_bcast_tensor","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2177,"end_line":2195,"context_start_line":2157,"context_end_line":2215,"code":" # This is an actually empty tensor\n torch.zeros((1, 0), dtype=torch.float32, device=\"cuda:0\"),\n # This one is not actually empty, but should appear to be empty due to expand\n torch.zeros((1, 1), dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.broadcast_in_dim(T0, shape=[0, 0], broadcast_dims=[0, 1])\n T3 = fd.ops.broadcast_in_dim(T1, shape=[0, 0], broadcast_dims=[0, 1])\n fd.add_output(T2)\n fd.add_output(T3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(nvf_out[0].shape, (0, 0))\n nvfuser_direct_test.assertEqual(nvf_out[1].shape, (0, 0))\n\n\ndef test_expanded_bcast_tensor(nvfuser_direct_test):\n inputs = [\n torch.tensor(1.5, device=\"cuda\"),\n torch.randn(5, 5, 5, device=\"cuda\"),\n torch.randint(0, 1, (5, 5), device=\"cuda\").bool().unsqueeze(-1).expand(5, 5, 5),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.from_pytorch(inputs[2])\n T3 = fd.ops.add(T0, T1)\n T4 = fd.ops.add(T2, T3)\n fd.add_output(T4)\n\n eager_out = inputs[0] + inputs[1] + inputs[2]\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_inplace_update_on_non_contiguous_inputs(nvfuser_direct_test):\n inputs = [\n torch.randn(5, dtype=torch.float32, device=\"cuda:0\").as_strided((2, 2), (1, 3)),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2, 2],\n contiguity=[False, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0, 1],\n )\n S1 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T2 = fd.ops.gt(T0, S1)\n S3 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T4 = fd.ops.where(T2, T0, S3)\n T5 = fd.ops.cast(T4, dtype=DataType.Float)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_inplace_update_on_non_contiguous_inputs","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_inplace_update_on_non_contiguous_inputs#L2198-L2228","kind":"function","name":"test_inplace_update_on_non_contiguous_inputs","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2198,"end_line":2228,"context_start_line":2178,"context_end_line":2248,"code":" inputs = [\n torch.tensor(1.5, device=\"cuda\"),\n torch.randn(5, 5, 5, device=\"cuda\"),\n torch.randint(0, 1, (5, 5), device=\"cuda\").bool().unsqueeze(-1).expand(5, 5, 5),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.from_pytorch(inputs[2])\n T3 = fd.ops.add(T0, T1)\n T4 = fd.ops.add(T2, T3)\n fd.add_output(T4)\n\n eager_out = inputs[0] + inputs[1] + inputs[2]\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_inplace_update_on_non_contiguous_inputs(nvfuser_direct_test):\n inputs = [\n torch.randn(5, dtype=torch.float32, device=\"cuda:0\").as_strided((2, 2), (1, 3)),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2, 2],\n contiguity=[False, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0, 1],\n )\n S1 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T2 = fd.ops.gt(T0, S1)\n S3 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T4 = fd.ops.where(T2, T0, S3)\n T5 = fd.ops.cast(T4, dtype=DataType.Float)\n T6 = fd.ops.set(T5)\n fd.add_output(T6, T0)\n fd.add_output(T6)\n\n ref_inp = inputs[0].clone()\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func,\n inputs,\n )\n\n assert len(nvf_out) == 1\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0])\n nvfuser_direct_test.assertEqual(nvf_out[0], ref_inp.relu())\n\n\ndef test_pad_expanded_empty(nvfuser_direct_test):\n inputs = [\n torch.randn((0,), dtype=torch.float64, device=\"cuda:0\").as_strided(\n (2, 0, 3), (0, 0, 0)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n S1 = fd.define_scalar(-3.70753, dtype=DataType.Double)\n T2 = fd.ops.pad(T0, [0, 0, 1, 1, 1, 0], S1)\n fd.add_output(T2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n torch_ref = torch.nn.functional.pad(\n inputs[0], (0, 0, 1, 1, 1, 0), \"constant\", -3.70753\n )","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_pad_expanded_empty","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_pad_expanded_empty#L2231-L2250","kind":"function","name":"test_pad_expanded_empty","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2231,"end_line":2250,"context_start_line":2211,"context_end_line":2270,"code":" S1 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T2 = fd.ops.gt(T0, S1)\n S3 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T4 = fd.ops.where(T2, T0, S3)\n T5 = fd.ops.cast(T4, dtype=DataType.Float)\n T6 = fd.ops.set(T5)\n fd.add_output(T6, T0)\n fd.add_output(T6)\n\n ref_inp = inputs[0].clone()\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func,\n inputs,\n )\n\n assert len(nvf_out) == 1\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0])\n nvfuser_direct_test.assertEqual(nvf_out[0], ref_inp.relu())\n\n\ndef test_pad_expanded_empty(nvfuser_direct_test):\n inputs = [\n torch.randn((0,), dtype=torch.float64, device=\"cuda:0\").as_strided(\n (2, 0, 3), (0, 0, 0)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n S1 = fd.define_scalar(-3.70753, dtype=DataType.Double)\n T2 = fd.ops.pad(T0, [0, 0, 1, 1, 1, 0], S1)\n fd.add_output(T2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n torch_ref = torch.nn.functional.pad(\n inputs[0], (0, 0, 1, 1, 1, 0), \"constant\", -3.70753\n )\n\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_pad_prior_cat(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(3, 3, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n # pad tensors t0 and t1, so their first dimension are size 10.\n t0_pad = fd.ops.pad(t0, [0, 0, 0, 8])\n t1_pad = fd.ops.pad(t1, [0, 0, 0, 7])\n\n t3 = fd.ops.cat([t0_pad, t1_pad], 1)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_pad_prior_cat","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_pad_prior_cat#L2253-L2277","kind":"function","name":"test_pad_prior_cat","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2253,"end_line":2277,"context_start_line":2233,"context_end_line":2297,"code":" torch.randn((0,), dtype=torch.float64, device=\"cuda:0\").as_strided(\n (2, 0, 3), (0, 0, 0)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n S1 = fd.define_scalar(-3.70753, dtype=DataType.Double)\n T2 = fd.ops.pad(T0, [0, 0, 1, 1, 1, 0], S1)\n fd.add_output(T2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n torch_ref = torch.nn.functional.pad(\n inputs[0], (0, 0, 1, 1, 1, 0), \"constant\", -3.70753\n )\n\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_pad_prior_cat(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(3, 3, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n # pad tensors t0 and t1, so their first dimension are size 10.\n t0_pad = fd.ops.pad(t0, [0, 0, 0, 8])\n t1_pad = fd.ops.pad(t1, [0, 0, 0, 7])\n\n t3 = fd.ops.cat([t0_pad, t1_pad], 1)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n # pad tensors t0 and t1, so their first dimension are size 10.\n pad_input0 = torch.nn.functional.pad(inputs[0], [0, 0, 0, 8])\n pad_input1 = torch.nn.functional.pad(inputs[1], [0, 0, 0, 7])\n nvfuser_direct_test.assertEqual(\n torch.cat([pad_input0, pad_input1], dim=1), nvf_out[0]\n )\n\n\ndef test_replaced_sizes_pr2714(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.exp(T0)\n T3 = fd.ops.tanh(T1)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_replaced_sizes_pr2714","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_replaced_sizes_pr2714#L2280-L2321","kind":"function","name":"test_replaced_sizes_pr2714","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2280,"end_line":2321,"context_start_line":2260,"context_end_line":2341,"code":" t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n # pad tensors t0 and t1, so their first dimension are size 10.\n t0_pad = fd.ops.pad(t0, [0, 0, 0, 8])\n t1_pad = fd.ops.pad(t1, [0, 0, 0, 7])\n\n t3 = fd.ops.cat([t0_pad, t1_pad], 1)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n # pad tensors t0 and t1, so their first dimension are size 10.\n pad_input0 = torch.nn.functional.pad(inputs[0], [0, 0, 0, 8])\n pad_input1 = torch.nn.functional.pad(inputs[1], [0, 0, 0, 7])\n nvfuser_direct_test.assertEqual(\n torch.cat([pad_input0, pad_input1], dim=1), nvf_out[0]\n )\n\n\ndef test_replaced_sizes_pr2714(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.exp(T0)\n T3 = fd.ops.tanh(T1)\n S4 = fd.define_scalar(4, dtype=DataType.Int)\n T6 = fd.ops.reshape(T2, new_shape=[S4])\n S7 = fd.define_scalar(4, dtype=DataType.Int)\n T9 = fd.ops.reshape(T3, new_shape=[S7])\n T10 = fd.ops.add(T6, T9)\n T11 = fd.ops.reciprocal(T0)\n T12 = fd.ops.mul(T3, T11)\n S13 = fd.define_scalar(2.00000, dtype=DataType.Double)\n S14 = fd.ops.reciprocal(S13)\n T15 = fd.ops.mul(T10, S14)\n fd.add_output(T10)\n fd.add_output(T12)\n fd.add_output(T15)\n\n inputs = [\n torch.randn((4,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 2), (2, 1)\n ),\n torch.randn((4,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 2), (2, 1)\n ),\n ]\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_reshape_squeeze_concretization(nvfuser_direct_test):\n inputs = [\n torch.randn((100,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 5, 10), (50, 10, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[1, 2, 4], strides=[1, 1, 1]\n )","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_reshape_squeeze_concretization","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_reshape_squeeze_concretization#L2324-L2348","kind":"function","name":"test_reshape_squeeze_concretization","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2324,"end_line":2348,"context_start_line":2304,"context_end_line":2368,"code":" T12 = fd.ops.mul(T3, T11)\n S13 = fd.define_scalar(2.00000, dtype=DataType.Double)\n S14 = fd.ops.reciprocal(S13)\n T15 = fd.ops.mul(T10, S14)\n fd.add_output(T10)\n fd.add_output(T12)\n fd.add_output(T15)\n\n inputs = [\n torch.randn((4,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 2), (2, 1)\n ),\n torch.randn((4,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 2), (2, 1)\n ),\n ]\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_reshape_squeeze_concretization(nvfuser_direct_test):\n inputs = [\n torch.randn((100,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 5, 10), (50, 10, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[1, 2, 4], strides=[1, 1, 1]\n )\n S2 = fd.define_scalar(1, dtype=DataType.Int)\n S3 = fd.define_scalar(8, dtype=DataType.Int)\n T6 = fd.ops.reshape(T1, new_shape=[S2, S3])\n T7 = fd.ops.reshape(T6, new_shape=[S3])\n fd.add_output(T7)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_sum_sliced_reshape_to_broadcast(nvfuser_direct_test):\n inputs = [torch.randn((24, 128, 25, 32), dtype=torch.float32, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T18 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S91 = fd.define_scalar(12, dtype=DataType.Int)\n S92 = fd.define_scalar(128, dtype=DataType.Int)\n S93 = fd.define_scalar(25, dtype=DataType.Int)\n S94 = fd.define_scalar(32, dtype=DataType.Int)\n S95 = fd.define_scalar(2, dtype=DataType.Int)\n T97 = fd.ops.reshape(T18, new_shape=[S91, S92, S93, S94, S95])\n T98 = fd.ops.slice(\n T97,","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_sum_sliced_reshape_to_broadcast","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_sum_sliced_reshape_to_broadcast#L2351-L2386","kind":"function","name":"test_sum_sliced_reshape_to_broadcast","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2351,"end_line":2386,"context_start_line":2331,"context_end_line":2406,"code":" def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[1, 2, 4], strides=[1, 1, 1]\n )\n S2 = fd.define_scalar(1, dtype=DataType.Int)\n S3 = fd.define_scalar(8, dtype=DataType.Int)\n T6 = fd.ops.reshape(T1, new_shape=[S2, S3])\n T7 = fd.ops.reshape(T6, new_shape=[S3])\n fd.add_output(T7)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_sum_sliced_reshape_to_broadcast(nvfuser_direct_test):\n inputs = [torch.randn((24, 128, 25, 32), dtype=torch.float32, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T18 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S91 = fd.define_scalar(12, dtype=DataType.Int)\n S92 = fd.define_scalar(128, dtype=DataType.Int)\n S93 = fd.define_scalar(25, dtype=DataType.Int)\n S94 = fd.define_scalar(32, dtype=DataType.Int)\n S95 = fd.define_scalar(2, dtype=DataType.Int)\n T97 = fd.ops.reshape(T18, new_shape=[S91, S92, S93, S94, S95])\n T98 = fd.ops.slice(\n T97,\n start_indices=[0, 0, 0, 0, 0],\n end_indices=[12, 128, 25, 32, 1],\n strides=[1, 1, 1, 1, 1],\n )\n T89 = fd.ops.sum(T98, dims=[4], keepdim=False, dtype=DataType.Null)\n fd.add_output(T89)\n\n # Check that define_scalar is not used in fd_str\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1, -1, -1], contiguity=[True, True, True, True], dtype=DataType.Float, is_cpu=False)\n tv1 = fd.ops.reshape(tv0, new_shape=[12, 128, 25, 32, 2])\n tv2 = fd.ops.slice(tv1, start_indices=[0, 0, 0, 0, 0], end_indices=[12, 128, 25, 32, 1], strides=[1, 1, 1, 1, 1], manual_normalization=True)\n tv3 = fd.ops.squeeze(tv2, dims=[4])\n fd.add_output(tv3)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n\n\n# See https://github.com/NVIDIA/Fuser/issues/3833\ndef test_bcast_squeeze_replace_aliased_output(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor((1, 1, 576), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 576), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, 1, 576],\n contiguity=[None, None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 576],\n contiguity=[None, True],","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_bcast_squeeze_replace_aliased_output","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_bcast_squeeze_replace_aliased_output#L2390-L2419","kind":"function","name":"test_bcast_squeeze_replace_aliased_output","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2390,"end_line":2419,"context_start_line":2370,"context_end_line":2439,"code":" end_indices=[12, 128, 25, 32, 1],\n strides=[1, 1, 1, 1, 1],\n )\n T89 = fd.ops.sum(T98, dims=[4], keepdim=False, dtype=DataType.Null)\n fd.add_output(T89)\n\n # Check that define_scalar is not used in fd_str\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1, -1, -1], contiguity=[True, True, True, True], dtype=DataType.Float, is_cpu=False)\n tv1 = fd.ops.reshape(tv0, new_shape=[12, 128, 25, 32, 2])\n tv2 = fd.ops.slice(tv1, start_indices=[0, 0, 0, 0, 0], end_indices=[12, 128, 25, 32, 1], strides=[1, 1, 1, 1, 1], manual_normalization=True)\n tv3 = fd.ops.squeeze(tv2, dims=[4])\n fd.add_output(tv3)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n\n\n# See https://github.com/NVIDIA/Fuser/issues/3833\ndef test_bcast_squeeze_replace_aliased_output(nvfuser_direct_test):\n inputs = [\n torch.testing.make_tensor((1, 1, 576), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 576), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, 1, 576],\n contiguity=[None, None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 576],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T5 = fd.ops.reshape(T0, new_shape=[1, 576])\n T6 = fd.ops.set(T5)\n fd.add_output(T6, T1)\n fd.add_output(T5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n assert len(nvf_out) == 1\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0].squeeze(1))\n\n\ndef test_broadcast_and_stride_order(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 3, 4, dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n # Direct bindings does not support `add_output` with stride_order argument.\n # Instead, we use `stride_order` operation to set the stride order before\n # adding the output.\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.broadcast(T0, is_broadcast_dim=[False, True, False, False])\n T2 = fd.ops.stride_order(T1, stride_order=[0, 1, 2, 3])\n fd.add_output(T2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0].unsqueeze(1))\n nvfuser_direct_test.assertEqual(nvf_out[0].stride(), (1, 2, 2, 6))","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_broadcast_and_stride_order","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_broadcast_and_stride_order#L2422-L2439","kind":"function","name":"test_broadcast_and_stride_order","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2422,"end_line":2439,"context_start_line":2402,"context_end_line":2459,"code":" stride_order=[2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 576],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T5 = fd.ops.reshape(T0, new_shape=[1, 576])\n T6 = fd.ops.set(T5)\n fd.add_output(T6, T1)\n fd.add_output(T5)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n assert len(nvf_out) == 1\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0].squeeze(1))\n\n\ndef test_broadcast_and_stride_order(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 3, 4, dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n # Direct bindings does not support `add_output` with stride_order argument.\n # Instead, we use `stride_order` operation to set the stride order before\n # adding the output.\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.broadcast(T0, is_broadcast_dim=[False, True, False, False])\n T2 = fd.ops.stride_order(T1, stride_order=[0, 1, 2, 3])\n fd.add_output(T2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0].unsqueeze(1))\n nvfuser_direct_test.assertEqual(nvf_out[0].stride(), (1, 2, 2, 6))\n\n\ndef test_right_shift_logical(nvfuser_direct_test):\n dtypes = [torch.int32, torch.int64]\n input = torch.tensor(\n [\n -1,\n -2147483648,\n 1073741824,\n -64463884,\n -65968277,\n 4042311,\n -98914167,\n 5526216,\n ],\n device=\"cuda\",\n )\n\n # expected_outputs given by jax.lax.shift_right_logical(inputs, 3)\n expected_outputs = [","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_right_shift_logical","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_right_shift_logical#L2442-L2500","kind":"function","name":"test_right_shift_logical","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2442,"end_line":2500,"context_start_line":2422,"context_end_line":2520,"code":"def test_broadcast_and_stride_order(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 3, 4, dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n # Direct bindings does not support `add_output` with stride_order argument.\n # Instead, we use `stride_order` operation to set the stride order before\n # adding the output.\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.broadcast(T0, is_broadcast_dim=[False, True, False, False])\n T2 = fd.ops.stride_order(T1, stride_order=[0, 1, 2, 3])\n fd.add_output(T2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0].unsqueeze(1))\n nvfuser_direct_test.assertEqual(nvf_out[0].stride(), (1, 2, 2, 6))\n\n\ndef test_right_shift_logical(nvfuser_direct_test):\n dtypes = [torch.int32, torch.int64]\n input = torch.tensor(\n [\n -1,\n -2147483648,\n 1073741824,\n -64463884,\n -65968277,\n 4042311,\n -98914167,\n 5526216,\n ],\n device=\"cuda\",\n )\n\n # expected_outputs given by jax.lax.shift_right_logical(inputs, 3)\n expected_outputs = [\n torch.tensor(\n [\n 536870911,\n 268435456,\n 134217728,\n 528812926,\n 528624877,\n 505288,\n 524506641,\n 690777,\n ],\n dtype=torch.int32,\n device=\"cuda\",\n ),\n torch.tensor(\n [\n 2305843009213693951,\n 2305843008945258496,\n 134217728,\n 2305843009205635966,\n 2305843009205447917,\n 505288,\n 2305843009201329681,\n 690777,\n ],\n dtype=torch.int64,\n device=\"cuda\",\n ),\n ]\n\n for idx, dtype in enumerate(dtypes):\n current_input = input.to(dtype)\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(current_input)\n c0 = fd.define_scalar(3)\n t1 = fd.ops.logical_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [current_input])\n nvfuser_direct_test.assertEqual(nvf_out[0], expected_outputs[idx])\n\n\ndef test_right_shift_logical_sizeof_dtype(nvfuser_direct_test):\n dtypes = [torch.int32, torch.int64]\n input = torch.tensor(\n [\n -1,\n -2147483648,\n 1073741824,\n -64463884,\n -65968277,\n 4042311,\n -98914167,\n 5526216,\n ],\n device=\"cuda\",\n )\n\n for idx, dtype in enumerate(dtypes):\n current_input = input.to(dtype)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_right_shift_logical_sizeof_dtype","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_right_shift_logical_sizeof_dtype#L2503-L2539","kind":"function","name":"test_right_shift_logical_sizeof_dtype","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2503,"end_line":2539,"context_start_line":2483,"context_end_line":2559,"code":" 690777,\n ],\n dtype=torch.int64,\n device=\"cuda\",\n ),\n ]\n\n for idx, dtype in enumerate(dtypes):\n current_input = input.to(dtype)\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(current_input)\n c0 = fd.define_scalar(3)\n t1 = fd.ops.logical_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [current_input])\n nvfuser_direct_test.assertEqual(nvf_out[0], expected_outputs[idx])\n\n\ndef test_right_shift_logical_sizeof_dtype(nvfuser_direct_test):\n dtypes = [torch.int32, torch.int64]\n input = torch.tensor(\n [\n -1,\n -2147483648,\n 1073741824,\n -64463884,\n -65968277,\n 4042311,\n -98914167,\n 5526216,\n ],\n device=\"cuda\",\n )\n\n for idx, dtype in enumerate(dtypes):\n current_input = input.to(dtype)\n num_bits = 32 if (dtype == torch.int32) else 64\n\n # expected_outputs given by jax.lax.shift_right_logical(inputs, sizeof(dtype))\n # >>> jax.lax.shift_right_logical(input.to('cpu').numpy(), 32)\n # Array([0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)\n # >>> jax.lax.shift_right_logical(input.to('cpu').numpy(), 64)\n # Array([0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)\n expected_output = torch.zeros_like(current_input)\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(current_input)\n c0 = fd.define_scalar(None, dtype=DataType.Int)\n t1 = fd.ops.logical_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, [current_input, num_bits]\n )\n nvfuser_direct_test.assertEqual(nvf_out[0], expected_output)\n\n\ndef test_all_dim_var_mean(nvfuser_direct_test):\n inputs = [torch.randn(2, 2, 2, device=\"cuda\")]\n\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1, t2 = fd.ops.var_mean(t0, [0, 1, 2], correction)\n fd.add_output(t1)\n fd.add_output(t2)\n\n return fusion_func\n\n list_of_test_cases = [0, 1]\n for correction in list_of_test_cases:\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs\n )","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_all_dim_var_mean","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_all_dim_var_mean#L2542-L2561","kind":"function","name":"test_all_dim_var_mean","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2542,"end_line":2561,"context_start_line":2522,"context_end_line":2581,"code":"\n # expected_outputs given by jax.lax.shift_right_logical(inputs, sizeof(dtype))\n # >>> jax.lax.shift_right_logical(input.to('cpu').numpy(), 32)\n # Array([0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)\n # >>> jax.lax.shift_right_logical(input.to('cpu').numpy(), 64)\n # Array([0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)\n expected_output = torch.zeros_like(current_input)\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(current_input)\n c0 = fd.define_scalar(None, dtype=DataType.Int)\n t1 = fd.ops.logical_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, [current_input, num_bits]\n )\n nvfuser_direct_test.assertEqual(nvf_out[0], expected_output)\n\n\ndef test_all_dim_var_mean(nvfuser_direct_test):\n inputs = [torch.randn(2, 2, 2, device=\"cuda\")]\n\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1, t2 = fd.ops.var_mean(t0, [0, 1, 2], correction)\n fd.add_output(t1)\n fd.add_output(t2)\n\n return fusion_func\n\n list_of_test_cases = [0, 1]\n for correction in list_of_test_cases:\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs\n )\n torch_result = torch.var_mean(inputs[0], [0, 1, 2], bool(correction))\n nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_validate_precomputed_values(nvfuser_direct_test):\n # This test is from legacy test_nan.py\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n\n S1 = fd.define_scalar(None, dtype=DataType.Double)\n T2 = fd.ops.ge(T0, S1)\n fd.add_output(T2)\n\n outs, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func,\n [\n torch.randn((10,), dtype=torch.float32, device=\"cuda:0\").as_strided(","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_validate_precomputed_values","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_validate_precomputed_values#L2564-L2588","kind":"function","name":"test_validate_precomputed_values","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2564,"end_line":2588,"context_start_line":2544,"context_end_line":2608,"code":"\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1, t2 = fd.ops.var_mean(t0, [0, 1, 2], correction)\n fd.add_output(t1)\n fd.add_output(t2)\n\n return fusion_func\n\n list_of_test_cases = [0, 1]\n for correction in list_of_test_cases:\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs\n )\n torch_result = torch.var_mean(inputs[0], [0, 1, 2], bool(correction))\n nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_validate_precomputed_values(nvfuser_direct_test):\n # This test is from legacy test_nan.py\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n\n S1 = fd.define_scalar(None, dtype=DataType.Double)\n T2 = fd.ops.ge(T0, S1)\n fd.add_output(T2)\n\n outs, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func,\n [\n torch.randn((10,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 5), (5, 1)\n ),\n float(\"nan\"),\n ],\n )\n # Comparing any number to NaN results in False.\n torch.testing.assert_close(outs[0].cpu(), torch.full((2, 5), False))\n\n\ndef test_cpu_add(nvfuser_direct_test):\n \"\"\"\n Tests that CPU scalar tensor can be instantiated using fd.from_pytorch\n\n Migrated from `test_cpu_add` in legacy test_pointwise.py\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n torch.randn(3, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s0 = fd.from_pytorch(inputs[1])\n t1 = fd.ops.add(t0, s0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_cpu_add","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_cpu_add#L2591-L2609","kind":"function","name":"test_cpu_add","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2591,"end_line":2609,"context_start_line":2571,"context_end_line":2629,"code":" is_cpu=False,\n )\n\n S1 = fd.define_scalar(None, dtype=DataType.Double)\n T2 = fd.ops.ge(T0, S1)\n fd.add_output(T2)\n\n outs, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func,\n [\n torch.randn((10,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 5), (5, 1)\n ),\n float(\"nan\"),\n ],\n )\n # Comparing any number to NaN results in False.\n torch.testing.assert_close(outs[0].cpu(), torch.full((2, 5), False))\n\n\ndef test_cpu_add(nvfuser_direct_test):\n \"\"\"\n Tests that CPU scalar tensor can be instantiated using fd.from_pytorch\n\n Migrated from `test_cpu_add` in legacy test_pointwise.py\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n torch.randn(3, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s0 = fd.from_pytorch(inputs[1])\n t1 = fd.ops.add(t0, s0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0] + inputs[1])\n\n\ndef test_full_with_cpu_inputs(nvfuser_direct_test):\n \"\"\"\n This example contains CPU scalar only fusion inputs.\n The `full` op does not take any fusion inputs but generates a\n CUDA tensor. This is a nvFuser supported fusion since the final\n output is a CUDA tensor.\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0])\n s0 = fd.define_scalar(3.0)\n tv1 = fd.ops.full(shape=[2, 2], fill_value=s0, dtype=DataType.Float)\n t2 = fd.ops.mul(tv0, tv1) # CPU scalar * CUDA tensor = CUDA tensor\n fd.add_output(t2)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_full_with_cpu_inputs","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_full_with_cpu_inputs#L2612-L2631","kind":"function","name":"test_full_with_cpu_inputs","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2612,"end_line":2631,"context_start_line":2592,"context_end_line":2651,"code":" \"\"\"\n Tests that CPU scalar tensor can be instantiated using fd.from_pytorch\n\n Migrated from `test_cpu_add` in legacy test_pointwise.py\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n torch.randn(3, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n s0 = fd.from_pytorch(inputs[1])\n t1 = fd.ops.add(t0, s0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0] + inputs[1])\n\n\ndef test_full_with_cpu_inputs(nvfuser_direct_test):\n \"\"\"\n This example contains CPU scalar only fusion inputs.\n The `full` op does not take any fusion inputs but generates a\n CUDA tensor. This is a nvFuser supported fusion since the final\n output is a CUDA tensor.\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0])\n s0 = fd.define_scalar(3.0)\n tv1 = fd.ops.full(shape=[2, 2], fill_value=s0, dtype=DataType.Float)\n t2 = fd.ops.mul(tv0, tv1) # CPU scalar * CUDA tensor = CUDA tensor\n fd.add_output(t2)\n\n # fd.validate expects inputs and outputs to be on CUDA device\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_input_forwarding_device(nvfuser_direct_test):\n \"\"\"\n If fusion segment do not consist of any exprs, no kernel is\n launched and the output is on the correct device.\n \"\"\"\n inputs = [torch.tensor(2.0, device=\"cpu\", dtype=torch.float)]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0])\n fd.add_output(tv0)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n assert out[0].is_cpu\n\n\ndef test_single_segment_multi_device():\n \"\"\"\n Test single segment with CPU and CUDA outputs","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_input_forwarding_device","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_input_forwarding_device#L2634-L2646","kind":"function","name":"test_input_forwarding_device","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2634,"end_line":2646,"context_start_line":2614,"context_end_line":2666,"code":" This example contains CPU scalar only fusion inputs.\n The `full` op does not take any fusion inputs but generates a\n CUDA tensor. This is a nvFuser supported fusion since the final\n output is a CUDA tensor.\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0])\n s0 = fd.define_scalar(3.0)\n tv1 = fd.ops.full(shape=[2, 2], fill_value=s0, dtype=DataType.Float)\n t2 = fd.ops.mul(tv0, tv1) # CPU scalar * CUDA tensor = CUDA tensor\n fd.add_output(t2)\n\n # fd.validate expects inputs and outputs to be on CUDA device\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_input_forwarding_device(nvfuser_direct_test):\n \"\"\"\n If fusion segment do not consist of any exprs, no kernel is\n launched and the output is on the correct device.\n \"\"\"\n inputs = [torch.tensor(2.0, device=\"cpu\", dtype=torch.float)]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0])\n fd.add_output(tv0)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n assert out[0].is_cpu\n\n\ndef test_single_segment_multi_device():\n \"\"\"\n Test single segment with CPU and CUDA outputs\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n torch.tensor(3.0, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0])\n s0 = fd.define_scalar(3.0)\n tv1 = fd.ops.add(tv0, s0)\n tv2 = fd.from_pytorch(inputs[1])\n tv3 = fd.ops.add(tv1, tv2)\n fd.add_output(tv1)\n fd.add_output(tv2)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_single_segment_multi_device","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_single_segment_multi_device#L2649-L2673","kind":"function","name":"test_single_segment_multi_device","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2649,"end_line":2673,"context_start_line":2629,"context_end_line":2693,"code":"\n # fd.validate expects inputs and outputs to be on CUDA device\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_input_forwarding_device(nvfuser_direct_test):\n \"\"\"\n If fusion segment do not consist of any exprs, no kernel is\n launched and the output is on the correct device.\n \"\"\"\n inputs = [torch.tensor(2.0, device=\"cpu\", dtype=torch.float)]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0])\n fd.add_output(tv0)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n assert out[0].is_cpu\n\n\ndef test_single_segment_multi_device():\n \"\"\"\n Test single segment with CPU and CUDA outputs\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n torch.tensor(3.0, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0])\n s0 = fd.define_scalar(3.0)\n tv1 = fd.ops.add(tv0, s0)\n tv2 = fd.from_pytorch(inputs[1])\n tv3 = fd.ops.add(tv1, tv2)\n fd.add_output(tv1)\n fd.add_output(tv2)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n with pytest.raises(\n RuntimeError, match=\"KernelExecutor does not support the Fusion provided.\"\n ):\n _ = fd.execute(inputs)\n\n\n# Test that we properly handle packed type\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\ndef test_packed_fp4(nvfuser_direct_test):\n t0 = torch.rand(\n (\n 1024,\n 32,\n ),\n dtype=torch.float32,\n device=\"cuda:0\",\n )\n # we'll just ignore the scaling factor, since we only want to test basic fp4 support\n t0_fp4, _ = pytorch_nvfp4_quantize(t0, 1.0)\n inputs = [t0_fp4]\n\n def fusion_func(fd: FusionDefinition):","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_packed_fp4","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_packed_fp4#L2680-L2706","kind":"function","name":"test_packed_fp4","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2680,"end_line":2706,"context_start_line":2660,"context_end_line":2726,"code":" s0 = fd.define_scalar(3.0)\n tv1 = fd.ops.add(tv0, s0)\n tv2 = fd.from_pytorch(inputs[1])\n tv3 = fd.ops.add(tv1, tv2)\n fd.add_output(tv1)\n fd.add_output(tv2)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n with pytest.raises(\n RuntimeError, match=\"KernelExecutor does not support the Fusion provided.\"\n ):\n _ = fd.execute(inputs)\n\n\n# Test that we properly handle packed type\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\ndef test_packed_fp4(nvfuser_direct_test):\n t0 = torch.rand(\n (\n 1024,\n 32,\n ),\n dtype=torch.float32,\n device=\"cuda:0\",\n )\n # we'll just ignore the scaling factor, since we only want to test basic fp4 support\n t0_fp4, _ = pytorch_nvfp4_quantize(t0, 1.0)\n inputs = [t0_fp4]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[1024, 16],\n contiguity=[True, True],\n dtype=DataType.Float4_e2m1fn_x2,\n is_cpu=False,\n )\n T1 = fd.ops.cast(T0, DataType.Float)\n T2 = fd.ops.relu(T1)\n fd.add_output(T2)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n ref = fp4_to_fp32(unpack_fp4(t0_fp4.view(torch.uint8))).relu()\n nvfuser_direct_test.assertEqual(out[0], ref)\n\n\ndef test_broadcast_in_dim_no_redundant_set(nvfuser_direct_test):\n \"\"\"\n Test that broadcast_in_dim doesn't introduce redundant Set operations\n when all input dimensions are in broadcast_dims (i.e., no actual broadcast).\n\n This verifies the fix for the issue where broadcast_in_dim would create\n a redundant float-to-float cast operation via Set when the input already\n had the correct shape.\n \"\"\"\n\n def fusion_with_broadcast_in_dim(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[1, -1], contiguity=[None, True])\n t1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n # broadcast_in_dim with broadcast_dims=[0, 1] means no new dims are added\n t2 = fd.ops.broadcast_in_dim(t0, t1.shape(), [0, 1])\n t3 = fd.ops.add(t2, t1)\n fd.add_output(t3)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_broadcast_in_dim_no_redundant_set","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_broadcast_in_dim_no_redundant_set#L2709-L2744","kind":"function","name":"test_broadcast_in_dim_no_redundant_set","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2709,"end_line":2744,"context_start_line":2689,"context_end_line":2764,"code":" # we'll just ignore the scaling factor, since we only want to test basic fp4 support\n t0_fp4, _ = pytorch_nvfp4_quantize(t0, 1.0)\n inputs = [t0_fp4]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[1024, 16],\n contiguity=[True, True],\n dtype=DataType.Float4_e2m1fn_x2,\n is_cpu=False,\n )\n T1 = fd.ops.cast(T0, DataType.Float)\n T2 = fd.ops.relu(T1)\n fd.add_output(T2)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n ref = fp4_to_fp32(unpack_fp4(t0_fp4.view(torch.uint8))).relu()\n nvfuser_direct_test.assertEqual(out[0], ref)\n\n\ndef test_broadcast_in_dim_no_redundant_set(nvfuser_direct_test):\n \"\"\"\n Test that broadcast_in_dim doesn't introduce redundant Set operations\n when all input dimensions are in broadcast_dims (i.e., no actual broadcast).\n\n This verifies the fix for the issue where broadcast_in_dim would create\n a redundant float-to-float cast operation via Set when the input already\n had the correct shape.\n \"\"\"\n\n def fusion_with_broadcast_in_dim(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[1, -1], contiguity=[None, True])\n t1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n # broadcast_in_dim with broadcast_dims=[0, 1] means no new dims are added\n t2 = fd.ops.broadcast_in_dim(t0, t1.shape(), [0, 1])\n t3 = fd.ops.add(t2, t1)\n fd.add_output(t3)\n\n def fusion_with_expand(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[1, -1], contiguity=[None, True])\n t1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n # Direct expand without broadcast_in_dim\n t2 = fd.ops.expand(t0, t1.shape())\n t3 = fd.ops.add(t2, t1)\n fd.add_output(t3)\n\n with FusionDefinition() as fd_bid:\n fusion_with_broadcast_in_dim(fd_bid)\n\n with FusionDefinition() as fd_exp:\n fusion_with_expand(fd_exp)\n\n # Check that the broadcast_in_dim fusion doesn't have a redundant Set operation\n # by comparing the IR string representations - they should be identical since\n # broadcast is a no-op in this case\n assert str(fd_bid) == str(fd_exp)\n\n\ndef test_expanded_to_size_one(nvfuser_direct_test):\n \"\"\"\n Test expanded to size one, which was failing a false positive assert\n \"\"\"\n inputs = [\n torch.randint(0, 10, (1, 1), device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.define_tensor(\n shape=[1, -1], contiguity=[None, None], dtype=DataType.Int\n )\n fd.add_output(tv0)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_expanded_to_size_one","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_expanded_to_size_one#L2747-L2765","kind":"function","name":"test_expanded_to_size_one","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2747,"end_line":2765,"context_start_line":2727,"context_end_line":2785,"code":" def fusion_with_expand(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[1, -1], contiguity=[None, True])\n t1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n # Direct expand without broadcast_in_dim\n t2 = fd.ops.expand(t0, t1.shape())\n t3 = fd.ops.add(t2, t1)\n fd.add_output(t3)\n\n with FusionDefinition() as fd_bid:\n fusion_with_broadcast_in_dim(fd_bid)\n\n with FusionDefinition() as fd_exp:\n fusion_with_expand(fd_exp)\n\n # Check that the broadcast_in_dim fusion doesn't have a redundant Set operation\n # by comparing the IR string representations - they should be identical since\n # broadcast is a no-op in this case\n assert str(fd_bid) == str(fd_exp)\n\n\ndef test_expanded_to_size_one(nvfuser_direct_test):\n \"\"\"\n Test expanded to size one, which was failing a false positive assert\n \"\"\"\n inputs = [\n torch.randint(0, 10, (1, 1), device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.define_tensor(\n shape=[1, -1], contiguity=[None, None], dtype=DataType.Int\n )\n fd.add_output(tv0)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(out[0], inputs[0])\n\n\ndef test_issue4888(nvfuser_direct_test):\n # https://github.com/NVIDIA/Fuser/issues/4888\n def nvfuser_fusion_id2(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4096, 4097],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[4096, 4097],\n contiguity=[True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_issue4888","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_issue4888#L2768-L2861","kind":"function","name":"test_issue4888","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2768,"end_line":2861,"context_start_line":2748,"context_end_line":2861,"code":" \"\"\"\n Test expanded to size one, which was failing a false positive assert\n \"\"\"\n inputs = [\n torch.randint(0, 10, (1, 1), device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.define_tensor(\n shape=[1, -1], contiguity=[None, None], dtype=DataType.Int\n )\n fd.add_output(tv0)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(out[0], inputs[0])\n\n\ndef test_issue4888(nvfuser_direct_test):\n # https://github.com/NVIDIA/Fuser/issues/4888\n def nvfuser_fusion_id2(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4096, 4097],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[4096, 4097],\n contiguity=[True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[4096, 4097],\n contiguity=[True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 32, 4096, 4096],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T4 = fd.ops.cast(T0, dtype=DataType.Float)\n T5 = fd.ops.bitwise_or(T1, T2)\n T6 = fd.ops.set(T5)\n fd.add_output(T6, T1)\n T7 = fd.ops.cast(T6, dtype=DataType.Float)\n T8 = fd.ops.mul(T4, T7)\n T9 = fd.ops.cast(T8, dtype=DataType.BFloat16)\n T10 = fd.ops.set(T9)\n fd.add_output(T10, T0)\n T15 = fd.ops.broadcast_in_dim(T10, shape=[1, 4096, 4097], broadcast_dims=[1, 2])\n T21 = fd.ops.broadcast_in_dim(\n T15, shape=[1, 1, 4096, 4097], broadcast_dims=[0, 2, 3]\n )\n T27 = fd.ops.broadcast_in_dim(\n T21, shape=[1, 1, 4096, 4097], broadcast_dims=[0, 1, 2, 3]\n )\n T43 = fd.ops.slice(\n T27,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 1, 4096, 4096],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T49 = fd.ops.broadcast_in_dim(\n T43, shape=[1, 32, 4096, 4096], broadcast_dims=[0, 1, 2, 3]\n )\n T50 = fd.ops.cast(T49, dtype=DataType.Float)\n T51 = fd.ops.cast(T3, dtype=DataType.Float)\n S52 = fd.define_scalar(0.0883883, dtype=DataType.Double)\n T53 = fd.ops.mul(T51, S52)\n T54 = fd.ops.add(T53, T50)\n T55 = fd.ops.max(T54, dims=[3], keepdim=False, dtype=DataType.Null)\n T61 = fd.ops.broadcast_in_dim(\n T55, shape=[1, 32, 4096, 1], broadcast_dims=[0, 1, 2]\n )\n T67 = fd.ops.broadcast_in_dim(\n T61, shape=[1, 32, 4096, 4096], broadcast_dims=[0, 1, 2, 3]\n )\n T68 = fd.ops.sub(T54, T67)\n T69 = fd.ops.exp(T68)\n T70 = fd.ops.sum(T69, dims=[3], keepdim=False, dtype=DataType.Null)\n T76 = fd.ops.broadcast_in_dim(\n T70, shape=[1, 32, 4096, 1], broadcast_dims=[0, 1, 2]\n )\n T82 = fd.ops.broadcast_in_dim(\n T76, shape=[1, 32, 4096, 4096], broadcast_dims=[0, 1, 2, 3]\n )\n T83 = fd.ops.reciprocal(T82)\n T84 = fd.ops.mul(T69, T83)\n T85 = fd.ops.cast(T84, dtype=DataType.BFloat16)\n fd.add_output(T49)\n fd.add_output(T84)\n fd.add_output(T85)\n\n inputs = [\n torch.testing.make_tensor((4096, 4097), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((4096, 4097), dtype=torch.bool, device=\"cuda:0\"),\n torch.testing.make_tensor((4096, 4097), dtype=torch.bool, device=\"cuda:0\"),\n torch.testing.make_tensor(\n (1, 32, 4096, 4096), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id2, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.fusion_func","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.fusion_func#L2547-L2551","kind":"function","name":"fusion_func","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2547,"end_line":2551,"context_start_line":2527,"context_end_line":2571,"code":" # Array([0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)\n expected_output = torch.zeros_like(current_input)\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(current_input)\n c0 = fd.define_scalar(None, dtype=DataType.Int)\n t1 = fd.ops.logical_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, [current_input, num_bits]\n )\n nvfuser_direct_test.assertEqual(nvf_out[0], expected_output)\n\n\ndef test_all_dim_var_mean(nvfuser_direct_test):\n inputs = [torch.randn(2, 2, 2, device=\"cuda\")]\n\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1, t2 = fd.ops.var_mean(t0, [0, 1, 2], correction)\n fd.add_output(t1)\n fd.add_output(t2)\n\n return fusion_func\n\n list_of_test_cases = [0, 1]\n for correction in list_of_test_cases:\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs\n )\n torch_result = torch.var_mean(inputs[0], [0, 1, 2], bool(correction))\n nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_validate_precomputed_values(nvfuser_direct_test):\n # This test is from legacy test_nan.py\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.fn","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.fn#L189-L211","kind":"function","name":"fn","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":189,"end_line":211,"context_start_line":169,"context_end_line":231,"code":" t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n\n t0h = fd.ops.cast(t0, DataType.Half)\n t1h = fd.ops.cast(t1, DataType.Half)\n t2 = fd.ops.add(t0h, t1h)\n t3 = fd.ops.relu(t2)\n t4 = fd.ops.cast(t3, DataType.Half)\n\n fd.add_output(t4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.relu(inputs[0].to(torch.half) + inputs[1].to(torch.half))\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_cast_fp8(nvfuser_direct_test):\n def fn(in_type, out_type):\n inputs = [\n torch.randn([5, 5], device=\"cuda\").to(in_type),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.cast(T0, dtype=torch_dtype_to_nvfuser_dtype(out_type))\n fd.add_output(T1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0].to(out_type)\n if in_type == torch.float8_e8m0fnu or out_type == torch.float8_e8m0fnu:\n # Eager mode uses manual bit manipulation, and nvFuser uses\n # hardware instructions. Unfortunately, these implementations\n # do not match exactly. e8m0 can only represent 2^x, so we are\n # asserting that the x of the two results are off by at most 1.\n nvf_out_fp32 = nvf_out[0].to(torch.float32)\n eager_out_fp32 = eager_out.to(torch.float32)\n rel_err = eager_out_fp32.div(nvf_out_fp32).max().item()\n nvfuser_direct_test.assertTrue(rel_err <= 2 and rel_err >= 0.5)\n else:\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n for type0 in [torch.double, torch.float32, torch.float16, torch.bfloat16]:\n type1_list = [torch.float8_e4m3fn, torch.float8_e5m2]\n if not is_pre_blackwell():\n type1_list.append(torch.float8_e8m0fnu)\n for type1 in type1_list:\n fn(type0, type1)\n fn(type1, type0)\n\n\ndef test_promote_to_double(nvfuser_direct_test):\n inputs = [\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float16),\n torch.randn(2, 4, device=\"cuda\", dtype=torch.float64),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.dynamic_reshape","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.dynamic_reshape#L424-L430","kind":"function","name":"dynamic_reshape","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":424,"end_line":430,"context_start_line":404,"context_end_line":450,"code":" n_shape = fd.define_vector(2)\n\n t1 = fd.ops.reshape(t0, n_shape)\n t2 = fd.ops.sum(t1, dims=[0])\n\n fd.add_output(t2)\n\n eager_out = torch.sum(inputs_with_list[0].reshape(new_shape), dim=0)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs_with_list)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n inputs_with_tuple = [tensor, tuple(new_shape)]\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs_with_tuple, new_fusion_expected=False\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_dynamic_reshape(nvfuser_direct_test):\n def dynamic_reshape(fd: FusionDefinition) -> None:\n x = fd.define_tensor([-1, -1], [True, True])\n d0 = fd.ops.size(x, 0)\n d1 = fd.define_scalar(dtype=DataType.Int32)\n d2 = fd.define_scalar(dtype=DataType.Int32)\n y = fd.ops.reshape(x, [d0, d1, d2])\n fd.add_output(y)\n\n x = torch.rand(3, 4, device=\"cuda\")\n ys, _ = nvfuser_direct_test.exec_nvfuser(dynamic_reshape, [x, 2, 2])\n nvfuser_direct_test.assertEqual(len(ys), 1)\n y = ys[0]\n\n nvfuser_direct_test.assertEqual(y.shape, torch.Size([3, 2, 2]))\n nvfuser_direct_test.assertEqual(x.flatten(), y.flatten())\n\n\ndef test_reshape_dynamic(nvfuser_direct_test):\n inputs = [\n 32,\n torch.randn((192,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4, 8, 6), (48, 6, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Int)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_fn","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_fn#L749-L758","kind":"function","name":"test_fn","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":749,"end_line":758,"context_start_line":729,"context_end_line":778,"code":" def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cummin(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cummin(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out[0], nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_cummax(nvfuser_direct_test):\n inputs = [\n torch.randn(8, 16, device=\"cuda\"),\n ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cummax(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cummax(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out[0], nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_where(nvfuser_direct_test):\n # nvfuser_where is a decorator function. It takes the input arguments\n # and creates a function that builds a FusionDefinition.\n def nvfuser_where(pred, a, b):\n def fusion_func(fd: FusionDefinition):\n nv_pred = fd.define_tensor(\n sizes=pred.shape, strides=pred.stride(), dtype=DataType.Bool\n )\n nv_a = fd.define_tensor(\n sizes=a.shape,\n strides=a.stride(),\n dtype=torch_dtype_to_nvfuser_dtype(a.dtype),\n )\n nv_b = fd.define_tensor(\n sizes=b.shape,","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.nvfuser_where","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.nvfuser_where#L767-L785","kind":"function","name":"nvfuser_where","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":767,"end_line":785,"context_start_line":747,"context_end_line":805,"code":" ]\n\n def test_fn(dim):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.cummax(t0, dim)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = torch.cummax(inputs[0], dim)\n nvfuser_direct_test.assertEqual(eager_out[0], nvf_out[0])\n\n test_fn(0)\n test_fn(1)\n\n\ndef test_where(nvfuser_direct_test):\n # nvfuser_where is a decorator function. It takes the input arguments\n # and creates a function that builds a FusionDefinition.\n def nvfuser_where(pred, a, b):\n def fusion_func(fd: FusionDefinition):\n nv_pred = fd.define_tensor(\n sizes=pred.shape, strides=pred.stride(), dtype=DataType.Bool\n )\n nv_a = fd.define_tensor(\n sizes=a.shape,\n strides=a.stride(),\n dtype=torch_dtype_to_nvfuser_dtype(a.dtype),\n )\n nv_b = fd.define_tensor(\n sizes=b.shape,\n strides=b.stride(),\n dtype=torch_dtype_to_nvfuser_dtype(b.dtype),\n )\n result = fd.ops.where(nv_pred, nv_a, nv_b)\n fd.add_output(result)\n\n return fusion_func\n\n # get list of dtypes to test with\n list_of_dtype = [torch.float16, torch.float32]\n if not is_pre_ampere():\n list_of_dtype.append(torch.bfloat16)\n\n pred = torch.testing.make_tensor((5,), device=\"cuda\", dtype=torch.bool)\n for atype, btype in itertools.product(list_of_dtype, list_of_dtype):\n a = torch.randn((5,), device=\"cuda\", dtype=atype)\n b = torch.randn((5,), device=\"cuda\", dtype=btype)\n fusion_func = nvfuser_where(pred, a, b)\n nv_result, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [pred, a, b])\n torch_result = torch.where(pred, a, b)\n nvfuser_direct_test.assertEqual(nv_result[0], torch_result)\n\n\ndef test_where_dtypes(nvfuser_direct_test):\n inputs = [\n torch.arange(2, device=\"cuda\").type(torch.bool),\n ]","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.reshape","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.reshape#L1716-L1721","kind":"function","name":"reshape","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1716,"end_line":1721,"context_start_line":1696,"context_end_line":1741,"code":" torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n torch.testing.make_tensor(1024, device=\"cuda\", dtype=torch.long),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n t3 = fd.ops.truediv(t0, t1)\n fd.add_output(t2)\n fd.add_output(t3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(\n nvf_out[0], torch.div(inputs[0], inputs[1], rounding_mode=\"trunc\")\n )\n nvfuser_direct_test.assertEqual(nvf_out[1], torch.true_divide(inputs[0], inputs[1]))\n\n\ndef test_mark_alias_pass(nvfuser_direct_test):\n def reshape(fd: FusionDefinition) -> None:\n x = fd.define_tensor(\n [2, 3, 4], contiguity=[True, True, True], dtype=DataType.Float\n )\n y = fd.ops.reshape(x, [2, 12])\n fd.add_output(y)\n\n x = torch.rand(2, 3, 4, device=\"cuda\")\n ys, _ = nvfuser_direct_test.exec_nvfuser(reshape, [x])\n nvfuser_direct_test.assertEqual(len(ys), 1)\n y = ys[0]\n\n nvfuser_direct_test.assertEqual(y.data_ptr(), x.data_ptr())\n\n\ndef test_misaligned_add(nvfuser_direct_test):\n inputs = [\n torch.ones(2**20 + 1, device=\"cuda\")[1:], # cannot vectorize\n torch.ones(2**20, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.test_dtype","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.test_dtype#L1839-L1849","kind":"function","name":"test_dtype","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1839,"end_line":1849,"context_start_line":1819,"context_end_line":1869,"code":"\n\ndef test_real_imag(nvfuser_direct_test):\n for dtype in [torch.complex128, torch.complex64]:\n inputs = [\n torch.randn(5, dtype=dtype, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n fd.add_output(fd.ops.real(t0))\n fd.add_output(fd.ops.imag(t0))\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(torch.real(inputs[0]), nvf_out[0])\n nvfuser_direct_test.assertEqual(torch.imag(inputs[0]), nvf_out[1])\n\n\ndef test_reduction_complex_number(nvfuser_direct_test):\n def test_dtype(torch_dtype):\n inputs = [torch.randn(2, 32, device=\"cuda\", dtype=torch_dtype)]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.sum(t0, [-1], False, torch_dtype_to_nvfuser_dtype(torch_dtype))\n fd.add_output(t1)\n\n nvf_out1, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.sum(inputs[0], dim=-1)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out1[0])\n\n list_of_dtype = [torch.complex64, torch.complex128]\n for torch_dtype in list_of_dtype:\n test_dtype(torch_dtype)\n\n\ndef test_right_shift_arithmetic(nvfuser_direct_test):\n inputs = [torch.tensor([-2147483648, 1073741824], dtype=torch.int32, device=\"cuda\")]\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(3)\n t1 = fd.ops.bitwise_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out1, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out1 = torch.bitwise_right_shift(inputs[0], 3)\n nvfuser_direct_test.assertEqual(eager_out1, nvf_out1[0])\n\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.fusion_decorator","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.fusion_decorator#L2546-L2553","kind":"function","name":"fusion_decorator","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2546,"end_line":2553,"context_start_line":2526,"context_end_line":2573,"code":" # >>> jax.lax.shift_right_logical(input.to('cpu').numpy(), 64)\n # Array([0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)\n expected_output = torch.zeros_like(current_input)\n\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(current_input)\n c0 = fd.define_scalar(None, dtype=DataType.Int)\n t1 = fd.ops.logical_right_shift(t0, c0)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, [current_input, num_bits]\n )\n nvfuser_direct_test.assertEqual(nvf_out[0], expected_output)\n\n\ndef test_all_dim_var_mean(nvfuser_direct_test):\n inputs = [torch.randn(2, 2, 2, device=\"cuda\")]\n\n # use decorator to create fusion_func\n def fusion_decorator(correction):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1, t2 = fd.ops.var_mean(t0, [0, 1, 2], correction)\n fd.add_output(t1)\n fd.add_output(t2)\n\n return fusion_func\n\n list_of_test_cases = [0, 1]\n for correction in list_of_test_cases:\n fuser_result, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_decorator(correction), inputs\n )\n torch_result = torch.var_mean(inputs[0], [0, 1, 2], bool(correction))\n nvfuser_direct_test.assertEqual(fuser_result, torch_result)\n\n\ndef test_validate_precomputed_values(nvfuser_direct_test):\n # This test is from legacy test_nan.py\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.fusion_with_broadcast_in_dim","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.fusion_with_broadcast_in_dim#L2719-L2725","kind":"function","name":"fusion_with_broadcast_in_dim","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2719,"end_line":2725,"context_start_line":2699,"context_end_line":2745,"code":" )\n T1 = fd.ops.cast(T0, DataType.Float)\n T2 = fd.ops.relu(T1)\n fd.add_output(T2)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n ref = fp4_to_fp32(unpack_fp4(t0_fp4.view(torch.uint8))).relu()\n nvfuser_direct_test.assertEqual(out[0], ref)\n\n\ndef test_broadcast_in_dim_no_redundant_set(nvfuser_direct_test):\n \"\"\"\n Test that broadcast_in_dim doesn't introduce redundant Set operations\n when all input dimensions are in broadcast_dims (i.e., no actual broadcast).\n\n This verifies the fix for the issue where broadcast_in_dim would create\n a redundant float-to-float cast operation via Set when the input already\n had the correct shape.\n \"\"\"\n\n def fusion_with_broadcast_in_dim(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[1, -1], contiguity=[None, True])\n t1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n # broadcast_in_dim with broadcast_dims=[0, 1] means no new dims are added\n t2 = fd.ops.broadcast_in_dim(t0, t1.shape(), [0, 1])\n t3 = fd.ops.add(t2, t1)\n fd.add_output(t3)\n\n def fusion_with_expand(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[1, -1], contiguity=[None, True])\n t1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n # Direct expand without broadcast_in_dim\n t2 = fd.ops.expand(t0, t1.shape())\n t3 = fd.ops.add(t2, t1)\n fd.add_output(t3)\n\n with FusionDefinition() as fd_bid:\n fusion_with_broadcast_in_dim(fd_bid)\n\n with FusionDefinition() as fd_exp:\n fusion_with_expand(fd_exp)\n\n # Check that the broadcast_in_dim fusion doesn't have a redundant Set operation\n # by comparing the IR string representations - they should be identical since\n # broadcast is a no-op in this case\n assert str(fd_bid) == str(fd_exp)\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.fusion_with_expand","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.fusion_with_expand#L2727-L2733","kind":"function","name":"fusion_with_expand","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2727,"end_line":2733,"context_start_line":2707,"context_end_line":2753,"code":"\n\ndef test_broadcast_in_dim_no_redundant_set(nvfuser_direct_test):\n \"\"\"\n Test that broadcast_in_dim doesn't introduce redundant Set operations\n when all input dimensions are in broadcast_dims (i.e., no actual broadcast).\n\n This verifies the fix for the issue where broadcast_in_dim would create\n a redundant float-to-float cast operation via Set when the input already\n had the correct shape.\n \"\"\"\n\n def fusion_with_broadcast_in_dim(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[1, -1], contiguity=[None, True])\n t1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n # broadcast_in_dim with broadcast_dims=[0, 1] means no new dims are added\n t2 = fd.ops.broadcast_in_dim(t0, t1.shape(), [0, 1])\n t3 = fd.ops.add(t2, t1)\n fd.add_output(t3)\n\n def fusion_with_expand(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[1, -1], contiguity=[None, True])\n t1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n # Direct expand without broadcast_in_dim\n t2 = fd.ops.expand(t0, t1.shape())\n t3 = fd.ops.add(t2, t1)\n fd.add_output(t3)\n\n with FusionDefinition() as fd_bid:\n fusion_with_broadcast_in_dim(fd_bid)\n\n with FusionDefinition() as fd_exp:\n fusion_with_expand(fd_exp)\n\n # Check that the broadcast_in_dim fusion doesn't have a redundant Set operation\n # by comparing the IR string representations - they should be identical since\n # broadcast is a no-op in this case\n assert str(fd_bid) == str(fd_exp)\n\n\ndef test_expanded_to_size_one(nvfuser_direct_test):\n \"\"\"\n Test expanded to size one, which was failing a false positive assert\n \"\"\"\n inputs = [\n torch.randint(0, 10, (1, 1), device=\"cuda\"),\n ]","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.nvfuser_fusion_id2","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.nvfuser_fusion_id2#L2770-L2851","kind":"function","name":"nvfuser_fusion_id2","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":2770,"end_line":2851,"context_start_line":2750,"context_end_line":2861,"code":" \"\"\"\n inputs = [\n torch.randint(0, 10, (1, 1), device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.define_tensor(\n shape=[1, -1], contiguity=[None, None], dtype=DataType.Int\n )\n fd.add_output(tv0)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n nvfuser_direct_test.assertEqual(out[0], inputs[0])\n\n\ndef test_issue4888(nvfuser_direct_test):\n # https://github.com/NVIDIA/Fuser/issues/4888\n def nvfuser_fusion_id2(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4096, 4097],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[4096, 4097],\n contiguity=[True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[4096, 4097],\n contiguity=[True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 32, 4096, 4096],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T4 = fd.ops.cast(T0, dtype=DataType.Float)\n T5 = fd.ops.bitwise_or(T1, T2)\n T6 = fd.ops.set(T5)\n fd.add_output(T6, T1)\n T7 = fd.ops.cast(T6, dtype=DataType.Float)\n T8 = fd.ops.mul(T4, T7)\n T9 = fd.ops.cast(T8, dtype=DataType.BFloat16)\n T10 = fd.ops.set(T9)\n fd.add_output(T10, T0)\n T15 = fd.ops.broadcast_in_dim(T10, shape=[1, 4096, 4097], broadcast_dims=[1, 2])\n T21 = fd.ops.broadcast_in_dim(\n T15, shape=[1, 1, 4096, 4097], broadcast_dims=[0, 2, 3]\n )\n T27 = fd.ops.broadcast_in_dim(\n T21, shape=[1, 1, 4096, 4097], broadcast_dims=[0, 1, 2, 3]\n )\n T43 = fd.ops.slice(\n T27,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 1, 4096, 4096],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T49 = fd.ops.broadcast_in_dim(\n T43, shape=[1, 32, 4096, 4096], broadcast_dims=[0, 1, 2, 3]\n )\n T50 = fd.ops.cast(T49, dtype=DataType.Float)\n T51 = fd.ops.cast(T3, dtype=DataType.Float)\n S52 = fd.define_scalar(0.0883883, dtype=DataType.Double)\n T53 = fd.ops.mul(T51, S52)\n T54 = fd.ops.add(T53, T50)\n T55 = fd.ops.max(T54, dims=[3], keepdim=False, dtype=DataType.Null)\n T61 = fd.ops.broadcast_in_dim(\n T55, shape=[1, 32, 4096, 1], broadcast_dims=[0, 1, 2]\n )\n T67 = fd.ops.broadcast_in_dim(\n T61, shape=[1, 32, 4096, 4096], broadcast_dims=[0, 1, 2, 3]\n )\n T68 = fd.ops.sub(T54, T67)\n T69 = fd.ops.exp(T68)\n T70 = fd.ops.sum(T69, dims=[3], keepdim=False, dtype=DataType.Null)\n T76 = fd.ops.broadcast_in_dim(\n T70, shape=[1, 32, 4096, 1], broadcast_dims=[0, 1, 2]\n )\n T82 = fd.ops.broadcast_in_dim(\n T76, shape=[1, 32, 4096, 4096], broadcast_dims=[0, 1, 2, 3]\n )\n T83 = fd.ops.reciprocal(T82)\n T84 = fd.ops.mul(T69, T83)\n T85 = fd.ops.cast(T84, dtype=DataType.BFloat16)\n fd.add_output(T49)\n fd.add_output(T84)\n fd.add_output(T85)\n\n inputs = [\n torch.testing.make_tensor((4096, 4097), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((4096, 4097), dtype=torch.bool, device=\"cuda:0\"),\n torch.testing.make_tensor((4096, 4097), dtype=torch.bool, device=\"cuda:0\"),\n torch.testing.make_tensor(\n (1, 32, 4096, 4096), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id2, inputs)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.fusion_fn","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.fusion_fn#L1268-L1274","kind":"function","name":"fusion_fn","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1268,"end_line":1274,"context_start_line":1248,"context_end_line":1294,"code":" .min()\n .cpu()\n .float()\n .isclose(torch.tensor(lo), rtol=1e-2, atol=1e-2)\n .item()\n )\n nvfuser_direct_test.assertTrue(\n nvf_out[0]\n .max()\n .cpu()\n .float()\n .isclose(torch.tensor(hi), rtol=1e-2, atol=1e-2)\n .item()\n )\n\n\ndef test_random_distinct_values(nvfuser_direct_test):\n dtypes = [DataType.Double, DataType.Float, DataType.Half, DataType.BFloat16]\n for dtype, rand_op_name in itertools.product(dtypes, [\"uniform\", \"normal\"]):\n\n def fusion_fn(fd: FusionDefinition):\n # generate 4 values and check that they are all distinct\n rand_op = getattr(fd.ops, rand_op_name)\n S0 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S1 = fd.define_scalar(1.00000, dtype=DataType.Double)\n output = rand_op(S0, S1, shape=[2, 2], dtype=dtype)\n fd.add_output(output)\n\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n for i in range(100):\n output = fd.execute([])[0]\n\n # Rarely we might have a pair of matching lower precision\n # samples. However, it is extremely rare that we would have a\n # set of three matching elements in only 100 repeats unless we\n # have a bug.\n\n match = output.flatten().unsqueeze(0) == output.flatten().unsqueeze(1)\n match_pairs = (\n match ^ torch.eye(4, dtype=torch.bool, device=\"cuda\")\n ).sum() // 2\n\n assert match_pairs.item() < 3, f\"At least three entries match in {output}\"\n\n","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.fusion_set_func","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.fusion_set_func#L1421-L1426","kind":"function","name":"fusion_set_func","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1421,"end_line":1426,"context_start_line":1401,"context_end_line":1446,"code":"\n fd.add_output(t4)\n fd.add_output(t5)\n fd.add_output(t6)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = inputs[0] + inputs[1]\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0] + inputs[1])\n nvfuser_direct_test.assertEqual(nvf_out[1], inputs[2] + 3.0)\n nvfuser_direct_test.assertEqual(nvf_out[2], inputs[3] * 3.0)\n\n\ndef test_output_stride_order(nvfuser_direct_test):\n inputs = [\n torch.arange(0, 24).reshape(2, 3, 4).cuda().float(),\n ]\n eager_out = inputs[0] + 3.0\n\n for perm in itertools.permutations(range(3), 3):\n # testing stride_order in set\n def fusion_set_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(3.0)\n t1 = fd.ops.add(t0, c0)\n t2 = fd.ops.stride_order(t1, perm)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_set_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n nvf_stride = nvf_out[0].stride()\n verify_stride_order(nvf_stride, perm)\n\n\ndef test_output_stride_order_with_reduction(nvfuser_direct_test):\n inputs = [torch.randn(2, 3, 4, 5, device=\"cuda\", dtype=torch.float)]\n\n for stride_order in itertools.permutations(range(3), 3):\n\n def fusion_stride_order_op(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.sum(T0, dims=[2])\n T2 = fd.ops.stride_order(T1, stride_order)\n fd.add_output(T2)\n\n with FusionDefinition() as fd:","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_frontend.fusion_stride_order_op","uri":"program://Fuser/function/tests.python.direct.test_python_frontend.fusion_stride_order_op#L1440-L1444","kind":"function","name":"fusion_stride_order_op","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1440,"end_line":1444,"context_start_line":1420,"context_end_line":1464,"code":" # testing stride_order in set\n def fusion_set_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n c0 = fd.define_scalar(3.0)\n t1 = fd.ops.add(t0, c0)\n t2 = fd.ops.stride_order(t1, perm)\n fd.add_output(t2)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_set_func, inputs)\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n nvf_stride = nvf_out[0].stride()\n verify_stride_order(nvf_stride, perm)\n\n\ndef test_output_stride_order_with_reduction(nvfuser_direct_test):\n inputs = [torch.randn(2, 3, 4, 5, device=\"cuda\", dtype=torch.float)]\n\n for stride_order in itertools.permutations(range(3), 3):\n\n def fusion_stride_order_op(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.ops.sum(T0, dims=[2])\n T2 = fd.ops.stride_order(T1, stride_order)\n fd.add_output(T2)\n\n with FusionDefinition() as fd:\n fusion_stride_order_op(fd)\n\n out = fd.execute(inputs)[0]\n verify_stride_order(out.stride(), stride_order)\n\n\ndef test_triu(nvfuser_direct_test):\n inputs = [\n torch.randn(4, 16, device=\"cuda\", dtype=torch.float16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.triu(t0, -1)\n fd.add_output(t1)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out0 = torch.triu(inputs[0], -1)","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision","uri":"program://Fuser/module/tests.python.direct.test_narrow_precision#L1-L989","kind":"module","name":"tests.python.direct.test_narrow_precision","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":1,"end_line":989,"context_start_line":1,"context_end_line":989,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\n\nfrom nvfuser_direct import (\n FusionDefinition,\n DataType,\n)\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom python.direct_utils import (\n FLOAT4_E2M1_MAX,\n FLOAT8_E4M3_MAX,\n pytorch_nvfp4_quantize,\n microarchitecture_is,\n is_pre_blackwell,\n microarchitecture_is_pre,\n linear_to_swizzled_128_4,\n round_up,\n activation_scale_to_nvfp4,\n to_fp4,\n swizzled_to_linear_128_4,\n dequantize_fp4,\n)\n\nimport pytest\n\n\ndef nvfp4_quantize(x):\n x_global_scale = ((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / x.abs().max()).to(\n torch.float32\n )\n\n x_u8, x_scale = pytorch_nvfp4_quantize(x, x_global_scale)\n return x_u8, x_scale, x_global_scale\n\n\ndef quantize_to_mxfp8_e4m3(tensor: torch.Tensor):\n \"\"\"\n Quantize a Float32 tensor to MXFP8 E4M3 format using block scaling.\n Args:\n tensor: Input Float32 tensor to quantize\n Returns:\n MXFP8Tensor containing quantized data and scaling factors\n Note: You can access the components separately:\n - quantized_tensor._rowwise_data: quantized FP8 values (uint8)\n - quantized_tensor._rowwise_scale_inv: inverse scale factors (uint8)\n \"\"\"\n from transformer_engine.pytorch.tensor.mxfp8_tensor import MXFP8Quantizer\n import transformer_engine_torch as tex\n\n # Create MXFP8 quantizer for E4M3 format\n quantizer = MXFP8Quantizer(\n fp8_dtype=tex.DType.kFloat8E4M3,\n rowwise=True, # Enable rowwise scaling\n columnwise=False, # Disable columnwise scaling for this example\n )\n\n # Perform quantization\n quantized_tensor = quantizer(tensor)\n\n return quantized_tensor\n\n\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.parametrize(\"dtype\", [torch.float32, torch.bfloat16])\ndef test_nv_quantization_to_mxfp8(nvfuser_direct_test, dtype):\n x = torch.rand((1024, 1024), dtype=dtype, device=\"cuda\")\n\n quantized_x = quantize_to_mxfp8_e4m3(x)\n ref_vals = quantized_x._rowwise_data.view(torch.float8_e4m3fn)\n ref_scales = quantized_x._rowwise_scale_inv.view(torch.float8_e8m0fnu)\n\n def nvfuser_fusion_id0(fd: FusionDefinition):\n x_tv = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n is_cpu=False,\n )\n vals_, scales_ = fd.ops.nv_block_quantize(\n x_tv, None, False, 32, DataType.Float8_e4m3fn\n )\n fd.add_output(vals_)\n fd.add_output(scales_)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, [x])\n\n quantized_vals = outputs[0]\n quantized_scales = outputs[1]\n\n # Check that values match\n torch.testing.assert_close(\n quantized_vals, ref_vals, rtol=0, atol=0, msg=\"Quantized values do not match\"\n )\n\n # Check that scales match\n torch.testing.assert_close(\n quantized_scales, ref_scales, rtol=0, atol=0, msg=\"Block scales do not match\"\n )\n\n\ndef nvfp4_quantize_with_te(input_tensor):\n \"\"\"\n Directly quantizes a tensor to NVFP4 using TE NVFP4Quantizer,\n returning the NVFP4Tensor which contains the quantized values and block scales.\n Block size is 16 elements per scale.\n \"\"\"\n\n import transformer_engine.pytorch as te\n import transformer_engine.pytorch.cpp_extensions as tex\n\n try:\n # Create NVFP4Quantizer with block size of 16\n quantizer = te.NVFP4Quantizer(\n fp4_dtype=tex.DType.kFloat4E2M1, # NVFP4 format\n rowwise=True, # Use rowwise block scaling\n columnwise=False, # Disable columnwise\n )\n\n # Quantize the input tensor\n nvfp4_tensor = quantizer.quantize(input_tensor)\n return nvfp4_tensor\n\n except Exception as e:\n print(f\"\\nError during quantization: {e}\")\n import traceback\n\n traceback.print_exc()\n print(\"NOTE: This requires an NVIDIA Blackwell GPU and TE >= 1.6.\")\n return None\n\n\ndef compute_nvfp4_global_scale(tensor):\n \"\"\"Compute global scale factor for NVFP4 quantization.\n\n Args:\n tensor: Input tensor to compute scale for\n\n Returns:\n Global scale as (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / max(abs(tensor)),\n clamped to float32 max. Returns 1.0 if max(abs(tensor)) is 0.\n \"\"\"\n amax_scalar = torch.max(torch.abs(tensor)).cpu().to(torch.float32).item()\n\n if amax_scalar == 0.0:\n return torch.tensor(1.0, device=tensor.device, dtype=torch.float32)\n\n float32_max = torch.finfo(torch.float32).max\n scale = min((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / amax_scalar, float32_max)\n\n return torch.tensor(scale, device=tensor.device, dtype=torch.float32)\n\n\ndef extract_te_nvfp4_metadata(input_tensor):\n \"\"\"Quantize tensor with TE and extract quantization metadata.\n\n Args:\n input_tensor: Input tensor to quantize\n\n Returns:\n Tuple of (quantized_data, scale_inv, global_scale)\n \"\"\"\n nvfp4_tensor = nvfp4_quantize_with_te(input_tensor)\n metadata = nvfp4_tensor.get_metadata()\n quantized_data = metadata[\"rowwise_data\"].view((torch.float4_e2m1fn_x2))\n scale_inv = metadata[\"rowwise_scale_inv\"].view(torch.float8_e4m3fn)\n global_scale = compute_nvfp4_global_scale(input_tensor)\n return quantized_data, scale_inv, global_scale\n\n\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.parametrize(\"swizzle_scales\", [True, False])\n@pytest.mark.parametrize(\"sizes\", [[1024, 1024], [1, 1024]])\n@pytest.mark.parametrize(\"dtype\", [torch.bfloat16, torch.float32])\ndef test_nv_block_quantization_vs_te(nvfuser_direct_test, swizzle_scales, sizes, dtype):\n \"\"\"Compare nvfuser nv_block_quantize output against Transformer Engine NVFP4 quantization.\"\"\"\n x = torch.randn(sizes, dtype=dtype, device=\"cuda\")\n\n if swizzle_scales and (sizes[0] % 128 != 0 or sizes[1] % 4 != 0):\n # otherwise, nvfuser_direct_test.exec_nvfuser would assert on identical result from captured fusion.\n pytest.skip(\n \"Swizzled scales require 128x4 block size to avoid uninitialized padding region in outputs\"\n )\n\n # Compute global scale for nvfuser block quantization\n x_global_scale = compute_nvfp4_global_scale(x)\n\n def nvfuser_fusion_id0(fd: FusionDefinition):\n x_tv = fd.from_pytorch(x)\n global_scale_tv = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n vals_, scales_ = fd.ops.nv_block_quantize(\n x_tv, global_scale_tv, swizzle_scales, 16\n )\n fd.add_output(vals_)\n fd.add_output(scales_)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(\n nvfuser_fusion_id0, [x, x_global_scale]\n )\n\n # Get TE NVFP4 reference\n if sizes[0] == 1:\n # nvfp4_quantize_with_te requires batch dimension to be multiple of 16.\n x = x.expand(16, sizes[1])\n nvfp4_result = nvfp4_quantize_with_te(x)\n assert nvfp4_result is not None\n nvfp4_metadata = nvfp4_result.get_metadata()\n te_data = nvfp4_metadata[\"rowwise_data\"].view(torch.uint8)\n te_scales = nvfp4_metadata[\"rowwise_scale_inv\"]\n\n fuser_data = outputs[0].view(torch.uint8)\n fuser_scales = outputs[1]\n\n if swizzle_scales:\n te_scales = linear_to_swizzled_128_4(te_scales)\n te_scales = swizzled_to_linear_128_4(te_scales, *sizes)\n fuser_scales = swizzled_to_linear_128_4(fuser_scales, *sizes)\n\n ref_fp32 = dequantize_fp4(te_data, te_scales, torch.max(torch.abs(x)).float())\n fuser_fp32 = dequantize_fp4(\n fuser_data, fuser_scales, torch.max(torch.abs(x)).float()\n )\n if sizes[0] == 1:\n # slice the expanded data\n ref_fp32 = ref_fp32[0]\n abs_diff = torch.abs(ref_fp32 - fuser_fp32)\n assert torch.max(abs_diff) <= 1.0\n\n # The percentage of mismatched values is LT 10%.\n nonzero = torch.count_nonzero(torch.ne(abs_diff, 0.0))\n assert (nonzero / abs_diff.numel()) < 0.1\n\n\n# cannot use opinfo test, because the input tensor dtype and fusion definition dtype doesn't match\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[128, 256, 512], [128, 256, 512]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_scaled_mm(\n nvfuser_direct_test,\n config,\n out_dtype,\n):\n in_dtype = torch.float4_e2m1fn_x2\n quantization = nvfp4_quantize\n\n m, k, n = config\n mat1_ref = torch.randn((m, k), dtype=torch.float32, device=\"cuda\")\n mat2_ref = torch.randn((n, k), dtype=torch.float32, device=\"cuda\")\n\n mat1, scale1, global_sf1 = quantization(mat1_ref)\n mat2, scale2, global_sf2 = quantization(mat2_ref)\n alpha = 1.0 / (global_sf1 * global_sf2)\n\n inputs = [\n mat1,\n mat2.t(),\n linear_to_swizzled_128_4(scale1),\n linear_to_swizzled_128_4(scale2),\n alpha,\n ]\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float4_e2m1fn, is_cpu=False\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[0, 1],\n )\n scale1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n alpha = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n out, _, _ = fd.ops.scaled_mm(\n mat1,\n mat2,\n scale1,\n scale2,\n alpha,\n bias=None,\n beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(\n nvfuser_fusion_id0, inputs, new_fusion_expected=None\n )\n\n ref_outputs = (\n torch._scaled_mm(\n mat1,\n mat2.t(),\n linear_to_swizzled_128_4(scale1),\n linear_to_swizzled_128_4(scale2),\n None,\n None,\n out_dtype,\n )\n * alpha\n )\n torch.testing.assert_close(outputs[0], ref_outputs, rtol=1e-1, atol=1e-2)\n\n\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 1024, 1024]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_scaled_mm_nv_quantized(\n nvfuser_direct_test,\n config,\n out_dtype,\n):\n \"\"\"Test scaled_mm with on-the-fly quantization vs pre-quantized baseline.\n\n Compares nvfuser's nv_block_quantize (quantizing mat1 on-the-fly) against\n a baseline using pre-quantized inputs from Transformer Engine.\n \"\"\"\n m, k, n = config\n mat1_ref = torch.testing.make_tensor((m, k), dtype=torch.float, device=\"cuda\")\n mat2_ref = torch.testing.make_tensor((n, k), dtype=torch.float, device=\"cuda\")\n\n # Quantize both matrices using Transformer Engine\n mat1_quantized, mat1_scale_inv, global_sf1 = extract_te_nvfp4_metadata(mat1_ref)\n mat2_quantized, mat2_scale_inv, global_sf2 = extract_te_nvfp4_metadata(mat2_ref)\n\n # Alpha compensates for both quantization scales\n alpha = 1.0 / (global_sf1 * global_sf2)\n\n # Prepare inputs for fusion with on-the-fly quantization\n inputs_with_quantize = [\n mat1_ref,\n mat2_quantized.t(),\n global_sf1,\n linear_to_swizzled_128_4(mat2_scale_inv),\n alpha,\n ]\n\n # Fusion 1: Quantize mat1 on-the-fly using nv_block_quantize\n def fusion_with_nv_block_quantize(fd: FusionDefinition) -> None:\n \"\"\"Defines fusion that quantizes mat1 on-the-fly before scaled_mm.\"\"\"\n mat1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n mat2_fp4 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[0, 1],\n )\n global_scale = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n alpha = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n\n # Quantize mat1 on-the-fly\n mat1_fp4, scale1 = fd.ops.nv_block_quantize(mat1, global_scale, True, 16)\n\n # Perform scaled matrix multiplication\n out, _, _ = fd.ops.scaled_mm(\n mat1_fp4,\n mat2_fp4,\n scale1,\n scale2,\n alpha,\n bias=None,\n beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_with_nv_block_quantize, inputs_with_quantize\n )\n\n # Fusion 2: Baseline using pre-quantized inputs\n inputs_baseline = [\n mat1_quantized,\n mat2_quantized.t(),\n linear_to_swizzled_128_4(mat1_scale_inv),\n linear_to_swizzled_128_4(mat2_scale_inv),\n alpha,\n ]\n\n def fusion_baseline(fd: FusionDefinition) -> None:\n \"\"\"Defines baseline fusion using pre-quantized inputs.\"\"\"\n mat1_fp4 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float4_e2m1fn, is_cpu=False\n )\n mat2_fp4 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[0, 1],\n )\n scale1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n alpha = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n\n out, _, _ = fd.ops.scaled_mm(\n mat1_fp4,\n mat2_fp4,\n scale1,\n scale2,\n alpha,\n bias=None,\n beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs_baseline, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_baseline,\n inputs_baseline,\n new_fusion_expected=None,\n )\n\n torch.testing.assert_close(outputs[0], outputs_baseline[0], atol=1e-2, rtol=1e-2)\n\n\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_cutlass_nvfp4_grouped_mm(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n BLOCK_SIZE = 16\n\n # k dimension is multiple of 128 to avoid padding\n m, n, k = config\n # copy list and append tokens for last expert\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1_ref = torch.testing.make_tensor((m, k), dtype=torch.float32, device=\"cuda:0\")\n # format is g, n, k instead of g, k, n\n mat2_ref = torch.testing.make_tensor(\n (g, n, k), dtype=torch.float32, device=\"cuda:0\"\n )\n\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n blockscale_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n\n # prepare quantization for mat2\n mat2_gs = torch.empty((g,), dtype=torch.float32, device=\"cuda:0\")\n scale2 = torch.empty(\n (g, n, k // BLOCK_SIZE), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n\n acc_tokens = 0\n rounded_acc_tokens = 0\n mat2_scaled = torch.empty(\n (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n for i in range(g):\n global_sf = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2_ref[i].max()\n offsets[i] = acc_tokens\n blockscale_offsets[i] = rounded_acc_tokens\n acc_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_acc_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n scaled_mat2_i, bs_mat2_i = pytorch_nvfp4_quantize(mat2_ref[i], global_sf)\n mat2_gs[i] = 1.0 / global_sf\n mat2_scaled[i] = scaled_mat2_i\n scale2[i] = linear_to_swizzled_128_4(bs_mat2_i)\n\n # prepare quantization for mat1\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")\n mat1, scale1 = activation_scale_to_nvfp4(\n mat1_ref, mat1_gs, offsets, blockscale_offsets, BLOCK_SIZE\n )\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n scale1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n alpha = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n problem_sizes = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n blockscale_offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n mat1,\n mat2,\n scale1,\n scale2,\n alpha,\n problem_sizes,\n offsets,\n blockscale_offsets,\n DataType.BFloat16,\n )\n fd.add_output(out)\n\n inputs = [\n mat1.view(torch.float4_e2m1fn_x2),\n mat2_scaled.view(torch.float4_e2m1fn_x2).transpose(-1, -2),\n scale1,\n scale2,\n mat2_gs,\n problem_sizes,\n offsets,\n blockscale_offsets,\n ]\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n\n o_decomposed_ref = torch.empty(m, n, dtype=torch.bfloat16, device=\"cuda:0\")\n for i in range(g):\n l = offsets[i]\n l_sf = blockscale_offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n r_sf = round_up(tokens_per_expert[i], 128) + l_sf\n # For some reason I cannot feed mat2_gs[i] as alpha in the torch kernel.\n # This triggers a cublas invali\n# ... truncated ...","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.nvfp4_quantize","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.nvfp4_quantize#L31-L37","kind":"function","name":"nvfp4_quantize","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":31,"end_line":37,"context_start_line":11,"context_end_line":57,"code":")\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom python.direct_utils import (\n FLOAT4_E2M1_MAX,\n FLOAT8_E4M3_MAX,\n pytorch_nvfp4_quantize,\n microarchitecture_is,\n is_pre_blackwell,\n microarchitecture_is_pre,\n linear_to_swizzled_128_4,\n round_up,\n activation_scale_to_nvfp4,\n to_fp4,\n swizzled_to_linear_128_4,\n dequantize_fp4,\n)\n\nimport pytest\n\n\ndef nvfp4_quantize(x):\n x_global_scale = ((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / x.abs().max()).to(\n torch.float32\n )\n\n x_u8, x_scale = pytorch_nvfp4_quantize(x, x_global_scale)\n return x_u8, x_scale, x_global_scale\n\n\ndef quantize_to_mxfp8_e4m3(tensor: torch.Tensor):\n \"\"\"\n Quantize a Float32 tensor to MXFP8 E4M3 format using block scaling.\n Args:\n tensor: Input Float32 tensor to quantize\n Returns:\n MXFP8Tensor containing quantized data and scaling factors\n Note: You can access the components separately:\n - quantized_tensor._rowwise_data: quantized FP8 values (uint8)\n - quantized_tensor._rowwise_scale_inv: inverse scale factors (uint8)\n \"\"\"\n from transformer_engine.pytorch.tensor.mxfp8_tensor import MXFP8Quantizer\n import transformer_engine_torch as tex\n\n # Create MXFP8 quantizer for E4M3 format\n quantizer = MXFP8Quantizer(\n fp8_dtype=tex.DType.kFloat8E4M3,\n rowwise=True, # Enable rowwise scaling","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.quantize_to_mxfp8_e4m3","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.quantize_to_mxfp8_e4m3#L40-L64","kind":"function","name":"quantize_to_mxfp8_e4m3","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":40,"end_line":64,"context_start_line":20,"context_end_line":84,"code":" linear_to_swizzled_128_4,\n round_up,\n activation_scale_to_nvfp4,\n to_fp4,\n swizzled_to_linear_128_4,\n dequantize_fp4,\n)\n\nimport pytest\n\n\ndef nvfp4_quantize(x):\n x_global_scale = ((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / x.abs().max()).to(\n torch.float32\n )\n\n x_u8, x_scale = pytorch_nvfp4_quantize(x, x_global_scale)\n return x_u8, x_scale, x_global_scale\n\n\ndef quantize_to_mxfp8_e4m3(tensor: torch.Tensor):\n \"\"\"\n Quantize a Float32 tensor to MXFP8 E4M3 format using block scaling.\n Args:\n tensor: Input Float32 tensor to quantize\n Returns:\n MXFP8Tensor containing quantized data and scaling factors\n Note: You can access the components separately:\n - quantized_tensor._rowwise_data: quantized FP8 values (uint8)\n - quantized_tensor._rowwise_scale_inv: inverse scale factors (uint8)\n \"\"\"\n from transformer_engine.pytorch.tensor.mxfp8_tensor import MXFP8Quantizer\n import transformer_engine_torch as tex\n\n # Create MXFP8 quantizer for E4M3 format\n quantizer = MXFP8Quantizer(\n fp8_dtype=tex.DType.kFloat8E4M3,\n rowwise=True, # Enable rowwise scaling\n columnwise=False, # Disable columnwise scaling for this example\n )\n\n # Perform quantization\n quantized_tensor = quantizer(tensor)\n\n return quantized_tensor\n\n\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.parametrize(\"dtype\", [torch.float32, torch.bfloat16])\ndef test_nv_quantization_to_mxfp8(nvfuser_direct_test, dtype):\n x = torch.rand((1024, 1024), dtype=dtype, device=\"cuda\")\n\n quantized_x = quantize_to_mxfp8_e4m3(x)\n ref_vals = quantized_x._rowwise_data.view(torch.float8_e4m3fn)\n ref_scales = quantized_x._rowwise_scale_inv.view(torch.float8_e8m0fnu)\n\n def nvfuser_fusion_id0(fd: FusionDefinition):\n x_tv = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n is_cpu=False,\n )","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.test_nv_quantization_to_mxfp8","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.test_nv_quantization_to_mxfp8#L71-L104","kind":"function","name":"test_nv_quantization_to_mxfp8","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":71,"end_line":104,"context_start_line":51,"context_end_line":124,"code":" from transformer_engine.pytorch.tensor.mxfp8_tensor import MXFP8Quantizer\n import transformer_engine_torch as tex\n\n # Create MXFP8 quantizer for E4M3 format\n quantizer = MXFP8Quantizer(\n fp8_dtype=tex.DType.kFloat8E4M3,\n rowwise=True, # Enable rowwise scaling\n columnwise=False, # Disable columnwise scaling for this example\n )\n\n # Perform quantization\n quantized_tensor = quantizer(tensor)\n\n return quantized_tensor\n\n\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.parametrize(\"dtype\", [torch.float32, torch.bfloat16])\ndef test_nv_quantization_to_mxfp8(nvfuser_direct_test, dtype):\n x = torch.rand((1024, 1024), dtype=dtype, device=\"cuda\")\n\n quantized_x = quantize_to_mxfp8_e4m3(x)\n ref_vals = quantized_x._rowwise_data.view(torch.float8_e4m3fn)\n ref_scales = quantized_x._rowwise_scale_inv.view(torch.float8_e8m0fnu)\n\n def nvfuser_fusion_id0(fd: FusionDefinition):\n x_tv = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n is_cpu=False,\n )\n vals_, scales_ = fd.ops.nv_block_quantize(\n x_tv, None, False, 32, DataType.Float8_e4m3fn\n )\n fd.add_output(vals_)\n fd.add_output(scales_)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, [x])\n\n quantized_vals = outputs[0]\n quantized_scales = outputs[1]\n\n # Check that values match\n torch.testing.assert_close(\n quantized_vals, ref_vals, rtol=0, atol=0, msg=\"Quantized values do not match\"\n )\n\n # Check that scales match\n torch.testing.assert_close(\n quantized_scales, ref_scales, rtol=0, atol=0, msg=\"Block scales do not match\"\n )\n\n\ndef nvfp4_quantize_with_te(input_tensor):\n \"\"\"\n Directly quantizes a tensor to NVFP4 using TE NVFP4Quantizer,\n returning the NVFP4Tensor which contains the quantized values and block scales.\n Block size is 16 elements per scale.\n \"\"\"\n\n import transformer_engine.pytorch as te\n import transformer_engine.pytorch.cpp_extensions as tex\n\n try:\n # Create NVFP4Quantizer with block size of 16\n quantizer = te.NVFP4Quantizer(\n fp4_dtype=tex.DType.kFloat4E2M1, # NVFP4 format\n rowwise=True, # Use rowwise block scaling\n columnwise=False, # Disable columnwise\n )\n","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.nvfp4_quantize_with_te","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.nvfp4_quantize_with_te#L107-L135","kind":"function","name":"nvfp4_quantize_with_te","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":107,"end_line":135,"context_start_line":87,"context_end_line":155,"code":" )\n fd.add_output(vals_)\n fd.add_output(scales_)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, [x])\n\n quantized_vals = outputs[0]\n quantized_scales = outputs[1]\n\n # Check that values match\n torch.testing.assert_close(\n quantized_vals, ref_vals, rtol=0, atol=0, msg=\"Quantized values do not match\"\n )\n\n # Check that scales match\n torch.testing.assert_close(\n quantized_scales, ref_scales, rtol=0, atol=0, msg=\"Block scales do not match\"\n )\n\n\ndef nvfp4_quantize_with_te(input_tensor):\n \"\"\"\n Directly quantizes a tensor to NVFP4 using TE NVFP4Quantizer,\n returning the NVFP4Tensor which contains the quantized values and block scales.\n Block size is 16 elements per scale.\n \"\"\"\n\n import transformer_engine.pytorch as te\n import transformer_engine.pytorch.cpp_extensions as tex\n\n try:\n # Create NVFP4Quantizer with block size of 16\n quantizer = te.NVFP4Quantizer(\n fp4_dtype=tex.DType.kFloat4E2M1, # NVFP4 format\n rowwise=True, # Use rowwise block scaling\n columnwise=False, # Disable columnwise\n )\n\n # Quantize the input tensor\n nvfp4_tensor = quantizer.quantize(input_tensor)\n return nvfp4_tensor\n\n except Exception as e:\n print(f\"\\nError during quantization: {e}\")\n import traceback\n\n traceback.print_exc()\n print(\"NOTE: This requires an NVIDIA Blackwell GPU and TE >= 1.6.\")\n return None\n\n\ndef compute_nvfp4_global_scale(tensor):\n \"\"\"Compute global scale factor for NVFP4 quantization.\n\n Args:\n tensor: Input tensor to compute scale for\n\n Returns:\n Global scale as (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / max(abs(tensor)),\n clamped to float32 max. Returns 1.0 if max(abs(tensor)) is 0.\n \"\"\"\n amax_scalar = torch.max(torch.abs(tensor)).cpu().to(torch.float32).item()\n\n if amax_scalar == 0.0:\n return torch.tensor(1.0, device=tensor.device, dtype=torch.float32)\n\n float32_max = torch.finfo(torch.float32).max\n scale = min((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / amax_scalar, float32_max)\n","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.compute_nvfp4_global_scale","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.compute_nvfp4_global_scale#L138-L156","kind":"function","name":"compute_nvfp4_global_scale","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":138,"end_line":156,"context_start_line":118,"context_end_line":176,"code":" # Create NVFP4Quantizer with block size of 16\n quantizer = te.NVFP4Quantizer(\n fp4_dtype=tex.DType.kFloat4E2M1, # NVFP4 format\n rowwise=True, # Use rowwise block scaling\n columnwise=False, # Disable columnwise\n )\n\n # Quantize the input tensor\n nvfp4_tensor = quantizer.quantize(input_tensor)\n return nvfp4_tensor\n\n except Exception as e:\n print(f\"\\nError during quantization: {e}\")\n import traceback\n\n traceback.print_exc()\n print(\"NOTE: This requires an NVIDIA Blackwell GPU and TE >= 1.6.\")\n return None\n\n\ndef compute_nvfp4_global_scale(tensor):\n \"\"\"Compute global scale factor for NVFP4 quantization.\n\n Args:\n tensor: Input tensor to compute scale for\n\n Returns:\n Global scale as (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / max(abs(tensor)),\n clamped to float32 max. Returns 1.0 if max(abs(tensor)) is 0.\n \"\"\"\n amax_scalar = torch.max(torch.abs(tensor)).cpu().to(torch.float32).item()\n\n if amax_scalar == 0.0:\n return torch.tensor(1.0, device=tensor.device, dtype=torch.float32)\n\n float32_max = torch.finfo(torch.float32).max\n scale = min((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / amax_scalar, float32_max)\n\n return torch.tensor(scale, device=tensor.device, dtype=torch.float32)\n\n\ndef extract_te_nvfp4_metadata(input_tensor):\n \"\"\"Quantize tensor with TE and extract quantization metadata.\n\n Args:\n input_tensor: Input tensor to quantize\n\n Returns:\n Tuple of (quantized_data, scale_inv, global_scale)\n \"\"\"\n nvfp4_tensor = nvfp4_quantize_with_te(input_tensor)\n metadata = nvfp4_tensor.get_metadata()\n quantized_data = metadata[\"rowwise_data\"].view((torch.float4_e2m1fn_x2))\n scale_inv = metadata[\"rowwise_scale_inv\"].view(torch.float8_e4m3fn)\n global_scale = compute_nvfp4_global_scale(input_tensor)\n return quantized_data, scale_inv, global_scale\n\n\n@pytest.mark.skipif(","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.extract_te_nvfp4_metadata","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.extract_te_nvfp4_metadata#L159-L173","kind":"function","name":"extract_te_nvfp4_metadata","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":159,"end_line":173,"context_start_line":139,"context_end_line":193,"code":" \"\"\"Compute global scale factor for NVFP4 quantization.\n\n Args:\n tensor: Input tensor to compute scale for\n\n Returns:\n Global scale as (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / max(abs(tensor)),\n clamped to float32 max. Returns 1.0 if max(abs(tensor)) is 0.\n \"\"\"\n amax_scalar = torch.max(torch.abs(tensor)).cpu().to(torch.float32).item()\n\n if amax_scalar == 0.0:\n return torch.tensor(1.0, device=tensor.device, dtype=torch.float32)\n\n float32_max = torch.finfo(torch.float32).max\n scale = min((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / amax_scalar, float32_max)\n\n return torch.tensor(scale, device=tensor.device, dtype=torch.float32)\n\n\ndef extract_te_nvfp4_metadata(input_tensor):\n \"\"\"Quantize tensor with TE and extract quantization metadata.\n\n Args:\n input_tensor: Input tensor to quantize\n\n Returns:\n Tuple of (quantized_data, scale_inv, global_scale)\n \"\"\"\n nvfp4_tensor = nvfp4_quantize_with_te(input_tensor)\n metadata = nvfp4_tensor.get_metadata()\n quantized_data = metadata[\"rowwise_data\"].view((torch.float4_e2m1fn_x2))\n scale_inv = metadata[\"rowwise_scale_inv\"].view(torch.float8_e4m3fn)\n global_scale = compute_nvfp4_global_scale(input_tensor)\n return quantized_data, scale_inv, global_scale\n\n\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.parametrize(\"swizzle_scales\", [True, False])\n@pytest.mark.parametrize(\"sizes\", [[1024, 1024], [1, 1024]])\n@pytest.mark.parametrize(\"dtype\", [torch.bfloat16, torch.float32])\ndef test_nv_block_quantization_vs_te(nvfuser_direct_test, swizzle_scales, sizes, dtype):\n \"\"\"Compare nvfuser nv_block_quantize output against Transformer Engine NVFP4 quantization.\"\"\"\n x = torch.randn(sizes, dtype=dtype, device=\"cuda\")\n\n if swizzle_scales and (sizes[0] % 128 != 0 or sizes[1] % 4 != 0):\n # otherwise, nvfuser_direct_test.exec_nvfuser would assert on identical result from captured fusion.\n pytest.skip(\n \"Swizzled scales require 128x4 block size to avoid uninitialized padding region in outputs\"\n )\n\n # Compute global scale for nvfuser block quantization\n x_global_scale = compute_nvfp4_global_scale(x)","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.test_nv_block_quantization_vs_te","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.test_nv_block_quantization_vs_te#L182-L240","kind":"function","name":"test_nv_block_quantization_vs_te","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":182,"end_line":240,"context_start_line":162,"context_end_line":260,"code":" Args:\n input_tensor: Input tensor to quantize\n\n Returns:\n Tuple of (quantized_data, scale_inv, global_scale)\n \"\"\"\n nvfp4_tensor = nvfp4_quantize_with_te(input_tensor)\n metadata = nvfp4_tensor.get_metadata()\n quantized_data = metadata[\"rowwise_data\"].view((torch.float4_e2m1fn_x2))\n scale_inv = metadata[\"rowwise_scale_inv\"].view(torch.float8_e4m3fn)\n global_scale = compute_nvfp4_global_scale(input_tensor)\n return quantized_data, scale_inv, global_scale\n\n\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.parametrize(\"swizzle_scales\", [True, False])\n@pytest.mark.parametrize(\"sizes\", [[1024, 1024], [1, 1024]])\n@pytest.mark.parametrize(\"dtype\", [torch.bfloat16, torch.float32])\ndef test_nv_block_quantization_vs_te(nvfuser_direct_test, swizzle_scales, sizes, dtype):\n \"\"\"Compare nvfuser nv_block_quantize output against Transformer Engine NVFP4 quantization.\"\"\"\n x = torch.randn(sizes, dtype=dtype, device=\"cuda\")\n\n if swizzle_scales and (sizes[0] % 128 != 0 or sizes[1] % 4 != 0):\n # otherwise, nvfuser_direct_test.exec_nvfuser would assert on identical result from captured fusion.\n pytest.skip(\n \"Swizzled scales require 128x4 block size to avoid uninitialized padding region in outputs\"\n )\n\n # Compute global scale for nvfuser block quantization\n x_global_scale = compute_nvfp4_global_scale(x)\n\n def nvfuser_fusion_id0(fd: FusionDefinition):\n x_tv = fd.from_pytorch(x)\n global_scale_tv = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n vals_, scales_ = fd.ops.nv_block_quantize(\n x_tv, global_scale_tv, swizzle_scales, 16\n )\n fd.add_output(vals_)\n fd.add_output(scales_)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(\n nvfuser_fusion_id0, [x, x_global_scale]\n )\n\n # Get TE NVFP4 reference\n if sizes[0] == 1:\n # nvfp4_quantize_with_te requires batch dimension to be multiple of 16.\n x = x.expand(16, sizes[1])\n nvfp4_result = nvfp4_quantize_with_te(x)\n assert nvfp4_result is not None\n nvfp4_metadata = nvfp4_result.get_metadata()\n te_data = nvfp4_metadata[\"rowwise_data\"].view(torch.uint8)\n te_scales = nvfp4_metadata[\"rowwise_scale_inv\"]\n\n fuser_data = outputs[0].view(torch.uint8)\n fuser_scales = outputs[1]\n\n if swizzle_scales:\n te_scales = linear_to_swizzled_128_4(te_scales)\n te_scales = swizzled_to_linear_128_4(te_scales, *sizes)\n fuser_scales = swizzled_to_linear_128_4(fuser_scales, *sizes)\n\n ref_fp32 = dequantize_fp4(te_data, te_scales, torch.max(torch.abs(x)).float())\n fuser_fp32 = dequantize_fp4(\n fuser_data, fuser_scales, torch.max(torch.abs(x)).float()\n )\n if sizes[0] == 1:\n # slice the expanded data\n ref_fp32 = ref_fp32[0]\n abs_diff = torch.abs(ref_fp32 - fuser_fp32)\n assert torch.max(abs_diff) <= 1.0\n\n # The percentage of mismatched values is LT 10%.\n nonzero = torch.count_nonzero(torch.ne(abs_diff, 0.0))\n assert (nonzero / abs_diff.numel()) < 0.1\n\n\n# cannot use opinfo test, because the input tensor dtype and fusion definition dtype doesn't match\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[128, 256, 512], [128, 256, 512]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_scaled_mm(\n nvfuser_direct_test,\n config,\n out_dtype,\n):\n in_dtype = torch.float4_e2m1fn_x2\n quantization = nvfp4_quantize\n\n m, k, n = config\n mat1_ref = torch.randn((m, k), dtype=torch.float32, device=\"cuda\")\n mat2_ref = torch.randn((n, k), dtype=torch.float32, device=\"cuda\")\n","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.test_scaled_mm","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.test_scaled_mm#L249-L321","kind":"function","name":"test_scaled_mm","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":249,"end_line":321,"context_start_line":229,"context_end_line":341,"code":" fuser_fp32 = dequantize_fp4(\n fuser_data, fuser_scales, torch.max(torch.abs(x)).float()\n )\n if sizes[0] == 1:\n # slice the expanded data\n ref_fp32 = ref_fp32[0]\n abs_diff = torch.abs(ref_fp32 - fuser_fp32)\n assert torch.max(abs_diff) <= 1.0\n\n # The percentage of mismatched values is LT 10%.\n nonzero = torch.count_nonzero(torch.ne(abs_diff, 0.0))\n assert (nonzero / abs_diff.numel()) < 0.1\n\n\n# cannot use opinfo test, because the input tensor dtype and fusion definition dtype doesn't match\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[128, 256, 512], [128, 256, 512]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_scaled_mm(\n nvfuser_direct_test,\n config,\n out_dtype,\n):\n in_dtype = torch.float4_e2m1fn_x2\n quantization = nvfp4_quantize\n\n m, k, n = config\n mat1_ref = torch.randn((m, k), dtype=torch.float32, device=\"cuda\")\n mat2_ref = torch.randn((n, k), dtype=torch.float32, device=\"cuda\")\n\n mat1, scale1, global_sf1 = quantization(mat1_ref)\n mat2, scale2, global_sf2 = quantization(mat2_ref)\n alpha = 1.0 / (global_sf1 * global_sf2)\n\n inputs = [\n mat1,\n mat2.t(),\n linear_to_swizzled_128_4(scale1),\n linear_to_swizzled_128_4(scale2),\n alpha,\n ]\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float4_e2m1fn, is_cpu=False\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[0, 1],\n )\n scale1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n alpha = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n out, _, _ = fd.ops.scaled_mm(\n mat1,\n mat2,\n scale1,\n scale2,\n alpha,\n bias=None,\n beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(\n nvfuser_fusion_id0, inputs, new_fusion_expected=None\n )\n\n ref_outputs = (\n torch._scaled_mm(\n mat1,\n mat2.t(),\n linear_to_swizzled_128_4(scale1),\n linear_to_swizzled_128_4(scale2),\n None,\n None,\n out_dtype,\n )\n * alpha\n )\n torch.testing.assert_close(outputs[0], ref_outputs, rtol=1e-1, atol=1e-2)\n\n\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 1024, 1024]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_scaled_mm_nv_quantized(\n nvfuser_direct_test,\n config,\n out_dtype,\n):\n \"\"\"Test scaled_mm with on-the-fly quantization vs pre-quantized baseline.\n\n Compares nvfuser's nv_block_quantize (quantizing mat1 on-the-fly) against\n a baseline using pre-quantized inputs from Transformer Engine.\n \"\"\"\n m, k, n = config\n mat1_ref = torch.testing.make_tensor((m, k), dtype=torch.float, device=\"cuda\")\n mat2_ref = torch.testing.make_tensor((n, k), dtype=torch.float, device=\"cuda\")","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.test_scaled_mm_nv_quantized","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.test_scaled_mm_nv_quantized#L329-L451","kind":"function","name":"test_scaled_mm_nv_quantized","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":329,"end_line":451,"context_start_line":309,"context_end_line":471,"code":" ref_outputs = (\n torch._scaled_mm(\n mat1,\n mat2.t(),\n linear_to_swizzled_128_4(scale1),\n linear_to_swizzled_128_4(scale2),\n None,\n None,\n out_dtype,\n )\n * alpha\n )\n torch.testing.assert_close(outputs[0], ref_outputs, rtol=1e-1, atol=1e-2)\n\n\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 1024, 1024]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_scaled_mm_nv_quantized(\n nvfuser_direct_test,\n config,\n out_dtype,\n):\n \"\"\"Test scaled_mm with on-the-fly quantization vs pre-quantized baseline.\n\n Compares nvfuser's nv_block_quantize (quantizing mat1 on-the-fly) against\n a baseline using pre-quantized inputs from Transformer Engine.\n \"\"\"\n m, k, n = config\n mat1_ref = torch.testing.make_tensor((m, k), dtype=torch.float, device=\"cuda\")\n mat2_ref = torch.testing.make_tensor((n, k), dtype=torch.float, device=\"cuda\")\n\n # Quantize both matrices using Transformer Engine\n mat1_quantized, mat1_scale_inv, global_sf1 = extract_te_nvfp4_metadata(mat1_ref)\n mat2_quantized, mat2_scale_inv, global_sf2 = extract_te_nvfp4_metadata(mat2_ref)\n\n # Alpha compensates for both quantization scales\n alpha = 1.0 / (global_sf1 * global_sf2)\n\n # Prepare inputs for fusion with on-the-fly quantization\n inputs_with_quantize = [\n mat1_ref,\n mat2_quantized.t(),\n global_sf1,\n linear_to_swizzled_128_4(mat2_scale_inv),\n alpha,\n ]\n\n # Fusion 1: Quantize mat1 on-the-fly using nv_block_quantize\n def fusion_with_nv_block_quantize(fd: FusionDefinition) -> None:\n \"\"\"Defines fusion that quantizes mat1 on-the-fly before scaled_mm.\"\"\"\n mat1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n mat2_fp4 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[0, 1],\n )\n global_scale = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n alpha = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n\n # Quantize mat1 on-the-fly\n mat1_fp4, scale1 = fd.ops.nv_block_quantize(mat1, global_scale, True, 16)\n\n # Perform scaled matrix multiplication\n out, _, _ = fd.ops.scaled_mm(\n mat1_fp4,\n mat2_fp4,\n scale1,\n scale2,\n alpha,\n bias=None,\n beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_with_nv_block_quantize, inputs_with_quantize\n )\n\n # Fusion 2: Baseline using pre-quantized inputs\n inputs_baseline = [\n mat1_quantized,\n mat2_quantized.t(),\n linear_to_swizzled_128_4(mat1_scale_inv),\n linear_to_swizzled_128_4(mat2_scale_inv),\n alpha,\n ]\n\n def fusion_baseline(fd: FusionDefinition) -> None:\n \"\"\"Defines baseline fusion using pre-quantized inputs.\"\"\"\n mat1_fp4 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float4_e2m1fn, is_cpu=False\n )\n mat2_fp4 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[0, 1],\n )\n scale1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n alpha = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n\n out, _, _ = fd.ops.scaled_mm(\n mat1_fp4,\n mat2_fp4,\n scale1,\n scale2,\n alpha,\n bias=None,\n beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs_baseline, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_baseline,\n inputs_baseline,\n new_fusion_expected=None,\n )\n\n torch.testing.assert_close(outputs[0], outputs_baseline[0], atol=1e-2, rtol=1e-2)\n\n\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_cutlass_nvfp4_grouped_mm(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n BLOCK_SIZE = 16\n\n # k dimension is multiple of 128 to avoid padding\n m, n, k = config\n # copy list and append tokens for last expert\n tokens_per_expert = list(tokens_per_expert_neg_one)","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.test_cutlass_nvfp4_grouped_mm","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.test_cutlass_nvfp4_grouped_mm#L460-L610","kind":"function","name":"test_cutlass_nvfp4_grouped_mm","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":460,"end_line":610,"context_start_line":440,"context_end_line":630,"code":" beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs_baseline, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_baseline,\n inputs_baseline,\n new_fusion_expected=None,\n )\n\n torch.testing.assert_close(outputs[0], outputs_baseline[0], atol=1e-2, rtol=1e-2)\n\n\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_cutlass_nvfp4_grouped_mm(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n BLOCK_SIZE = 16\n\n # k dimension is multiple of 128 to avoid padding\n m, n, k = config\n # copy list and append tokens for last expert\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1_ref = torch.testing.make_tensor((m, k), dtype=torch.float32, device=\"cuda:0\")\n # format is g, n, k instead of g, k, n\n mat2_ref = torch.testing.make_tensor(\n (g, n, k), dtype=torch.float32, device=\"cuda:0\"\n )\n\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n blockscale_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n\n # prepare quantization for mat2\n mat2_gs = torch.empty((g,), dtype=torch.float32, device=\"cuda:0\")\n scale2 = torch.empty(\n (g, n, k // BLOCK_SIZE), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n\n acc_tokens = 0\n rounded_acc_tokens = 0\n mat2_scaled = torch.empty(\n (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n for i in range(g):\n global_sf = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2_ref[i].max()\n offsets[i] = acc_tokens\n blockscale_offsets[i] = rounded_acc_tokens\n acc_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_acc_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n scaled_mat2_i, bs_mat2_i = pytorch_nvfp4_quantize(mat2_ref[i], global_sf)\n mat2_gs[i] = 1.0 / global_sf\n mat2_scaled[i] = scaled_mat2_i\n scale2[i] = linear_to_swizzled_128_4(bs_mat2_i)\n\n # prepare quantization for mat1\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")\n mat1, scale1 = activation_scale_to_nvfp4(\n mat1_ref, mat1_gs, offsets, blockscale_offsets, BLOCK_SIZE\n )\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n scale1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n alpha = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n problem_sizes = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n blockscale_offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n mat1,\n mat2,\n scale1,\n scale2,\n alpha,\n problem_sizes,\n offsets,\n blockscale_offsets,\n DataType.BFloat16,\n )\n fd.add_output(out)\n\n inputs = [\n mat1.view(torch.float4_e2m1fn_x2),\n mat2_scaled.view(torch.float4_e2m1fn_x2).transpose(-1, -2),\n scale1,\n scale2,\n mat2_gs,\n problem_sizes,\n offsets,\n blockscale_offsets,\n ]\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n\n o_decomposed_ref = torch.empty(m, n, dtype=torch.bfloat16, device=\"cuda:0\")\n for i in range(g):\n l = offsets[i]\n l_sf = blockscale_offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n r_sf = round_up(tokens_per_expert[i], 128) + l_sf\n # For some reason I cannot feed mat2_gs[i] as alpha in the torch kernel.\n # This triggers a cublas invalid value error.\n o_decomposed_ref[l:r] = (\n torch._scaled_mm(\n mat1[l:r],\n mat2_scaled[i].transpose(-1, -2),\n scale1[l_sf:r_sf],\n scale2[i],\n None,\n None,\n torch.bfloat16,\n )\n * mat2_gs[i]\n )\n\n torch.testing.assert_close(o_decomposed_ref, outputs[0], atol=1e-2, rtol=1e-2)\n\n\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.skipif(\n not microarchitecture_is_pre(12), reason=\"Does not support blackwell compute 12.0\"\n)\n@pytest.mark.parametrize(\"dtype\", [torch.bfloat16, torch.float])\ndef test_fp4_vectorization(\n nvfuser_direct_test,\n dtype,\n):\n inputs = [\n torch.ones(4, 8, dtype=dtype, device=\"cuda\"),\n torch.ones(4, dtype=dtype, device=\"cuda\"),\n ]\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.test_fp4_vectorization","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.test_fp4_vectorization#L620-L651","kind":"function","name":"test_fp4_vectorization","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":620,"end_line":651,"context_start_line":600,"context_end_line":671,"code":" mat2_scaled[i].transpose(-1, -2),\n scale1[l_sf:r_sf],\n scale2[i],\n None,\n None,\n torch.bfloat16,\n )\n * mat2_gs[i]\n )\n\n torch.testing.assert_close(o_decomposed_ref, outputs[0], atol=1e-2, rtol=1e-2)\n\n\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.skipif(\n not microarchitecture_is_pre(12), reason=\"Does not support blackwell compute 12.0\"\n)\n@pytest.mark.parametrize(\"dtype\", [torch.bfloat16, torch.float])\ndef test_fp4_vectorization(\n nvfuser_direct_test,\n dtype,\n):\n inputs = [\n torch.ones(4, 8, dtype=dtype, device=\"cuda\"),\n torch.ones(4, dtype=dtype, device=\"cuda\"),\n ]\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.cast(T0, DataType.Float)\n cast_T1 = fd.ops.cast(T1, DataType.Float)\n broadcast_T1 = fd.ops.broadcast(cast_T1, [False, True])\n T3 = fd.ops.div(T2, broadcast_T1)\n T4 = fd.ops.cast(T3, DataType.Float4_e2m1fn)\n T5 = fd.ops.reshape(T4, [32])\n fd.add_output(T5)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n\n ref_outputs = to_fp4(inputs[0].to(torch.float) / inputs[1].unsqueeze(-1)).reshape(\n -1\n )\n\n torch.testing.assert_close(\n outputs[0].view(dtype=torch.uint8),\n ref_outputs.view(dtype=torch.uint8),\n rtol=1e-1,\n atol=1e-2,\n )\n\n\n# This is adopted from the decomposed version.\n# A few things I have to change in order to pass the test:\n# 1. inputs data needs to be changed from `torch.testing.make_tensor` to `torch.randn`;\n# 2. output errors are much more relaxed.\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_block_quantize_op_and_layout_op(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n BLOCK_SIZE = 16\n","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.test_block_quantize_op_and_layout_op","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.test_block_quantize_op_and_layout_op#L664-L822","kind":"function","name":"test_block_quantize_op_and_layout_op","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":664,"end_line":822,"context_start_line":644,"context_end_line":842,"code":" )\n\n torch.testing.assert_close(\n outputs[0].view(dtype=torch.uint8),\n ref_outputs.view(dtype=torch.uint8),\n rtol=1e-1,\n atol=1e-2,\n )\n\n\n# This is adopted from the decomposed version.\n# A few things I have to change in order to pass the test:\n# 1. inputs data needs to be changed from `torch.testing.make_tensor` to `torch.randn`;\n# 2. output errors are much more relaxed.\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_block_quantize_op_and_layout_op(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n BLOCK_SIZE = 16\n\n # k dimension is multiple of 4 * 16 to avoid padding on block scaling factor\n m, n, k = config\n assert k % 64 == 0\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1 = torch.randn((m, k), dtype=torch.float32, device=\"cuda:0\")\n # format is g, n, k instead of g, k, n\n mat2 = torch.randn((g, n, k), dtype=torch.float32, device=\"cuda:0\")\n\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n blockscale_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n\n # prepare quantization for mat2\n mat2_gs = torch.empty((g,), dtype=torch.float32, device=\"cuda:0\")\n scale2 = torch.empty(\n (g, n, k // BLOCK_SIZE), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n\n acc_tokens = 0\n rounded_acc_tokens = 0\n mat2_scaled = torch.empty(\n (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n for i in range(g):\n global_sf = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2[i].max()\n offsets[i] = acc_tokens\n blockscale_offsets[i] = rounded_acc_tokens\n acc_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_acc_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n scaled_mat2_i, bs_mat2_i = pytorch_nvfp4_quantize(mat2[i], global_sf)\n mat2_gs[i] = 1.0 / global_sf\n mat2_scaled[i] = scaled_mat2_i\n scale2[i] = linear_to_swizzled_128_4(bs_mat2_i)\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n alpha = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n problem_sizes = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n blockscale_offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n\n # Note: the decomposed quantization seems to give much better numerics.\n # quantization math with nv_block_quantize op\n fp4_mat1, fp8_scale1 = fd.ops.nv_block_quantize(mat1)\n\n # swizzle & pad block sf\n layout_fp8_scale1 = fd.ops.preprocess_grouped_matmul_input_sf(\n fp8_scale1, offsets, blockscale_offsets\n )\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n mat2,\n layout_fp8_scale1,\n scale2,\n alpha,\n problem_sizes,\n offsets,\n blockscale_offsets,\n DataType.BFloat16,\n )\n fd.add_output(out)\n\n inputs = [\n mat1,\n mat2_scaled.view(torch.float4_e2m1fn_x2).transpose(-1, -2),\n scale2,\n mat2_gs,\n problem_sizes,\n offsets,\n blockscale_offsets,\n ]\n\n o, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n # quantization for activation is needed for reference.\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")\n mat1_fp4, scale1 = activation_scale_to_nvfp4(\n mat1, mat1_gs, offsets, blockscale_offsets, BLOCK_SIZE\n )\n o_decomposed_ref = torch.empty(m, n, dtype=torch.bfloat16, device=\"cuda:0\")\n for i in range(g):\n l = offsets[i]\n l_sf = blockscale_offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n r_sf = round_up(tokens_per_expert[i], 128) + l_sf\n # For some reason I cannot feed mat2_gs[i] as alpha in the torch kernel.\n # This triggers a cublas invalid value error.\n o_decomposed_ref[l:r] = (\n torch._scaled_mm(\n mat1_fp4[l:r],\n mat2_scaled[i].transpose(-1, -2),\n scale1[l_sf:r_sf],\n scale2[i],\n None,\n None,\n torch.bfloat16,\n )\n * mat2_gs[i]\n )\n\n # Validate: nvfuser quantization should match baseline\n abs_diff = torch.abs(o[0] - o_decomposed_ref)\n max_diff = torch.max(abs_diff)\n assert max_diff <= 10.0, f\"Max difference {max_diff:.4f} exceeds threshold of 10.0\"\n\n # Check that large differences (> 5.0) are rare (< 10% of elements)\n large_diff_count = torch.count_nonzero(torch.gt(abs_diff, 5.0))\n large_diff_ratio = large_diff_count / abs_diff.numel()\n assert (\n large_diff_ratio < 0.1\n ), f\"Large diff ratio {large_diff_ratio:.2%} exceeds 10% threshold\"\n\n\n# This is adopted from the decomposed version test_block_quantize_op_and_layout_op\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.skipif(\n not microarchitecture_is_pre(12), reason=\"Does not support blackwell compute 12.0\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_grouped_block_quantize_op(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n BLOCK_SIZE = 16\n","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.test_grouped_block_quantize_op","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.test_grouped_block_quantize_op#L835-L989","kind":"function","name":"test_grouped_block_quantize_op","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":835,"end_line":989,"context_start_line":815,"context_end_line":989,"code":" assert max_diff <= 10.0, f\"Max difference {max_diff:.4f} exceeds threshold of 10.0\"\n\n # Check that large differences (> 5.0) are rare (< 10% of elements)\n large_diff_count = torch.count_nonzero(torch.gt(abs_diff, 5.0))\n large_diff_ratio = large_diff_count / abs_diff.numel()\n assert (\n large_diff_ratio < 0.1\n ), f\"Large diff ratio {large_diff_ratio:.2%} exceeds 10% threshold\"\n\n\n# This is adopted from the decomposed version test_block_quantize_op_and_layout_op\n@pytest.mark.skipif(\n is_pre_blackwell(), reason=\"Only supported on blackwell and newer devices.\"\n)\n@pytest.mark.skipif(\n not microarchitecture_is_pre(12), reason=\"Does not support blackwell compute 12.0\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_grouped_block_quantize_op(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n BLOCK_SIZE = 16\n\n # k dimension is multiple of 4 * 16 to avoid padding on block scaling factor\n m, n, k = config\n assert k % 64 == 0\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1 = torch.randn((m, k), dtype=torch.float32, device=\"cuda:0\")\n # format is g, n, k instead of g, k, n\n mat2 = torch.randn((g, n, k), dtype=torch.float32, device=\"cuda:0\")\n\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n blockscale_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n\n # prepare quantization for mat2\n mat2_gs = torch.empty((g,), dtype=torch.float32, device=\"cuda:0\")\n scale2 = torch.empty(\n (g, n, k // BLOCK_SIZE), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n\n acc_tokens = 0\n rounded_acc_tokens = 0\n mat2_scaled = torch.empty(\n (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n for i in range(g):\n global_sf = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2[i].max()\n offsets[i] = acc_tokens\n blockscale_offsets[i] = rounded_acc_tokens\n acc_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_acc_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n scaled_mat2_i, bs_mat2_i = pytorch_nvfp4_quantize(mat2[i], global_sf)\n mat2_gs[i] = 1.0 / global_sf\n mat2_scaled[i] = scaled_mat2_i\n scale2[i] = linear_to_swizzled_128_4(bs_mat2_i)\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n alpha = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n problem_sizes = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n blockscale_offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n\n fp4_mat1, fp8_scale1 = fd.ops.nv_grouped_block_quantize(\n mat1, offsets, blockscale_offsets\n )\n\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n mat2,\n fp8_scale1,\n scale2,\n alpha,\n problem_sizes,\n offsets,\n blockscale_offsets,\n DataType.BFloat16,\n )\n fd.add_output(out)\n\n inputs = [\n mat1,\n mat2_scaled.view(torch.float4_e2m1fn_x2).transpose(-1, -2),\n scale2,\n mat2_gs,\n problem_sizes,\n offsets,\n blockscale_offsets,\n ]\n\n o, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n # quantization for activation is needed for reference.\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")\n mat1_fp4, scale1 = activation_scale_to_nvfp4(\n mat1, mat1_gs, offsets, blockscale_offsets, BLOCK_SIZE\n )\n o_decomposed_ref = torch.empty(m, n, dtype=torch.bfloat16, device=\"cuda:0\")\n for i in range(g):\n l = offsets[i]\n l_sf = blockscale_offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n r_sf = round_up(tokens_per_expert[i], 128) + l_sf\n # For some reason I cannot feed mat2_gs[i] as alpha in the torch kernel.\n # This triggers a cublas invalid value error.\n o_decomposed_ref[l:r] = (\n torch._scaled_mm(\n mat1_fp4[l:r],\n mat2_scaled[i].transpose(-1, -2),\n scale1[l_sf:r_sf],\n scale2[i],\n None,\n None,\n torch.bfloat16,\n )\n * mat2_gs[i]\n )\n\n # Validate: nvfuser quantization should match baseline\n abs_diff = torch.abs(o[0] - o_decomposed_ref)\n max_diff = torch.max(abs_diff)\n assert max_diff <= 10.0, f\"Max difference {max_diff:.4f} exceeds threshold of 10.0\"\n\n # Check that large differences (> 5.0) are rare (< 10% of elements)\n large_diff_count = torch.count_nonzero(torch.gt(abs_diff, 5.0))\n large_diff_ratio = large_diff_count / abs_diff.numel()\n assert (\n large_diff_ratio < 0.1\n ), f\"Large diff ratio {large_diff_ratio:.2%} exceeds 10% threshold\"","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.nvfuser_fusion_id0","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.nvfuser_fusion_id0#L887-L935","kind":"function","name":"nvfuser_fusion_id0","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":887,"end_line":935,"context_start_line":867,"context_end_line":955,"code":" (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n for i in range(g):\n global_sf = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2[i].max()\n offsets[i] = acc_tokens\n blockscale_offsets[i] = rounded_acc_tokens\n acc_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_acc_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n scaled_mat2_i, bs_mat2_i = pytorch_nvfp4_quantize(mat2[i], global_sf)\n mat2_gs[i] = 1.0 / global_sf\n mat2_scaled[i] = scaled_mat2_i\n scale2[i] = linear_to_swizzled_128_4(bs_mat2_i)\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n mat1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n )\n mat2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=True,\n dtype=DataType.Float8_e4m3fn,\n is_cpu=False,\n )\n alpha = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n problem_sizes = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n blockscale_offsets = fd.define_tensor(\n shape=[-1], contiguity=True, dtype=DataType.Int32, is_cpu=False\n )\n\n fp4_mat1, fp8_scale1 = fd.ops.nv_grouped_block_quantize(\n mat1, offsets, blockscale_offsets\n )\n\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n mat2,\n fp8_scale1,\n scale2,\n alpha,\n problem_sizes,\n offsets,\n blockscale_offsets,\n DataType.BFloat16,\n )\n fd.add_output(out)\n\n inputs = [\n mat1,\n mat2_scaled.view(torch.float4_e2m1fn_x2).transpose(-1, -2),\n scale2,\n mat2_gs,\n problem_sizes,\n offsets,\n blockscale_offsets,\n ]\n\n o, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n # quantization for activation is needed for reference.\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")\n mat1_fp4, scale1 = activation_scale_to_nvfp4(\n mat1, mat1_gs, offsets, blockscale_offsets, BLOCK_SIZE\n )\n o_decomposed_ref = torch.empty(m, n, dtype=torch.bfloat16, device=\"cuda:0\")","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.fusion_with_nv_block_quantize","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.fusion_with_nv_block_quantize#L360-L396","kind":"function","name":"fusion_with_nv_block_quantize","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":360,"end_line":396,"context_start_line":340,"context_end_line":416,"code":" mat1_ref = torch.testing.make_tensor((m, k), dtype=torch.float, device=\"cuda\")\n mat2_ref = torch.testing.make_tensor((n, k), dtype=torch.float, device=\"cuda\")\n\n # Quantize both matrices using Transformer Engine\n mat1_quantized, mat1_scale_inv, global_sf1 = extract_te_nvfp4_metadata(mat1_ref)\n mat2_quantized, mat2_scale_inv, global_sf2 = extract_te_nvfp4_metadata(mat2_ref)\n\n # Alpha compensates for both quantization scales\n alpha = 1.0 / (global_sf1 * global_sf2)\n\n # Prepare inputs for fusion with on-the-fly quantization\n inputs_with_quantize = [\n mat1_ref,\n mat2_quantized.t(),\n global_sf1,\n linear_to_swizzled_128_4(mat2_scale_inv),\n alpha,\n ]\n\n # Fusion 1: Quantize mat1 on-the-fly using nv_block_quantize\n def fusion_with_nv_block_quantize(fd: FusionDefinition) -> None:\n \"\"\"Defines fusion that quantizes mat1 on-the-fly before scaled_mm.\"\"\"\n mat1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n mat2_fp4 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[0, 1],\n )\n global_scale = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n alpha = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n\n # Quantize mat1 on-the-fly\n mat1_fp4, scale1 = fd.ops.nv_block_quantize(mat1, global_scale, True, 16)\n\n # Perform scaled matrix multiplication\n out, _, _ = fd.ops.scaled_mm(\n mat1_fp4,\n mat2_fp4,\n scale1,\n scale2,\n alpha,\n bias=None,\n beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_with_nv_block_quantize, inputs_with_quantize\n )\n\n # Fusion 2: Baseline using pre-quantized inputs\n inputs_baseline = [\n mat1_quantized,\n mat2_quantized.t(),\n linear_to_swizzled_128_4(mat1_scale_inv),\n linear_to_swizzled_128_4(mat2_scale_inv),\n alpha,\n ]\n\n def fusion_baseline(fd: FusionDefinition) -> None:\n \"\"\"Defines baseline fusion using pre-quantized inputs.\"\"\"\n mat1_fp4 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float4_e2m1fn, is_cpu=False\n )\n mat2_fp4 = fd.define_tensor(","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_narrow_precision.fusion_baseline","uri":"program://Fuser/function/tests.python.direct.test_narrow_precision.fusion_baseline#L411-L443","kind":"function","name":"fusion_baseline","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":411,"end_line":443,"context_start_line":391,"context_end_line":463,"code":" alpha,\n bias=None,\n beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_with_nv_block_quantize, inputs_with_quantize\n )\n\n # Fusion 2: Baseline using pre-quantized inputs\n inputs_baseline = [\n mat1_quantized,\n mat2_quantized.t(),\n linear_to_swizzled_128_4(mat1_scale_inv),\n linear_to_swizzled_128_4(mat2_scale_inv),\n alpha,\n ]\n\n def fusion_baseline(fd: FusionDefinition) -> None:\n \"\"\"Defines baseline fusion using pre-quantized inputs.\"\"\"\n mat1_fp4 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float4_e2m1fn, is_cpu=False\n )\n mat2_fp4 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float4_e2m1fn,\n is_cpu=False,\n stride_order=[0, 1],\n )\n scale1 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n scale2 = fd.define_tensor(\n shape=[-1, -1], contiguity=True, dtype=DataType.Float8_e4m3fn, is_cpu=False\n )\n alpha = fd.define_tensor(\n shape=[], contiguity=True, dtype=DataType.Float, is_cpu=False\n )\n\n out, _, _ = fd.ops.scaled_mm(\n mat1_fp4,\n mat2_fp4,\n scale1,\n scale2,\n alpha,\n bias=None,\n beta=None,\n dtype=torch_dtype_to_nvfuser_dtype(out_dtype),\n )\n fd.add_output(out)\n\n outputs_baseline, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_baseline,\n inputs_baseline,\n new_fusion_expected=None,\n )\n\n torch.testing.assert_close(outputs[0], outputs_baseline[0], atol=1e-2, rtol=1e-2)\n\n\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0), reason=\"Only supported on blackwell compute 10.0.\"\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16])\ndef test_cutlass_nvfp4_grouped_mm(\n nvfuser_direct_test,\n config,\n tokens_per_expert_neg_one,","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_alphafold3","uri":"program://Fuser/module/tests.python.direct.test_alphafold3#L1-L189","kind":"module","name":"tests.python.direct.test_alphafold3","path":"tests/python/direct/test_alphafold3.py","language":"python","start_line":1,"end_line":189,"context_start_line":1,"context_end_line":189,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\n# This file contains certain building blocks of the AlphaFold3 model.\n\nimport pytest\nimport torch\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\n\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4\n\n\n_DEFAULT_CONFIG = ModelConfig()\n\n\nclass Direction(Enum):\n INCOMING = auto() # aka ending node\n OUTGOING = auto() # aka starting node\n\n\n# `def test_triangle_updates` has been moved to tests/python/multidevice.\n\n\ndef layer_norm(\n fd: FusionDefinition, x: TensorView, w: TensorView, b: TensorView\n) -> TensorView:\n io_dtype = x.dtype()\n x = fd.ops.cast(x, dtype=DataType.Float)\n var, mean = fd.ops.var_mean(x, dims=[-1], correction=0, keepdim=True)\n y = fd.ops.sub(x, mean)\n var = fd.ops.add(var, fd.define_scalar(1e-5))\n y = fd.ops.mul(y, fd.ops.rsqrt(var))\n shape = fd.ops.shape(x)\n w = fd.ops.broadcast_in_dim(w, shape=shape, broadcast_dims=[-1])\n y = fd.ops.mul(y, w)\n b = fd.ops.broadcast_in_dim(b, shape=shape, broadcast_dims=[-1])\n y = fd.ops.add(y, b)\n y = fd.ops.cast(y, dtype=io_dtype)\n return y\n\n\n# https://elanapearl.github.io/blog/2024/the-illustrated-alphafold/#triangle-attention\n#\n# Jumper, J., Evans, R., Pritzel, A. et al. Highly accurate protein structure\n# prediction with AlphaFold. Nature 596, 583–589 (2021).\n# https://doi.org/10.1038/s41586-021-03819-2\n# (see Supplementary Methods 1.6.6 for details)\n@pytest.mark.parametrize(\n \"direction\", [Direction.OUTGOING, Direction.INCOMING], ids=lambda d: d.name.lower()\n)\ndef test_triangle_attention(direction):\n c_z, c_hidden, h = (\n _DEFAULT_CONFIG.c_z,\n _DEFAULT_CONFIG.c_hidden,\n _DEFAULT_CONFIG.n_heads,\n )\n\n with FusionDefinition() as fd:\n z_in = fd.define_tensor(\n shape=[-1, -1, -1, c_z],\n dtype=DataType.BFloat16,\n contiguity=True,\n ) # [b, i, j, c_z]\n w_norm = fd.define_tensor(shape=[c_z], dtype=DataType.BFloat16, contiguity=True)\n b_norm = fd.define_tensor(shape=[c_z], dtype=DataType.BFloat16, contiguity=True)\n w_q = fd.define_tensor(\n shape=[h * c_hidden, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_k = fd.define_tensor(\n shape=[h * c_hidden, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_b = fd.define_tensor(shape=[h, c_z], dtype=DataType.BFloat16, contiguity=True)\n mask = fd.define_tensor(\n shape=[-1, -1, -1], dtype=DataType.Bool, contiguity=True\n ) # [b, i, j]\n w_v = fd.define_tensor(\n shape=[h * c_hidden, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_g = fd.define_tensor(\n shape=[h * c_hidden, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_o = fd.define_tensor(\n shape=[c_z, h * c_hidden], dtype=DataType.BFloat16, contiguity=True\n )\n\n batch_size = fd.ops.size(z_in, 0)\n n_tokens = fd.ops.size(z_in, 1)\n\n if direction == Direction.INCOMING:\n z_in = fd.ops.permute(z_in, [0, 2, 1, 3])\n z_in = layer_norm(fd, z_in, w_norm, b_norm)\n q = fd.ops.linear(z_in, w_q)\n q_h = fd.ops.reshape(\n q, [batch_size, n_tokens, n_tokens, h, -1]\n ) # [b, i, j, h, c_hidden]\n q_h = fd.ops.permute(q_h, [0, 1, 3, 2, 4]) # [b, i, h, j, c_hidden]\n\n k = fd.ops.linear(z_in, w_k)\n k_h = fd.ops.reshape(\n k, [batch_size, n_tokens, n_tokens, h, -1]\n ) # [b, i, k, h, c_hidden]\n k_h = fd.ops.permute(k_h, [0, 1, 3, 2, 4]) # [b, i, h, k, c_hidden]\n\n b_h = fd.ops.linear(z_in, w_b) # [b, j, k, h]\n b_h = fd.ops.permute(b_h, [0, 3, 1, 2]) # [b, h, j, k]\n b_h = fd.ops.broadcast_in_dim(\n b_h,\n shape=[batch_size, 1, h, n_tokens, n_tokens],\n broadcast_dims=[0, 2, 3, 4],\n ) # [b, 1, h, j, k]\n\n if direction == Direction.INCOMING:\n mask = fd.ops.permute(mask, [0, 2, 1])\n mask = fd.ops.broadcast_in_dim(\n mask,\n shape=[batch_size, n_tokens, 1, 1, n_tokens],\n broadcast_dims=[0, 1, 4],\n ) # [b, i, 1, 1, k]\n\n v = fd.ops.linear(z_in, w_v)\n v_h = fd.ops.reshape(\n v, [batch_size, n_tokens, n_tokens, h, -1]\n ) # [b, i, k, h, c_hidden]\n v_h = fd.ops.permute(v_h, [0, 1, 3, 2, 4]) # [b, i, h, k, c_hidden]\n\n # k_h.T: [b, i, h, c_hidden, k]\n # attention_matrix: [b, i, h, j, k]\n o_h, _, _, _ = fd.ops.sdpfa_fwd(\n q_h, k_h, v_h, bias=b_h, mask=mask, is_causal=False\n ) # [b, i, h, j, c_hidden]\n\n g = fd.ops.linear(z_in, w_g)\n g = fd.ops.sigmoid(g)\n g_h = fd.ops.reshape(\n g, [batch_size, n_tokens, n_tokens, h, -1]\n ) # [b, i, j, h, c_hidden]\n g_h = fd.ops.permute(g_h, [0, 1, 3, 2, 4]) # [b, i, h, j, c_hidden]\n\n o_h = fd.ops.mul(o_h, g_h) # [b, i, h, j, c_hidden]\n o_h = fd.ops.cast(o_h, dtype=DataType.BFloat16)\n\n o = fd.ops.permute(o_h, [0, 1, 3, 2, 4]) # [b, i, j, h, c_hidden]\n o = fd.ops.reshape(\n o, [batch_size, n_tokens, n_tokens, -1]\n ) # [b, i, j, h * c_hidden]\n\n z_out = fd.ops.linear(o, w_o) # [b, i, j, c_z]\n if direction == Direction.INCOMING:\n z_out = fd.ops.permute(z_out, [0, 2, 1, 3])\n fd.add_output(z_out)\n\n batch_size = 3\n n_tokens = 5\n z_in = torch.testing.make_tensor(\n batch_size, n_tokens, n_tokens, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_norm = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n b_norm = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n w_q = torch.testing.make_tensor(\n h * c_hidden, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_k = torch.testing.make_tensor(\n h * c_hidden, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_b = torch.testing.make_tensor(h, c_z, dtype=torch.bfloat16, device=\"cuda\")\n mask = torch.testing.make_tensor(\n batch_size, n_tokens, n_tokens, dtype=torch.bool, device=\"cuda\"\n )\n w_v = torch.testing.make_tensor(\n h * c_hidden, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_g = torch.testing.make_tensor(\n h * c_hidden, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_o = torch.testing.make_tensor(\n c_z, h * c_hidden, dtype=torch.bfloat16, device=\"cuda\"\n )\n (z_out,) = fd.execute([z_in, w_norm, b_norm, w_q, w_k, w_b, mask, w_v, w_g, w_o])\n assert z_out.shape == (batch_size, n_tokens, n_tokens, c_z)","source_hash":"6a26821a82d11493f977f992f6869d6772e3eabfbe1ff3c78afc222d6674a7f3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_alphafold3.ModelConfig","uri":"program://Fuser/class/tests.python.direct.test_alphafold3.ModelConfig#L17-L20","kind":"class","name":"ModelConfig","path":"tests/python/direct/test_alphafold3.py","language":"python","start_line":17,"end_line":20,"context_start_line":1,"context_end_line":40,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\n# This file contains certain building blocks of the AlphaFold3 model.\n\nimport pytest\nimport torch\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\n\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4\n\n\n_DEFAULT_CONFIG = ModelConfig()\n\n\nclass Direction(Enum):\n INCOMING = auto() # aka ending node\n OUTGOING = auto() # aka starting node\n\n\n# `def test_triangle_updates` has been moved to tests/python/multidevice.\n\n\ndef layer_norm(\n fd: FusionDefinition, x: TensorView, w: TensorView, b: TensorView\n) -> TensorView:\n io_dtype = x.dtype()\n x = fd.ops.cast(x, dtype=DataType.Float)\n var, mean = fd.ops.var_mean(x, dims=[-1], correction=0, keepdim=True)\n y = fd.ops.sub(x, mean)","source_hash":"6a26821a82d11493f977f992f6869d6772e3eabfbe1ff3c78afc222d6674a7f3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_alphafold3.Direction","uri":"program://Fuser/class/tests.python.direct.test_alphafold3.Direction#L26-L28","kind":"class","name":"Direction","path":"tests/python/direct/test_alphafold3.py","language":"python","start_line":26,"end_line":28,"context_start_line":6,"context_end_line":48,"code":"# This file contains certain building blocks of the AlphaFold3 model.\n\nimport pytest\nimport torch\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\n\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4\n\n\n_DEFAULT_CONFIG = ModelConfig()\n\n\nclass Direction(Enum):\n INCOMING = auto() # aka ending node\n OUTGOING = auto() # aka starting node\n\n\n# `def test_triangle_updates` has been moved to tests/python/multidevice.\n\n\ndef layer_norm(\n fd: FusionDefinition, x: TensorView, w: TensorView, b: TensorView\n) -> TensorView:\n io_dtype = x.dtype()\n x = fd.ops.cast(x, dtype=DataType.Float)\n var, mean = fd.ops.var_mean(x, dims=[-1], correction=0, keepdim=True)\n y = fd.ops.sub(x, mean)\n var = fd.ops.add(var, fd.define_scalar(1e-5))\n y = fd.ops.mul(y, fd.ops.rsqrt(var))\n shape = fd.ops.shape(x)\n w = fd.ops.broadcast_in_dim(w, shape=shape, broadcast_dims=[-1])\n y = fd.ops.mul(y, w)\n b = fd.ops.broadcast_in_dim(b, shape=shape, broadcast_dims=[-1])\n y = fd.ops.add(y, b)\n y = fd.ops.cast(y, dtype=io_dtype)","source_hash":"6a26821a82d11493f977f992f6869d6772e3eabfbe1ff3c78afc222d6674a7f3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_alphafold3.layer_norm","uri":"program://Fuser/function/tests.python.direct.test_alphafold3.layer_norm#L34-L49","kind":"function","name":"layer_norm","path":"tests/python/direct/test_alphafold3.py","language":"python","start_line":34,"end_line":49,"context_start_line":14,"context_end_line":69,"code":"\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4\n\n\n_DEFAULT_CONFIG = ModelConfig()\n\n\nclass Direction(Enum):\n INCOMING = auto() # aka ending node\n OUTGOING = auto() # aka starting node\n\n\n# `def test_triangle_updates` has been moved to tests/python/multidevice.\n\n\ndef layer_norm(\n fd: FusionDefinition, x: TensorView, w: TensorView, b: TensorView\n) -> TensorView:\n io_dtype = x.dtype()\n x = fd.ops.cast(x, dtype=DataType.Float)\n var, mean = fd.ops.var_mean(x, dims=[-1], correction=0, keepdim=True)\n y = fd.ops.sub(x, mean)\n var = fd.ops.add(var, fd.define_scalar(1e-5))\n y = fd.ops.mul(y, fd.ops.rsqrt(var))\n shape = fd.ops.shape(x)\n w = fd.ops.broadcast_in_dim(w, shape=shape, broadcast_dims=[-1])\n y = fd.ops.mul(y, w)\n b = fd.ops.broadcast_in_dim(b, shape=shape, broadcast_dims=[-1])\n y = fd.ops.add(y, b)\n y = fd.ops.cast(y, dtype=io_dtype)\n return y\n\n\n# https://elanapearl.github.io/blog/2024/the-illustrated-alphafold/#triangle-attention\n#\n# Jumper, J., Evans, R., Pritzel, A. et al. Highly accurate protein structure\n# prediction with AlphaFold. Nature 596, 583–589 (2021).\n# https://doi.org/10.1038/s41586-021-03819-2\n# (see Supplementary Methods 1.6.6 for details)\n@pytest.mark.parametrize(\n \"direction\", [Direction.OUTGOING, Direction.INCOMING], ids=lambda d: d.name.lower()\n)\ndef test_triangle_attention(direction):\n c_z, c_hidden, h = (\n _DEFAULT_CONFIG.c_z,\n _DEFAULT_CONFIG.c_hidden,\n _DEFAULT_CONFIG.n_heads,\n )\n\n with FusionDefinition() as fd:\n z_in = fd.define_tensor(","source_hash":"6a26821a82d11493f977f992f6869d6772e3eabfbe1ff3c78afc222d6674a7f3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_alphafold3.test_triangle_attention","uri":"program://Fuser/function/tests.python.direct.test_alphafold3.test_triangle_attention#L61-L189","kind":"function","name":"test_triangle_attention","path":"tests/python/direct/test_alphafold3.py","language":"python","start_line":61,"end_line":189,"context_start_line":41,"context_end_line":189,"code":" var = fd.ops.add(var, fd.define_scalar(1e-5))\n y = fd.ops.mul(y, fd.ops.rsqrt(var))\n shape = fd.ops.shape(x)\n w = fd.ops.broadcast_in_dim(w, shape=shape, broadcast_dims=[-1])\n y = fd.ops.mul(y, w)\n b = fd.ops.broadcast_in_dim(b, shape=shape, broadcast_dims=[-1])\n y = fd.ops.add(y, b)\n y = fd.ops.cast(y, dtype=io_dtype)\n return y\n\n\n# https://elanapearl.github.io/blog/2024/the-illustrated-alphafold/#triangle-attention\n#\n# Jumper, J., Evans, R., Pritzel, A. et al. Highly accurate protein structure\n# prediction with AlphaFold. Nature 596, 583–589 (2021).\n# https://doi.org/10.1038/s41586-021-03819-2\n# (see Supplementary Methods 1.6.6 for details)\n@pytest.mark.parametrize(\n \"direction\", [Direction.OUTGOING, Direction.INCOMING], ids=lambda d: d.name.lower()\n)\ndef test_triangle_attention(direction):\n c_z, c_hidden, h = (\n _DEFAULT_CONFIG.c_z,\n _DEFAULT_CONFIG.c_hidden,\n _DEFAULT_CONFIG.n_heads,\n )\n\n with FusionDefinition() as fd:\n z_in = fd.define_tensor(\n shape=[-1, -1, -1, c_z],\n dtype=DataType.BFloat16,\n contiguity=True,\n ) # [b, i, j, c_z]\n w_norm = fd.define_tensor(shape=[c_z], dtype=DataType.BFloat16, contiguity=True)\n b_norm = fd.define_tensor(shape=[c_z], dtype=DataType.BFloat16, contiguity=True)\n w_q = fd.define_tensor(\n shape=[h * c_hidden, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_k = fd.define_tensor(\n shape=[h * c_hidden, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_b = fd.define_tensor(shape=[h, c_z], dtype=DataType.BFloat16, contiguity=True)\n mask = fd.define_tensor(\n shape=[-1, -1, -1], dtype=DataType.Bool, contiguity=True\n ) # [b, i, j]\n w_v = fd.define_tensor(\n shape=[h * c_hidden, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_g = fd.define_tensor(\n shape=[h * c_hidden, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_o = fd.define_tensor(\n shape=[c_z, h * c_hidden], dtype=DataType.BFloat16, contiguity=True\n )\n\n batch_size = fd.ops.size(z_in, 0)\n n_tokens = fd.ops.size(z_in, 1)\n\n if direction == Direction.INCOMING:\n z_in = fd.ops.permute(z_in, [0, 2, 1, 3])\n z_in = layer_norm(fd, z_in, w_norm, b_norm)\n q = fd.ops.linear(z_in, w_q)\n q_h = fd.ops.reshape(\n q, [batch_size, n_tokens, n_tokens, h, -1]\n ) # [b, i, j, h, c_hidden]\n q_h = fd.ops.permute(q_h, [0, 1, 3, 2, 4]) # [b, i, h, j, c_hidden]\n\n k = fd.ops.linear(z_in, w_k)\n k_h = fd.ops.reshape(\n k, [batch_size, n_tokens, n_tokens, h, -1]\n ) # [b, i, k, h, c_hidden]\n k_h = fd.ops.permute(k_h, [0, 1, 3, 2, 4]) # [b, i, h, k, c_hidden]\n\n b_h = fd.ops.linear(z_in, w_b) # [b, j, k, h]\n b_h = fd.ops.permute(b_h, [0, 3, 1, 2]) # [b, h, j, k]\n b_h = fd.ops.broadcast_in_dim(\n b_h,\n shape=[batch_size, 1, h, n_tokens, n_tokens],\n broadcast_dims=[0, 2, 3, 4],\n ) # [b, 1, h, j, k]\n\n if direction == Direction.INCOMING:\n mask = fd.ops.permute(mask, [0, 2, 1])\n mask = fd.ops.broadcast_in_dim(\n mask,\n shape=[batch_size, n_tokens, 1, 1, n_tokens],\n broadcast_dims=[0, 1, 4],\n ) # [b, i, 1, 1, k]\n\n v = fd.ops.linear(z_in, w_v)\n v_h = fd.ops.reshape(\n v, [batch_size, n_tokens, n_tokens, h, -1]\n ) # [b, i, k, h, c_hidden]\n v_h = fd.ops.permute(v_h, [0, 1, 3, 2, 4]) # [b, i, h, k, c_hidden]\n\n # k_h.T: [b, i, h, c_hidden, k]\n # attention_matrix: [b, i, h, j, k]\n o_h, _, _, _ = fd.ops.sdpfa_fwd(\n q_h, k_h, v_h, bias=b_h, mask=mask, is_causal=False\n ) # [b, i, h, j, c_hidden]\n\n g = fd.ops.linear(z_in, w_g)\n g = fd.ops.sigmoid(g)\n g_h = fd.ops.reshape(\n g, [batch_size, n_tokens, n_tokens, h, -1]\n ) # [b, i, j, h, c_hidden]\n g_h = fd.ops.permute(g_h, [0, 1, 3, 2, 4]) # [b, i, h, j, c_hidden]\n\n o_h = fd.ops.mul(o_h, g_h) # [b, i, h, j, c_hidden]\n o_h = fd.ops.cast(o_h, dtype=DataType.BFloat16)\n\n o = fd.ops.permute(o_h, [0, 1, 3, 2, 4]) # [b, i, j, h, c_hidden]\n o = fd.ops.reshape(\n o, [batch_size, n_tokens, n_tokens, -1]\n ) # [b, i, j, h * c_hidden]\n\n z_out = fd.ops.linear(o, w_o) # [b, i, j, c_z]\n if direction == Direction.INCOMING:\n z_out = fd.ops.permute(z_out, [0, 2, 1, 3])\n fd.add_output(z_out)\n\n batch_size = 3\n n_tokens = 5\n z_in = torch.testing.make_tensor(\n batch_size, n_tokens, n_tokens, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_norm = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n b_norm = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n w_q = torch.testing.make_tensor(\n h * c_hidden, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_k = torch.testing.make_tensor(\n h * c_hidden, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_b = torch.testing.make_tensor(h, c_z, dtype=torch.bfloat16, device=\"cuda\")\n mask = torch.testing.make_tensor(\n batch_size, n_tokens, n_tokens, dtype=torch.bool, device=\"cuda\"\n )\n w_v = torch.testing.make_tensor(\n h * c_hidden, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_g = torch.testing.make_tensor(\n h * c_hidden, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_o = torch.testing.make_tensor(\n c_z, h * c_hidden, dtype=torch.bfloat16, device=\"cuda\"\n )\n (z_out,) = fd.execute([z_in, w_norm, b_norm, w_q, w_k, w_b, mask, w_v, w_g, w_o])\n assert z_out.shape == (batch_size, n_tokens, n_tokens, c_z)","source_hash":"6a26821a82d11493f977f992f6869d6772e3eabfbe1ff3c78afc222d6674a7f3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro","uri":"program://Fuser/module/tests.python.direct.test_repro#L1-L4831","kind":"module","name":"tests.python.direct.test_repro","path":"tests/python/direct/test_repro.py","language":"python","start_line":1,"end_line":4831,"context_start_line":1,"context_end_line":4831,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom python.direct_utils import skip_if_global_memory_below_gb\n\n# Use smaller range for torch.testing.make_tensor for nvfuser_direct.validate\nLOW_VAL = -2\nHIGH_VAL = 2\n\n\ndef test_issue1129(nvfuser_direct_test):\n \"\"\"\n Test for issue 1129 - tests reshape and index_select operations with strided tensors.\n\n This test verifies that reshape and index_select operations work correctly\n with tensors that have non-standard strides, particularly when reshaping\n a tensor and then using it for index selection.\n \"\"\"\n inputs = [\n torch.randint(0, 10, (25,), dtype=torch.int64, device=\"cuda:0\").as_strided(\n (5, 5), (5, 1)\n ),\n torch.randn((129024,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2016, 64), (64, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Int,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S2 = fd.define_scalar(25, dtype=DataType.Int)\n T4 = fd.ops.reshape(T0, new_shape=[S2])\n T5 = fd.ops.index_select(T1, T4, dim=0)\n S6 = fd.define_scalar(5, dtype=DataType.Int)\n S7 = fd.define_scalar(5, dtype=DataType.Int)\n S8 = fd.define_scalar(64, dtype=DataType.Int)\n T10 = fd.ops.reshape(T5, new_shape=[S6, S7, S8])\n fd.add_output(T10)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = torch.reshape(\n torch.index_select(inputs[1], 0, torch.reshape(inputs[0], [25])), [5, 5, 64]\n )\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1246(nvfuser_direct_test):\n \"\"\"\n Test for issue 1246 - tests concatenation with empty tensors and strided tensors.\n\n This test verifies that concatenation operations work correctly with:\n - Strided tensors with non-standard memory layouts\n - Empty tensors (zero-sized dimensions)\n - Both with and without additional operations after concatenation\n \"\"\"\n inputs = [\n torch.randn((8388608,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 32, 2048, 128), (8388608, 262144, 128, 1)\n ),\n torch.randn((0,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 32, 2048, 0), (8388608, 262144, 128, 1)\n ),\n ]\n\n for final_mul in [False, True]:\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, -1, -1, -1],\n contiguity=[None, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, -1, -1, -1],\n contiguity=[None, True, False, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S2 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T3 = fd.ops.mul(T0, S2)\n T4 = fd.ops.cat([T3, T1], dim=-1)\n if final_mul:\n # NOTE: original repro does not have this final op\n S3 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T5 = fd.ops.mul(T4, S3)\n fd.add_output(T5)\n else:\n fd.add_output(T4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = torch.cat([2.0 * inputs[0], inputs[1]], dim=-1)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1270(nvfuser_direct_test):\n \"\"\"\n Test for issue 1270 - tests operations with empty tensors and dead code removal.\n\n This test verifies that operations work correctly with:\n - Empty tensors (zero-sized dimensions)\n - Dead code removal during fusion optimization\n - Complex operations involving casting, multiplication, and reduction\n - Proper handling of empty tensor operations that should not cause problems\n \"\"\"\n inputs = [\n torch.randn(0, device=\"cuda\", dtype=torch.bfloat16).as_strided((5, 0), (1, 0)),\n torch.randn(0, device=\"cuda\", dtype=torch.bfloat16).as_strided((5, 0), (0, 1)),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, None],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T2 = fd.ops.cast(T1, dtype=DataType.Float)\n S3 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T4 = fd.ops.full(fill_value=S3, shape=[5, 0], dtype=DataType.BFloat16)\n T5 = fd.ops.cast(T4, dtype=DataType.Float)\n T6 = fd.ops.mul(T2, T5)\n T7 = fd.ops.cast(T0, dtype=DataType.Float)\n T8 = fd.ops.mul(T7, T5)\n T24 = fd.ops.sum(T6, dims=[1], keepdim=False, dtype=DataType.Null)\n T11 = fd.ops.sum(T8, dims=[0], keepdim=False, dtype=DataType.Null)\n fd.add_output(T24)\n fd.add_output(T11)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n t2 = inputs[1].type(torch.float32)\n t4 = torch.full([5, 0], 1.0, dtype=torch.bfloat16, device=\"cuda\")\n t5 = t4.type(torch.float32)\n t6 = t2 * t5\n t7 = inputs[0].type(torch.float32)\n t8 = t7 * t5\n t24 = t6.sum([1])\n t11 = t8.sum([0])\n nvfuser_direct_test.assertEqual(nvf_out[0], t24)\n nvfuser_direct_test.assertEqual(nvf_out[1], t11)\n\n\ndef test_issue1273(nvfuser_direct_test):\n \"\"\"\n Test for issue 1273 - tests squeeze of dynamic input handling.\n\n This test verifies that squeeze operations work correctly with:\n - Dynamic input tensors with strided layouts\n - Complex operations involving reshape, var_mean, broadcast_in_dim\n - Layer normalization-like operations with variance and mean\n - Proper handling of tensor reshaping and broadcasting\n - Correct computation of normalization operations\n \"\"\"\n inputs = [\n torch.randn((4,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 2), (2, 1)\n ),\n 1e-05,\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S1 = fd.define_scalar(None, dtype=DataType.Double)\n T7 = fd.ops.reshape(T0, new_shape=[2, 1, 2])\n T8, T9 = fd.ops.var_mean(T7, dims=[2], correction=0, keepdim=False)\n T14 = fd.ops.broadcast_in_dim(T8, shape=[2, 1, 1], broadcast_dims=[0, 1])\n T19 = fd.ops.broadcast_in_dim(T9, shape=[2, 1, 1], broadcast_dims=[0, 1])\n T20 = fd.ops.add(T14, S1)\n T21 = fd.ops.rsqrt(T20)\n T26 = fd.ops.broadcast_in_dim(T19, shape=[2, 1, 2], broadcast_dims=[0, 1, 2])\n T27 = fd.ops.sub(T7, T26)\n T32 = fd.ops.broadcast_in_dim(T21, shape=[2, 1, 2], broadcast_dims=[0, 1, 2])\n T33 = fd.ops.mul(T27, T32)\n T37 = fd.ops.reshape(T33, new_shape=[2, 2])\n fd.add_output(T37)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n t7 = inputs[0].reshape((2, 1, 2))\n t8 = t7.var(dim=2, unbiased=False)\n t9 = t7.mean(dim=2)\n t27 = t7 - t9.unsqueeze(-1).expand((2, 1, 2))\n t32 = torch.rsqrt(inputs[1] + t8.unsqueeze(-1)).expand((2, 1, 2))\n torch_ref = (t27 * t32).reshape((2, 2))\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1277(nvfuser_direct_test):\n \"\"\"\n Test for issue 1277 - tests complex operations with strided tensors and slicing.\n\n This test verifies that complex operations work correctly with:\n - Multiple strided tensors with complex memory layouts\n - Extensive slicing operations with different indices\n - Padding operations with various configurations\n - Permutation and arithmetic operations\n - Complex tensor manipulation sequences\n - Proper handling of resized extents and expression simplification\n \"\"\"\n inputs = [\n 0.5,\n 0.5,\n torch.randn((20,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 4), (0, 0, 4, 1)\n ),\n torch.randn((20,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 4), (0, 0, 4, 1)\n ),\n torch.randn((20,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 4), (0, 0, 4, 1)\n ),\n torch.randn((20,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 4), (0, 0, 4, 1)\n ),\n torch.randn((1600,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 16), (320, 80, 16, 1)\n ),\n torch.randn((1600,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 16, 5), (320, 80, 5, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Double)\n S1 = fd.define_scalar(None, dtype=DataType.Double)\n T2 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T3 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T4 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T5 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T6 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T7 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T8 = fd.ops.mul(T6, S0)\n T9 = fd.ops.slice(\n T8,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 4],\n strides=[1, 1, 1, 1],\n )\n T10 = fd.ops.slice(\n T8,\n start_indices=[0, 0, 0, 4],\n end_indices=[5, 4, 5, 16],\n strides=[1, 1, 1, 1],\n )\n S11 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T12 = fd.ops.pad(T10, [4, 0, 0, 0, 0, 0, 0, 0], S11)\n S13 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T14 = fd.ops.mul(S13, T9)\n S15 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T16 = fd.ops.mul(S15, T9)\n T17 = fd.ops.mul(T16, T3)\n T18 = fd.ops.mul(T14, T2)\n T19 = fd.ops.slice(\n T17,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 2],\n strides=[1, 1, 1, 1],\n )\n T20 = fd.ops.slice(\n T17,\n start_indices=[0, 0, 0, 2],\n end_indices=[5, 4, 5, 4],\n strides=[1, 1, 1, 1],\n )\n T21 = fd.ops.neg(T19)\n S22 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T23 = fd.ops.pad(T21, [2, 0, 0, 0, 0, 0, 0, 0], S22)\n T24 = fd.ops.add(T18, T23)\n S25 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T26 = fd.ops.pad(T20, [0, 2, 0, 0, 0, 0, 0, 0], S25)\n T27 = fd.ops.add(T24, T26)\n S28 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T29 = fd.ops.pad(T27, [0, 12, 0, 0, 0, 0, 0, 0], S28)\n T30 = fd.ops.add(T12, T29)\n T31 = fd.ops.mul(T7, S1)\n T32 = fd.ops.permute(T31, dims=[0, 1, 3, 2])\n T33 = fd.ops.slice(\n T32,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 4],\n strides=[1, 1, 1, 1],\n )\n T34 = fd.ops.slice(\n T32,\n start_indices=[0, 0, 0, 4],\n end_indices=[5, 4, 5, 16],\n strides=[1, 1, 1, 1],\n )\n S35 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T36 = fd.ops.pad(T34, [4, 0, 0, 0, 0, 0, 0, 0], S35)\n S37 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T38 = fd.ops.mul(S37, T33)\n S39 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T40 = fd.ops.mul(S39, T33)\n T41 = fd.ops.mul(T40, T5)\n T42 = fd.ops.mul(T38, T4)\n T43 = fd.ops.slice(\n T41,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 2],\n strides=[1, 1, 1, 1],\n )\n T44 = fd.ops.slice(\n T41,\n start_indices=[0, 0, 0, 2],\n end_indices=[5, 4, 5, 4],\n strides=[1, 1, 1, 1],\n )\n T45 = fd.ops.neg(T43)\n S46 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T47 = fd.ops.pad(T45, [2, 0, 0, 0, 0, 0, 0, 0], S46)\n T48 = fd.ops.add(T42, T47)\n S49 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T50 = fd.ops.pad(T44, [0, 2, 0, 0, 0, 0, 0, 0], S49)\n T51 = fd.ops.add(T48, T50)\n S52 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T53 = fd.ops.pad(T51, [0, 12, 0, 0, 0, 0, 0, 0], S52)\n T54 = fd.ops.add(T36, T53)\n fd.add_output(T54)\n fd.add_output(T30)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_issue1279(nvfuser_direct_test):\n \"\"\"\n Test for issue 1279 - tests var_mean operations with casting.\n\n This test verifies that var_mean operations work correctly with:\n - Half-precision (float16) input tensors\n - Casting operations between different data types\n - Variance and mean computation with correction\n - correction is 0 because reduction dimension is 1, which can cause\n division by zero.\n - Proper handling of dimension reduction\n - Multiple output tensors from var_mean operation\n \"\"\"\n inputs = [\n torch.randn(2, 1, 2, dtype=torch.float16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1, -1],\n contiguity=[True, None, True],\n dtype=DataType.Half,\n is_cpu=False,\n )\n T4 = fd.ops.cast(T0, dtype=DataType.Float)\n T5, T6 = fd.ops.var_mean(T4, dims=[1], correction=0, keepdim=False)\n T7 = fd.ops.cast(T5, dtype=DataType.Half)\n T8 = fd.ops.cast(T6, dtype=DataType.Half)\n fd.add_output(T7)\n fd.add_output(T8)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n a = inputs[0].type(torch.float32)\n b, c = torch.var_mean(a, dim=1, correction=0)\n d = b.type(torch.float16)\n e = c.type(torch.float16)\n\n nvfuser_direct_test.assertEqual(nvf_out[0], d)\n nvfuser_direct_test.assertEqual(nvf_out[1], e)\n\n\ndef test_issue1310(nvfuser_direct_test):\n \"\"\"\n Test for issue 1310 - tests input forwarding with multiple UnaryOps.\n\n This test verifies that inputs are properly forwarded when an input is used in multiple\n UnaryOps, some having one and others having multiple further uses:\n - Multiple cast operations on the same input tensor\n - Different reduction operations on cast results\n - Proper handling of tensor aliasing and forwarding\n - Correct computation of multiple reduction operations\n \"\"\"\n inputs = [torch.randn((16, 128, 768), dtype=torch.bfloat16, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T3 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T14 = fd.ops.cast(\n T3, dtype=DataType.Float\n ) # NOTE that RHS is same, but the result is assigned to different variables\n T15 = fd.ops.cast(\n T3, dtype=DataType.Float\n ) # NOTE that RHS is same, but the result is assigned to different variables\n T16 = fd.ops.sum(T15, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T20 = fd.ops.sum(T14, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T31 = fd.ops.sum(T14, dims=[2], keepdim=False, dtype=DataType.Null)\n fd.add_output(T16)\n fd.add_output(T20)\n fd.add_output(T31)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n t14 = inputs[0].type(torch.float32)\n t16 = t14.sum([0, 1])\n t31 = t14.sum([2])\n nvfuser_direct_test.assertEqual(nvf_out[0], t16)\n nvfuser_direct_test.assertEqual(nvf_out[1], t16) # T16 == T20\n nvfuser_direct_test.assertEqual(nvf_out[2], t31)\n\n\ndef test_issue1393(nvfuser_direct_test):\n \"\"\"\n Test for issue 1393 - tests complex operations with strided tensors and broadcasting.\n\n This test verifies that complex operations work correctly with:\n - Strided tensors with non-standard memory layouts\n - Casting operations between different data types\n - Multiplication and reshape operations\n - Broadcast_in_dim operations with explicit dimensions\n - Complex tensor manipulation sequences\n - Proper handling of tensor contiguity and strides\n \"\"\"\n inputs = [\n torch.randn((5,), dtype=torch.float16, device=\"cuda:0\").as_strided(\n (3, 4, 5), (0, 0, 1)\n ),\n torch.randn((3,), dtype=torch.float16, device=\"cuda:0\").as_strided(\n (3, 4), (1, 0)\n ),\n torch.randn((4,), dtype=torch.float16, device=\"cuda:0\").as_strided(\n (3, 4), (0, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[None, None, True],\n dtype=DataType.Half,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, None],\n dtype=DataType.Half,\n is_cpu=False,\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[None, True],\n dtype=DataType.Half,\n is_cpu=False,\n )\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.cast(T2, dtype=DataType.Float)\n T5 = fd.ops.mul(T3, T4)\n T6 = fd.ops.cast(T5, dtype=DataType.Half)\n S7 = fd.define_scalar(3, dtype=DataType.Int)\n S8 = fd.define_scalar(4, dtype=DataType.Int)\n S9 = fd.define_scalar(1, dtype=DataType.Int)\n T11 = fd.ops.reshape(T6, new_shape=[S7, S8, S9])\n S12 = fd.define_scalar(3, dtype=DataType.Int)\n S13 = fd.define_scalar(4, dtype=DataType.Int)\n S14 = fd.define_scalar(5, dtype=DataType.Int)\n T16 = fd.ops.broadcast_in_dim(\n T11, shape=[S12, S13, S14], broadcast_dims=[0, 1, 2]\n )\n T17 = fd.ops.cast(T16, dtype=DataType.Float)\n T18 = fd.ops.cast(T0, dtype=DataType.Float)\n T19 = fd.ops.mul(T17, T18)\n T20 = fd.ops.cast(T19, dtype=DataType.Half)\n fd.add_output(T20)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = inputs[0] * (inputs[1] * inputs[2]).unsqueeze(-1)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1691(nvfuser_direct_test):\n \"\"\"\n Test for issue 1691 - tests complex reduction operations with reshape and multiplication.\n\n This test verifies that complex reduction operations work correc\n# ... truncated ...","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1129","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1129#L16-L59","kind":"function","name":"test_issue1129","path":"tests/python/direct/test_repro.py","language":"python","start_line":16,"end_line":59,"context_start_line":1,"context_end_line":79,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom python.direct_utils import skip_if_global_memory_below_gb\n\n# Use smaller range for torch.testing.make_tensor for nvfuser_direct.validate\nLOW_VAL = -2\nHIGH_VAL = 2\n\n\ndef test_issue1129(nvfuser_direct_test):\n \"\"\"\n Test for issue 1129 - tests reshape and index_select operations with strided tensors.\n\n This test verifies that reshape and index_select operations work correctly\n with tensors that have non-standard strides, particularly when reshaping\n a tensor and then using it for index selection.\n \"\"\"\n inputs = [\n torch.randint(0, 10, (25,), dtype=torch.int64, device=\"cuda:0\").as_strided(\n (5, 5), (5, 1)\n ),\n torch.randn((129024,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2016, 64), (64, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Int,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S2 = fd.define_scalar(25, dtype=DataType.Int)\n T4 = fd.ops.reshape(T0, new_shape=[S2])\n T5 = fd.ops.index_select(T1, T4, dim=0)\n S6 = fd.define_scalar(5, dtype=DataType.Int)\n S7 = fd.define_scalar(5, dtype=DataType.Int)\n S8 = fd.define_scalar(64, dtype=DataType.Int)\n T10 = fd.ops.reshape(T5, new_shape=[S6, S7, S8])\n fd.add_output(T10)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = torch.reshape(\n torch.index_select(inputs[1], 0, torch.reshape(inputs[0], [25])), [5, 5, 64]\n )\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1246(nvfuser_direct_test):\n \"\"\"\n Test for issue 1246 - tests concatenation with empty tensors and strided tensors.\n\n This test verifies that concatenation operations work correctly with:\n - Strided tensors with non-standard memory layouts\n - Empty tensors (zero-sized dimensions)\n - Both with and without additional operations after concatenation\n \"\"\"\n inputs = [\n torch.randn((8388608,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 32, 2048, 128), (8388608, 262144, 128, 1)\n ),\n torch.randn((0,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 32, 2048, 0), (8388608, 262144, 128, 1)\n ),\n ]\n","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1246","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1246#L62-L108","kind":"function","name":"test_issue1246","path":"tests/python/direct/test_repro.py","language":"python","start_line":62,"end_line":108,"context_start_line":42,"context_end_line":128,"code":" contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S2 = fd.define_scalar(25, dtype=DataType.Int)\n T4 = fd.ops.reshape(T0, new_shape=[S2])\n T5 = fd.ops.index_select(T1, T4, dim=0)\n S6 = fd.define_scalar(5, dtype=DataType.Int)\n S7 = fd.define_scalar(5, dtype=DataType.Int)\n S8 = fd.define_scalar(64, dtype=DataType.Int)\n T10 = fd.ops.reshape(T5, new_shape=[S6, S7, S8])\n fd.add_output(T10)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = torch.reshape(\n torch.index_select(inputs[1], 0, torch.reshape(inputs[0], [25])), [5, 5, 64]\n )\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1246(nvfuser_direct_test):\n \"\"\"\n Test for issue 1246 - tests concatenation with empty tensors and strided tensors.\n\n This test verifies that concatenation operations work correctly with:\n - Strided tensors with non-standard memory layouts\n - Empty tensors (zero-sized dimensions)\n - Both with and without additional operations after concatenation\n \"\"\"\n inputs = [\n torch.randn((8388608,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 32, 2048, 128), (8388608, 262144, 128, 1)\n ),\n torch.randn((0,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 32, 2048, 0), (8388608, 262144, 128, 1)\n ),\n ]\n\n for final_mul in [False, True]:\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, -1, -1, -1],\n contiguity=[None, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, -1, -1, -1],\n contiguity=[None, True, False, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S2 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T3 = fd.ops.mul(T0, S2)\n T4 = fd.ops.cat([T3, T1], dim=-1)\n if final_mul:\n # NOTE: original repro does not have this final op\n S3 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T5 = fd.ops.mul(T4, S3)\n fd.add_output(T5)\n else:\n fd.add_output(T4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = torch.cat([2.0 * inputs[0], inputs[1]], dim=-1)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1270(nvfuser_direct_test):\n \"\"\"\n Test for issue 1270 - tests operations with empty tensors and dead code removal.\n\n This test verifies that operations work correctly with:\n - Empty tensors (zero-sized dimensions)\n - Dead code removal during fusion optimization\n - Complex operations involving casting, multiplication, and reduction\n - Proper handling of empty tensor operations that should not cause problems\n \"\"\"\n inputs = [\n torch.randn(0, device=\"cuda\", dtype=torch.bfloat16).as_strided((5, 0), (1, 0)),\n torch.randn(0, device=\"cuda\", dtype=torch.bfloat16).as_strided((5, 0), (0, 1)),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1270","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1270#L111-L161","kind":"function","name":"test_issue1270","path":"tests/python/direct/test_repro.py","language":"python","start_line":111,"end_line":161,"context_start_line":91,"context_end_line":181,"code":" contiguity=[None, True, False, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S2 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T3 = fd.ops.mul(T0, S2)\n T4 = fd.ops.cat([T3, T1], dim=-1)\n if final_mul:\n # NOTE: original repro does not have this final op\n S3 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T5 = fd.ops.mul(T4, S3)\n fd.add_output(T5)\n else:\n fd.add_output(T4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = torch.cat([2.0 * inputs[0], inputs[1]], dim=-1)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1270(nvfuser_direct_test):\n \"\"\"\n Test for issue 1270 - tests operations with empty tensors and dead code removal.\n\n This test verifies that operations work correctly with:\n - Empty tensors (zero-sized dimensions)\n - Dead code removal during fusion optimization\n - Complex operations involving casting, multiplication, and reduction\n - Proper handling of empty tensor operations that should not cause problems\n \"\"\"\n inputs = [\n torch.randn(0, device=\"cuda\", dtype=torch.bfloat16).as_strided((5, 0), (1, 0)),\n torch.randn(0, device=\"cuda\", dtype=torch.bfloat16).as_strided((5, 0), (0, 1)),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, None],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T2 = fd.ops.cast(T1, dtype=DataType.Float)\n S3 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T4 = fd.ops.full(fill_value=S3, shape=[5, 0], dtype=DataType.BFloat16)\n T5 = fd.ops.cast(T4, dtype=DataType.Float)\n T6 = fd.ops.mul(T2, T5)\n T7 = fd.ops.cast(T0, dtype=DataType.Float)\n T8 = fd.ops.mul(T7, T5)\n T24 = fd.ops.sum(T6, dims=[1], keepdim=False, dtype=DataType.Null)\n T11 = fd.ops.sum(T8, dims=[0], keepdim=False, dtype=DataType.Null)\n fd.add_output(T24)\n fd.add_output(T11)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n t2 = inputs[1].type(torch.float32)\n t4 = torch.full([5, 0], 1.0, dtype=torch.bfloat16, device=\"cuda\")\n t5 = t4.type(torch.float32)\n t6 = t2 * t5\n t7 = inputs[0].type(torch.float32)\n t8 = t7 * t5\n t24 = t6.sum([1])\n t11 = t8.sum([0])\n nvfuser_direct_test.assertEqual(nvf_out[0], t24)\n nvfuser_direct_test.assertEqual(nvf_out[1], t11)\n\n\ndef test_issue1273(nvfuser_direct_test):\n \"\"\"\n Test for issue 1273 - tests squeeze of dynamic input handling.\n\n This test verifies that squeeze operations work correctly with:\n - Dynamic input tensors with strided layouts\n - Complex operations involving reshape, var_mean, broadcast_in_dim\n - Layer normalization-like operations with variance and mean\n - Proper handling of tensor reshaping and broadcasting\n - Correct computation of normalization operations\n \"\"\"\n inputs = [\n torch.randn((4,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 2), (2, 1)\n ),\n 1e-05,\n ]\n","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1273","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1273#L164-L210","kind":"function","name":"test_issue1273","path":"tests/python/direct/test_repro.py","language":"python","start_line":164,"end_line":210,"context_start_line":144,"context_end_line":230,"code":" T7 = fd.ops.cast(T0, dtype=DataType.Float)\n T8 = fd.ops.mul(T7, T5)\n T24 = fd.ops.sum(T6, dims=[1], keepdim=False, dtype=DataType.Null)\n T11 = fd.ops.sum(T8, dims=[0], keepdim=False, dtype=DataType.Null)\n fd.add_output(T24)\n fd.add_output(T11)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n t2 = inputs[1].type(torch.float32)\n t4 = torch.full([5, 0], 1.0, dtype=torch.bfloat16, device=\"cuda\")\n t5 = t4.type(torch.float32)\n t6 = t2 * t5\n t7 = inputs[0].type(torch.float32)\n t8 = t7 * t5\n t24 = t6.sum([1])\n t11 = t8.sum([0])\n nvfuser_direct_test.assertEqual(nvf_out[0], t24)\n nvfuser_direct_test.assertEqual(nvf_out[1], t11)\n\n\ndef test_issue1273(nvfuser_direct_test):\n \"\"\"\n Test for issue 1273 - tests squeeze of dynamic input handling.\n\n This test verifies that squeeze operations work correctly with:\n - Dynamic input tensors with strided layouts\n - Complex operations involving reshape, var_mean, broadcast_in_dim\n - Layer normalization-like operations with variance and mean\n - Proper handling of tensor reshaping and broadcasting\n - Correct computation of normalization operations\n \"\"\"\n inputs = [\n torch.randn((4,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 2), (2, 1)\n ),\n 1e-05,\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S1 = fd.define_scalar(None, dtype=DataType.Double)\n T7 = fd.ops.reshape(T0, new_shape=[2, 1, 2])\n T8, T9 = fd.ops.var_mean(T7, dims=[2], correction=0, keepdim=False)\n T14 = fd.ops.broadcast_in_dim(T8, shape=[2, 1, 1], broadcast_dims=[0, 1])\n T19 = fd.ops.broadcast_in_dim(T9, shape=[2, 1, 1], broadcast_dims=[0, 1])\n T20 = fd.ops.add(T14, S1)\n T21 = fd.ops.rsqrt(T20)\n T26 = fd.ops.broadcast_in_dim(T19, shape=[2, 1, 2], broadcast_dims=[0, 1, 2])\n T27 = fd.ops.sub(T7, T26)\n T32 = fd.ops.broadcast_in_dim(T21, shape=[2, 1, 2], broadcast_dims=[0, 1, 2])\n T33 = fd.ops.mul(T27, T32)\n T37 = fd.ops.reshape(T33, new_shape=[2, 2])\n fd.add_output(T37)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n t7 = inputs[0].reshape((2, 1, 2))\n t8 = t7.var(dim=2, unbiased=False)\n t9 = t7.mean(dim=2)\n t27 = t7 - t9.unsqueeze(-1).expand((2, 1, 2))\n t32 = torch.rsqrt(inputs[1] + t8.unsqueeze(-1)).expand((2, 1, 2))\n torch_ref = (t27 * t32).reshape((2, 2))\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1277(nvfuser_direct_test):\n \"\"\"\n Test for issue 1277 - tests complex operations with strided tensors and slicing.\n\n This test verifies that complex operations work correctly with:\n - Multiple strided tensors with complex memory layouts\n - Extensive slicing operations with different indices\n - Padding operations with various configurations\n - Permutation and arithmetic operations\n - Complex tensor manipulation sequences\n - Proper handling of resized extents and expression simplification\n \"\"\"\n inputs = [\n 0.5,\n 0.5,\n torch.randn((20,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 4), (0, 0, 4, 1)\n ),","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1277","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1277#L213-L377","kind":"function","name":"test_issue1277","path":"tests/python/direct/test_repro.py","language":"python","start_line":213,"end_line":377,"context_start_line":193,"context_end_line":397,"code":" T19 = fd.ops.broadcast_in_dim(T9, shape=[2, 1, 1], broadcast_dims=[0, 1])\n T20 = fd.ops.add(T14, S1)\n T21 = fd.ops.rsqrt(T20)\n T26 = fd.ops.broadcast_in_dim(T19, shape=[2, 1, 2], broadcast_dims=[0, 1, 2])\n T27 = fd.ops.sub(T7, T26)\n T32 = fd.ops.broadcast_in_dim(T21, shape=[2, 1, 2], broadcast_dims=[0, 1, 2])\n T33 = fd.ops.mul(T27, T32)\n T37 = fd.ops.reshape(T33, new_shape=[2, 2])\n fd.add_output(T37)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n t7 = inputs[0].reshape((2, 1, 2))\n t8 = t7.var(dim=2, unbiased=False)\n t9 = t7.mean(dim=2)\n t27 = t7 - t9.unsqueeze(-1).expand((2, 1, 2))\n t32 = torch.rsqrt(inputs[1] + t8.unsqueeze(-1)).expand((2, 1, 2))\n torch_ref = (t27 * t32).reshape((2, 2))\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1277(nvfuser_direct_test):\n \"\"\"\n Test for issue 1277 - tests complex operations with strided tensors and slicing.\n\n This test verifies that complex operations work correctly with:\n - Multiple strided tensors with complex memory layouts\n - Extensive slicing operations with different indices\n - Padding operations with various configurations\n - Permutation and arithmetic operations\n - Complex tensor manipulation sequences\n - Proper handling of resized extents and expression simplification\n \"\"\"\n inputs = [\n 0.5,\n 0.5,\n torch.randn((20,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 4), (0, 0, 4, 1)\n ),\n torch.randn((20,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 4), (0, 0, 4, 1)\n ),\n torch.randn((20,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 4), (0, 0, 4, 1)\n ),\n torch.randn((20,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 4), (0, 0, 4, 1)\n ),\n torch.randn((1600,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 5, 16), (320, 80, 16, 1)\n ),\n torch.randn((1600,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (5, 4, 16, 5), (320, 80, 5, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Double)\n S1 = fd.define_scalar(None, dtype=DataType.Double)\n T2 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T3 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T4 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T5 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T6 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T7 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T8 = fd.ops.mul(T6, S0)\n T9 = fd.ops.slice(\n T8,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 4],\n strides=[1, 1, 1, 1],\n )\n T10 = fd.ops.slice(\n T8,\n start_indices=[0, 0, 0, 4],\n end_indices=[5, 4, 5, 16],\n strides=[1, 1, 1, 1],\n )\n S11 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T12 = fd.ops.pad(T10, [4, 0, 0, 0, 0, 0, 0, 0], S11)\n S13 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T14 = fd.ops.mul(S13, T9)\n S15 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T16 = fd.ops.mul(S15, T9)\n T17 = fd.ops.mul(T16, T3)\n T18 = fd.ops.mul(T14, T2)\n T19 = fd.ops.slice(\n T17,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 2],\n strides=[1, 1, 1, 1],\n )\n T20 = fd.ops.slice(\n T17,\n start_indices=[0, 0, 0, 2],\n end_indices=[5, 4, 5, 4],\n strides=[1, 1, 1, 1],\n )\n T21 = fd.ops.neg(T19)\n S22 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T23 = fd.ops.pad(T21, [2, 0, 0, 0, 0, 0, 0, 0], S22)\n T24 = fd.ops.add(T18, T23)\n S25 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T26 = fd.ops.pad(T20, [0, 2, 0, 0, 0, 0, 0, 0], S25)\n T27 = fd.ops.add(T24, T26)\n S28 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T29 = fd.ops.pad(T27, [0, 12, 0, 0, 0, 0, 0, 0], S28)\n T30 = fd.ops.add(T12, T29)\n T31 = fd.ops.mul(T7, S1)\n T32 = fd.ops.permute(T31, dims=[0, 1, 3, 2])\n T33 = fd.ops.slice(\n T32,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 4],\n strides=[1, 1, 1, 1],\n )\n T34 = fd.ops.slice(\n T32,\n start_indices=[0, 0, 0, 4],\n end_indices=[5, 4, 5, 16],\n strides=[1, 1, 1, 1],\n )\n S35 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T36 = fd.ops.pad(T34, [4, 0, 0, 0, 0, 0, 0, 0], S35)\n S37 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T38 = fd.ops.mul(S37, T33)\n S39 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T40 = fd.ops.mul(S39, T33)\n T41 = fd.ops.mul(T40, T5)\n T42 = fd.ops.mul(T38, T4)\n T43 = fd.ops.slice(\n T41,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 2],\n strides=[1, 1, 1, 1],\n )\n T44 = fd.ops.slice(\n T41,\n start_indices=[0, 0, 0, 2],\n end_indices=[5, 4, 5, 4],\n strides=[1, 1, 1, 1],\n )\n T45 = fd.ops.neg(T43)\n S46 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T47 = fd.ops.pad(T45, [2, 0, 0, 0, 0, 0, 0, 0], S46)\n T48 = fd.ops.add(T42, T47)\n S49 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T50 = fd.ops.pad(T44, [0, 2, 0, 0, 0, 0, 0, 0], S49)\n T51 = fd.ops.add(T48, T50)\n S52 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T53 = fd.ops.pad(T51, [0, 12, 0, 0, 0, 0, 0, 0], S52)\n T54 = fd.ops.add(T36, T53)\n fd.add_output(T54)\n fd.add_output(T30)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_issue1279(nvfuser_direct_test):\n \"\"\"\n Test for issue 1279 - tests var_mean operations with casting.\n\n This test verifies that var_mean operations work correctly with:\n - Half-precision (float16) input tensors\n - Casting operations between different data types\n - Variance and mean computation with correction\n - correction is 0 because reduction dimension is 1, which can cause\n division by zero.\n - Proper handling of dimension reduction\n - Multiple output tensors from var_mean operation\n \"\"\"\n inputs = [\n torch.randn(2, 1, 2, dtype=torch.float16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1279","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1279#L380-L419","kind":"function","name":"test_issue1279","path":"tests/python/direct/test_repro.py","language":"python","start_line":380,"end_line":419,"context_start_line":360,"context_end_line":439,"code":" start_indices=[0, 0, 0, 2],\n end_indices=[5, 4, 5, 4],\n strides=[1, 1, 1, 1],\n )\n T45 = fd.ops.neg(T43)\n S46 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T47 = fd.ops.pad(T45, [2, 0, 0, 0, 0, 0, 0, 0], S46)\n T48 = fd.ops.add(T42, T47)\n S49 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T50 = fd.ops.pad(T44, [0, 2, 0, 0, 0, 0, 0, 0], S49)\n T51 = fd.ops.add(T48, T50)\n S52 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T53 = fd.ops.pad(T51, [0, 12, 0, 0, 0, 0, 0, 0], S52)\n T54 = fd.ops.add(T36, T53)\n fd.add_output(T54)\n fd.add_output(T30)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_issue1279(nvfuser_direct_test):\n \"\"\"\n Test for issue 1279 - tests var_mean operations with casting.\n\n This test verifies that var_mean operations work correctly with:\n - Half-precision (float16) input tensors\n - Casting operations between different data types\n - Variance and mean computation with correction\n - correction is 0 because reduction dimension is 1, which can cause\n division by zero.\n - Proper handling of dimension reduction\n - Multiple output tensors from var_mean operation\n \"\"\"\n inputs = [\n torch.randn(2, 1, 2, dtype=torch.float16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1, -1],\n contiguity=[True, None, True],\n dtype=DataType.Half,\n is_cpu=False,\n )\n T4 = fd.ops.cast(T0, dtype=DataType.Float)\n T5, T6 = fd.ops.var_mean(T4, dims=[1], correction=0, keepdim=False)\n T7 = fd.ops.cast(T5, dtype=DataType.Half)\n T8 = fd.ops.cast(T6, dtype=DataType.Half)\n fd.add_output(T7)\n fd.add_output(T8)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n a = inputs[0].type(torch.float32)\n b, c = torch.var_mean(a, dim=1, correction=0)\n d = b.type(torch.float16)\n e = c.type(torch.float16)\n\n nvfuser_direct_test.assertEqual(nvf_out[0], d)\n nvfuser_direct_test.assertEqual(nvf_out[1], e)\n\n\ndef test_issue1310(nvfuser_direct_test):\n \"\"\"\n Test for issue 1310 - tests input forwarding with multiple UnaryOps.\n\n This test verifies that inputs are properly forwarded when an input is used in multiple\n UnaryOps, some having one and others having multiple further uses:\n - Multiple cast operations on the same input tensor\n - Different reduction operations on cast results\n - Proper handling of tensor aliasing and forwarding\n - Correct computation of multiple reduction operations\n \"\"\"\n inputs = [torch.randn((16, 128, 768), dtype=torch.bfloat16, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T3 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.BFloat16,","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1310","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1310#L422-L461","kind":"function","name":"test_issue1310","path":"tests/python/direct/test_repro.py","language":"python","start_line":422,"end_line":461,"context_start_line":402,"context_end_line":481,"code":" is_cpu=False,\n )\n T4 = fd.ops.cast(T0, dtype=DataType.Float)\n T5, T6 = fd.ops.var_mean(T4, dims=[1], correction=0, keepdim=False)\n T7 = fd.ops.cast(T5, dtype=DataType.Half)\n T8 = fd.ops.cast(T6, dtype=DataType.Half)\n fd.add_output(T7)\n fd.add_output(T8)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n a = inputs[0].type(torch.float32)\n b, c = torch.var_mean(a, dim=1, correction=0)\n d = b.type(torch.float16)\n e = c.type(torch.float16)\n\n nvfuser_direct_test.assertEqual(nvf_out[0], d)\n nvfuser_direct_test.assertEqual(nvf_out[1], e)\n\n\ndef test_issue1310(nvfuser_direct_test):\n \"\"\"\n Test for issue 1310 - tests input forwarding with multiple UnaryOps.\n\n This test verifies that inputs are properly forwarded when an input is used in multiple\n UnaryOps, some having one and others having multiple further uses:\n - Multiple cast operations on the same input tensor\n - Different reduction operations on cast results\n - Proper handling of tensor aliasing and forwarding\n - Correct computation of multiple reduction operations\n \"\"\"\n inputs = [torch.randn((16, 128, 768), dtype=torch.bfloat16, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T3 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T14 = fd.ops.cast(\n T3, dtype=DataType.Float\n ) # NOTE that RHS is same, but the result is assigned to different variables\n T15 = fd.ops.cast(\n T3, dtype=DataType.Float\n ) # NOTE that RHS is same, but the result is assigned to different variables\n T16 = fd.ops.sum(T15, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T20 = fd.ops.sum(T14, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T31 = fd.ops.sum(T14, dims=[2], keepdim=False, dtype=DataType.Null)\n fd.add_output(T16)\n fd.add_output(T20)\n fd.add_output(T31)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n t14 = inputs[0].type(torch.float32)\n t16 = t14.sum([0, 1])\n t31 = t14.sum([2])\n nvfuser_direct_test.assertEqual(nvf_out[0], t16)\n nvfuser_direct_test.assertEqual(nvf_out[1], t16) # T16 == T20\n nvfuser_direct_test.assertEqual(nvf_out[2], t31)\n\n\ndef test_issue1393(nvfuser_direct_test):\n \"\"\"\n Test for issue 1393 - tests complex operations with strided tensors and broadcasting.\n\n This test verifies that complex operations work correctly with:\n - Strided tensors with non-standard memory layouts\n - Casting operations between different data types\n - Multiplication and reshape operations\n - Broadcast_in_dim operations with explicit dimensions\n - Complex tensor manipulation sequences\n - Proper handling of tensor contiguity and strides\n \"\"\"\n inputs = [\n torch.randn((5,), dtype=torch.float16, device=\"cuda:0\").as_strided(\n (3, 4, 5), (0, 0, 1)\n ),\n torch.randn((3,), dtype=torch.float16, device=\"cuda:0\").as_strided(\n (3, 4), (1, 0)","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1393","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1393#L464-L529","kind":"function","name":"test_issue1393","path":"tests/python/direct/test_repro.py","language":"python","start_line":464,"end_line":529,"context_start_line":444,"context_end_line":549,"code":" ) # NOTE that RHS is same, but the result is assigned to different variables\n T15 = fd.ops.cast(\n T3, dtype=DataType.Float\n ) # NOTE that RHS is same, but the result is assigned to different variables\n T16 = fd.ops.sum(T15, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T20 = fd.ops.sum(T14, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T31 = fd.ops.sum(T14, dims=[2], keepdim=False, dtype=DataType.Null)\n fd.add_output(T16)\n fd.add_output(T20)\n fd.add_output(T31)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n t14 = inputs[0].type(torch.float32)\n t16 = t14.sum([0, 1])\n t31 = t14.sum([2])\n nvfuser_direct_test.assertEqual(nvf_out[0], t16)\n nvfuser_direct_test.assertEqual(nvf_out[1], t16) # T16 == T20\n nvfuser_direct_test.assertEqual(nvf_out[2], t31)\n\n\ndef test_issue1393(nvfuser_direct_test):\n \"\"\"\n Test for issue 1393 - tests complex operations with strided tensors and broadcasting.\n\n This test verifies that complex operations work correctly with:\n - Strided tensors with non-standard memory layouts\n - Casting operations between different data types\n - Multiplication and reshape operations\n - Broadcast_in_dim operations with explicit dimensions\n - Complex tensor manipulation sequences\n - Proper handling of tensor contiguity and strides\n \"\"\"\n inputs = [\n torch.randn((5,), dtype=torch.float16, device=\"cuda:0\").as_strided(\n (3, 4, 5), (0, 0, 1)\n ),\n torch.randn((3,), dtype=torch.float16, device=\"cuda:0\").as_strided(\n (3, 4), (1, 0)\n ),\n torch.randn((4,), dtype=torch.float16, device=\"cuda:0\").as_strided(\n (3, 4), (0, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[None, None, True],\n dtype=DataType.Half,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, None],\n dtype=DataType.Half,\n is_cpu=False,\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[None, True],\n dtype=DataType.Half,\n is_cpu=False,\n )\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.cast(T2, dtype=DataType.Float)\n T5 = fd.ops.mul(T3, T4)\n T6 = fd.ops.cast(T5, dtype=DataType.Half)\n S7 = fd.define_scalar(3, dtype=DataType.Int)\n S8 = fd.define_scalar(4, dtype=DataType.Int)\n S9 = fd.define_scalar(1, dtype=DataType.Int)\n T11 = fd.ops.reshape(T6, new_shape=[S7, S8, S9])\n S12 = fd.define_scalar(3, dtype=DataType.Int)\n S13 = fd.define_scalar(4, dtype=DataType.Int)\n S14 = fd.define_scalar(5, dtype=DataType.Int)\n T16 = fd.ops.broadcast_in_dim(\n T11, shape=[S12, S13, S14], broadcast_dims=[0, 1, 2]\n )\n T17 = fd.ops.cast(T16, dtype=DataType.Float)\n T18 = fd.ops.cast(T0, dtype=DataType.Float)\n T19 = fd.ops.mul(T17, T18)\n T20 = fd.ops.cast(T19, dtype=DataType.Half)\n fd.add_output(T20)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = inputs[0] * (inputs[1] * inputs[2]).unsqueeze(-1)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1691(nvfuser_direct_test):\n \"\"\"\n Test for issue 1691 - tests complex reduction operations with reshape and multiplication.\n\n This test verifies that complex reduction operations work correctly with:\n - Strided tensors with non-standard memory layouts\n - Multiple reduction operations along different dimensions\n - Reshape operations with scalar-defined shapes\n - Multiplication operations between reshaped tensors\n - Final reduction operations on multiplied results\n - Proper handling of tensor contiguity and stride order\n \"\"\"\n inputs = [\n torch.randn((12,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 3, 4), (12, 4, 1)\n ),\n torch.randn((12,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4, 3), (3, 1)","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1691","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1691#L532-L580","kind":"function","name":"test_issue1691","path":"tests/python/direct/test_repro.py","language":"python","start_line":532,"end_line":580,"context_start_line":512,"context_end_line":600,"code":" S8 = fd.define_scalar(4, dtype=DataType.Int)\n S9 = fd.define_scalar(1, dtype=DataType.Int)\n T11 = fd.ops.reshape(T6, new_shape=[S7, S8, S9])\n S12 = fd.define_scalar(3, dtype=DataType.Int)\n S13 = fd.define_scalar(4, dtype=DataType.Int)\n S14 = fd.define_scalar(5, dtype=DataType.Int)\n T16 = fd.ops.broadcast_in_dim(\n T11, shape=[S12, S13, S14], broadcast_dims=[0, 1, 2]\n )\n T17 = fd.ops.cast(T16, dtype=DataType.Float)\n T18 = fd.ops.cast(T0, dtype=DataType.Float)\n T19 = fd.ops.mul(T17, T18)\n T20 = fd.ops.cast(T19, dtype=DataType.Half)\n fd.add_output(T20)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = inputs[0] * (inputs[1] * inputs[2]).unsqueeze(-1)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1691(nvfuser_direct_test):\n \"\"\"\n Test for issue 1691 - tests complex reduction operations with reshape and multiplication.\n\n This test verifies that complex reduction operations work correctly with:\n - Strided tensors with non-standard memory layouts\n - Multiple reduction operations along different dimensions\n - Reshape operations with scalar-defined shapes\n - Multiplication operations between reshaped tensors\n - Final reduction operations on multiplied results\n - Proper handling of tensor contiguity and stride order\n \"\"\"\n inputs = [\n torch.randn((12,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 3, 4), (12, 4, 1)\n ),\n torch.randn((12,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4, 3), (3, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, -1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.sum(T1, dims=[1], keepdim=False, dtype=DataType.Null) # 1D\n T3 = fd.ops.sum(T0, dims=[1, 0], keepdim=False, dtype=DataType.Null) # 1D\n S4 = fd.define_scalar(4, dtype=DataType.Int)\n T6 = fd.ops.reshape(T2, new_shape=[S4])\n S7 = fd.define_scalar(4, dtype=DataType.Int)\n T9 = fd.ops.reshape(T3, new_shape=[S7])\n T10 = fd.ops.mul(T6, T9)\n T11 = fd.ops.sum(T10, dims=[0], keepdim=False, dtype=DataType.Null)\n fd.add_output(T11)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = (inputs[0].sum(dim=[0, 1]) * inputs[1].sum(dim=1)).sum(dim=0)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1706(nvfuser_direct_test):\n \"\"\"\n Test for issue 1706 - tests complex operations derived from Llama2 network.\n\n This test verifies that complex operations work correctly with:\n - Large tensors with bfloat16 precision\n - Extensive casting operations between different data types\n - Complex mathematical operations (rsqrt, pow, reciprocal)\n - Multiple broadcast_in_dim operations with different shapes\n - Reduction operations along different dimensions\n - Complex tensor manipulation sequences\n - Proper handling of tensor contiguity and memory layouts\n \"\"\"\n inputs = [\n 1e-6,\n 10,\n 4096,\n 4096,","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1706","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1706#L583-L772","kind":"function","name":"test_issue1706","path":"tests/python/direct/test_repro.py","language":"python","start_line":583,"end_line":772,"context_start_line":563,"context_end_line":792,"code":" contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.sum(T1, dims=[1], keepdim=False, dtype=DataType.Null) # 1D\n T3 = fd.ops.sum(T0, dims=[1, 0], keepdim=False, dtype=DataType.Null) # 1D\n S4 = fd.define_scalar(4, dtype=DataType.Int)\n T6 = fd.ops.reshape(T2, new_shape=[S4])\n S7 = fd.define_scalar(4, dtype=DataType.Int)\n T9 = fd.ops.reshape(T3, new_shape=[S7])\n T10 = fd.ops.mul(T6, T9)\n T11 = fd.ops.sum(T10, dims=[0], keepdim=False, dtype=DataType.Null)\n fd.add_output(T11)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = (inputs[0].sum(dim=[0, 1]) * inputs[1].sum(dim=1)).sum(dim=0)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1706(nvfuser_direct_test):\n \"\"\"\n Test for issue 1706 - tests complex operations derived from Llama2 network.\n\n This test verifies that complex operations work correctly with:\n - Large tensors with bfloat16 precision\n - Extensive casting operations between different data types\n - Complex mathematical operations (rsqrt, pow, reciprocal)\n - Multiple broadcast_in_dim operations with different shapes\n - Reduction operations along different dimensions\n - Complex tensor manipulation sequences\n - Proper handling of tensor contiguity and memory layouts\n \"\"\"\n inputs = [\n 1e-6,\n 10,\n 4096,\n 4096,\n torch.randn(\n (\n 1,\n 4096,\n 4096,\n ),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n ),\n torch.randn((10, 32), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn(\n (\n 1,\n 4096,\n 4096,\n ),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n ),\n torch.randn(\n (\n 1,\n 4096,\n 1,\n ),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n ),\n torch.randn(\n (\n 1,\n 1,\n 4096,\n ),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n ).expand(1, 4096, 4096),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Double)\n S1 = fd.define_scalar(None, dtype=DataType.Int)\n S2 = fd.define_scalar(None, dtype=DataType.Int)\n S3 = fd.define_scalar(None, dtype=DataType.Int)\n T4 = fd.define_tensor(\n shape=[1, -1, -1],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T5 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T6 = fd.define_tensor(\n shape=[1, -1, -1],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T7 = fd.define_tensor(\n shape=[1, -1, 1],\n contiguity=[None, True, None],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T8 = fd.define_tensor(\n shape=[1, -1, -1],\n contiguity=[None, None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T9 = fd.ops.cast(T6, dtype=DataType.Float)\n T10 = fd.ops.cast(T6, dtype=DataType.Float)\n T11 = fd.ops.cast(T7, dtype=DataType.Float)\n T12 = fd.ops.rsqrt(T11)\n T13 = fd.ops.cast(T12, dtype=DataType.BFloat16)\n S14 = fd.define_scalar(1, dtype=DataType.Int)\n S15 = fd.define_scalar(4096, dtype=DataType.Int)\n S16 = fd.define_scalar(4096, dtype=DataType.Int)\n T18 = fd.ops.broadcast_in_dim(\n T13, shape=[S14, S15, S16], broadcast_dims=[0, 1, 2]\n )\n T19 = fd.ops.cast(T6, dtype=DataType.Float)\n T20 = fd.ops.cast(T18, dtype=DataType.Float)\n T21 = fd.ops.mul(T19, T20)\n T22 = fd.ops.cast(T21, dtype=DataType.BFloat16)\n T23 = fd.ops.cast(T8, dtype=DataType.Float)\n T24 = fd.ops.cast(T22, dtype=DataType.Float)\n T25 = fd.ops.cast(T4, dtype=DataType.Float)\n T26 = fd.ops.mul(T25, T24)\n T27 = fd.ops.mul(T25, T23)\n T28 = fd.ops.cast(T27, dtype=DataType.BFloat16)\n T29 = fd.ops.cast(T26, dtype=DataType.BFloat16)\n T30 = fd.ops.cast(T29, dtype=DataType.Float)\n T31 = fd.ops.sum(T30, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T32 = fd.ops.cast(T31, dtype=DataType.BFloat16)\n T33 = fd.ops.cast(T32, dtype=DataType.Float)\n S34 = fd.define_scalar(2.00000, dtype=DataType.Double)\n S35 = fd.ops.reciprocal(S34)\n T36 = fd.ops.mul(T33, S35)\n T37 = fd.ops.cast(T36, dtype=DataType.BFloat16)\n T38 = fd.ops.cast(T28, dtype=DataType.Float)\n T39 = fd.ops.mul(T38, T20)\n T40 = fd.ops.mul(T38, T19)\n T41 = fd.ops.cast(T40, dtype=DataType.BFloat16)\n T42 = fd.ops.cast(T39, dtype=DataType.BFloat16)\n T43 = fd.ops.cast(T41, dtype=DataType.Float)\n T44 = fd.ops.sum(T43, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T45 = fd.ops.cast(T44, dtype=DataType.BFloat16)\n S46 = fd.define_scalar(1, dtype=DataType.Int)\n S47 = fd.define_scalar(4096, dtype=DataType.Int)\n S48 = fd.define_scalar(1, dtype=DataType.Int)\n T50 = fd.ops.broadcast_in_dim(T45, shape=[S46, S47, S48], broadcast_dims=[1])\n T51 = fd.ops.cast(T50, dtype=DataType.Float)\n S52 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T53 = fd.ops.mul(S52, T51)\n S54 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T55 = fd.ops.pow(T12, S54)\n T56 = fd.ops.mul(T53, T55)\n T57 = fd.ops.cast(T56, dtype=DataType.BFloat16)\n T58 = fd.ops.cast(T57, dtype=DataType.Float)\n T59 = fd.ops.cast(T58, dtype=DataType.BFloat16)\n T60 = fd.ops.cast(T59, dtype=DataType.Float)\n S61 = fd.ops.reciprocal(S0)\n T62 = fd.ops.mul(T60, S61)\n T63 = fd.ops.sum(T62, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n S64 = fd.define_scalar(1, dtype=DataType.Int)\n S65 = fd.define_scalar(4096, dtype=DataType.Int)\n T67 = fd.ops.broadcast_in_dim(T63, shape=[S64, S65], broadcast_dims=[1])\n S68 = fd.define_scalar(1, dtype=DataType.Int)\n S69 = fd.define_scalar(4096, dtype=DataType.Int)\n S70 = fd.define_scalar(1, dtype=DataType.Int)\n T72 = fd.ops.broadcast_in_dim(T67, shape=[S68, S69, S70], broadcast_dims=[0, 1])\n S73 = fd.define_scalar(1, dtype=DataType.Int)\n S74 = fd.define_scalar(4096, dtype=DataType.Int)\n S75 = fd.define_scalar(4096, dtype=DataType.Int)\n T77 = fd.ops.broadcast_in_dim(\n T72, shape=[S73, S74, S75], broadcast_dims=[0, 1, 2]\n )\n T78 = fd.ops.cast(T77, dtype=DataType.BFloat16)\n T79 = fd.ops.cast(T78, dtype=DataType.Float)\n T80 = fd.ops.mul(T79, T10)\n T81 = fd.ops.mul(T79, T9)\n T82 = fd.ops.cast(T81, dtype=DataType.BFloat16)\n T83 = fd.ops.cast(T80, dtype=DataType.BFloat16)\n T84 = fd.ops.cast(T42, dtype=DataType.Float)\n T85 = fd.ops.cast(T83, dtype=DataType.Float)\n T86 = fd.ops.add(T84, T85)\n T87 = fd.ops.cast(T86, dtype=DataType.BFloat16)\n T88 = fd.ops.cast(T87, dtype=DataType.Float)\n T89 = fd.ops.cast(T82, dtype=DataType.Float)\n T90 = fd.ops.add(T88, T89)\n T91 = fd.ops.cast(T90, dtype=DataType.BFloat16)\n T92 = fd.ops.cast(T91, dtype=DataType.Float)\n T93 = fd.ops.cast(T92, dtype=DataType.BFloat16)\n T94 = fd.ops.cast(T92, dtype=DataType.BFloat16)\n T95 = fd.ops.cast(T93, dtype=DataType.Float)\n T96 = fd.ops.cast(T5, dtype=DataType.Float)\n S97 = fd.define_scalar(2.00000, dtype=DataType.Double)\n S98 = fd.ops.reciprocal(S97)\n T99 = fd.ops.mul(T96, S98)\n T100 = fd.ops.cast(T99, dtype=DataType.BFloat16)\n fd.add_output(T100)\n fd.add_output(T37)\n fd.add_output(T94)\n fd.add_output(T95)\n\n # skip pytorch check because fusion is derived from llama2 network.\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_issue1872(nvfuser_direct_test):\n \"\"\"\n Test for issue 1872 - tests full tensor creation with slice operations and casting.\n\n This test verifies that tensor operations work correctly with:\n - Full tensor creation with scalar fill values\n - Slice operations with different start and end indices\n - Casting operations between different data types\n - Multiple output tensors from a single fusion\n - Proper handling of tensor shapes and data types\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(1.00000, dtype=DataType.Double)\n S1 = fd.define_scalar(5, dtype=DataType.Int)\n T3 = fd.ops.full(shape=[S1], fill_value=S0, dtype=DataType.Float)\n T4 = fd.ops.slice(T3, start_indices=[0], end_indices=[2], strides=[1])\n T5 = fd.ops.cast(T4, dtype=DataType.Half)","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1872","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1872#L775-L798","kind":"function","name":"test_issue1872","path":"tests/python/direct/test_repro.py","language":"python","start_line":775,"end_line":798,"context_start_line":755,"context_end_line":818,"code":" T90 = fd.ops.add(T88, T89)\n T91 = fd.ops.cast(T90, dtype=DataType.BFloat16)\n T92 = fd.ops.cast(T91, dtype=DataType.Float)\n T93 = fd.ops.cast(T92, dtype=DataType.BFloat16)\n T94 = fd.ops.cast(T92, dtype=DataType.BFloat16)\n T95 = fd.ops.cast(T93, dtype=DataType.Float)\n T96 = fd.ops.cast(T5, dtype=DataType.Float)\n S97 = fd.define_scalar(2.00000, dtype=DataType.Double)\n S98 = fd.ops.reciprocal(S97)\n T99 = fd.ops.mul(T96, S98)\n T100 = fd.ops.cast(T99, dtype=DataType.BFloat16)\n fd.add_output(T100)\n fd.add_output(T37)\n fd.add_output(T94)\n fd.add_output(T95)\n\n # skip pytorch check because fusion is derived from llama2 network.\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_issue1872(nvfuser_direct_test):\n \"\"\"\n Test for issue 1872 - tests full tensor creation with slice operations and casting.\n\n This test verifies that tensor operations work correctly with:\n - Full tensor creation with scalar fill values\n - Slice operations with different start and end indices\n - Casting operations between different data types\n - Multiple output tensors from a single fusion\n - Proper handling of tensor shapes and data types\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(1.00000, dtype=DataType.Double)\n S1 = fd.define_scalar(5, dtype=DataType.Int)\n T3 = fd.ops.full(shape=[S1], fill_value=S0, dtype=DataType.Float)\n T4 = fd.ops.slice(T3, start_indices=[0], end_indices=[2], strides=[1])\n T5 = fd.ops.cast(T4, dtype=DataType.Half)\n T6 = fd.ops.slice(T3, start_indices=[2], end_indices=[5], strides=[1])\n T7 = fd.ops.cast(T6, dtype=DataType.Half)\n fd.add_output(T5)\n fd.add_output(T7)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, [], validate_results=True)\n\n\ndef test_issue1953(nvfuser_direct_test):\n \"\"\"\n Test for issue 1953 - tests complex operations with strided tensors and multiple data types.\n\n This test verifies that complex operations work correctly with:\n - Large strided tensors with complex memory layouts\n - Multiple data types (Float32 and BFloat16)\n - Complex tensor operations (permute, reshape, slice, sum, mul, neg, add)\n - Broadcasting operations with different shapes\n - Padding operations with scalar values\n - Multiple output tensors from a single fusion\n - Proper handling of tensor contiguity and stride order\n \"\"\"\n inputs = [\n 128,\n 256,\n 6,\n 24,","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue1953","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue1953#L801-L991","kind":"function","name":"test_issue1953","path":"tests/python/direct/test_repro.py","language":"python","start_line":801,"end_line":991,"context_start_line":781,"context_end_line":1011,"code":" - Slice operations with different start and end indices\n - Casting operations between different data types\n - Multiple output tensors from a single fusion\n - Proper handling of tensor shapes and data types\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(1.00000, dtype=DataType.Double)\n S1 = fd.define_scalar(5, dtype=DataType.Int)\n T3 = fd.ops.full(shape=[S1], fill_value=S0, dtype=DataType.Float)\n T4 = fd.ops.slice(T3, start_indices=[0], end_indices=[2], strides=[1])\n T5 = fd.ops.cast(T4, dtype=DataType.Half)\n T6 = fd.ops.slice(T3, start_indices=[2], end_indices=[5], strides=[1])\n T7 = fd.ops.cast(T6, dtype=DataType.Half)\n fd.add_output(T5)\n fd.add_output(T7)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, [], validate_results=True)\n\n\ndef test_issue1953(nvfuser_direct_test):\n \"\"\"\n Test for issue 1953 - tests complex operations with strided tensors and multiple data types.\n\n This test verifies that complex operations work correctly with:\n - Large strided tensors with complex memory layouts\n - Multiple data types (Float32 and BFloat16)\n - Complex tensor operations (permute, reshape, slice, sum, mul, neg, add)\n - Broadcasting operations with different shapes\n - Padding operations with scalar values\n - Multiple output tensors from a single fusion\n - Proper handling of tensor contiguity and stride order\n \"\"\"\n inputs = [\n 128,\n 256,\n 6,\n 24,\n 2,\n 128,\n 256,\n 6,\n 24,\n 2,\n torch.randn((6144,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (128, 256, 6, 24), (0, 24, 0, 1)\n ),\n torch.randn((6144,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (128, 256, 6, 24), (0, 24, 0, 1)\n ),\n torch.randn((9437184,), dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (128, 6, 256, 48), (73728, 48, 288, 1)\n ),\n torch.randn((9437184,), dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (128, 6, 256, 48), (73728, 48, 288, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Int)\n S1 = fd.define_scalar(None, dtype=DataType.Int)\n S2 = fd.define_scalar(None, dtype=DataType.Int)\n S3 = fd.define_scalar(None, dtype=DataType.Int)\n S4 = fd.define_scalar(None, dtype=DataType.Int)\n S5 = fd.define_scalar(None, dtype=DataType.Int)\n S6 = fd.define_scalar(None, dtype=DataType.Int)\n S7 = fd.define_scalar(None, dtype=DataType.Int)\n S8 = fd.define_scalar(None, dtype=DataType.Int)\n S9 = fd.define_scalar(None, dtype=DataType.Int)\n T10 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, True, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T11 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, True, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T12 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T13 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T14 = fd.ops.cast(T13, dtype=DataType.Float)\n T15 = fd.ops.permute(T14, dims=[0, 2, 1, 3])\n S16 = fd.define_scalar(128, dtype=DataType.Int)\n S17 = fd.define_scalar(256, dtype=DataType.Int)\n S18 = fd.define_scalar(6, dtype=DataType.Int)\n S19 = fd.define_scalar(24, dtype=DataType.Int)\n S20 = fd.define_scalar(2, dtype=DataType.Int)\n T22 = fd.ops.reshape(T15, new_shape=[S16, S17, S18, S19, S20])\n T23 = fd.ops.slice(\n T22,\n start_indices=[0, 0, 0, 0, 0],\n end_indices=[128, 256, 6, 24, 1],\n strides=[1, 1, 1, 1, 1],\n )\n T24 = fd.ops.slice(\n T22,\n start_indices=[0, 0, 0, 0, 1],\n end_indices=[128, 256, 6, 24, 2],\n strides=[1, 1, 1, 1, 1],\n )\n T25 = fd.ops.sum(T24, dims=[4], keepdim=False, dtype=DataType.Null)\n T26 = fd.ops.sum(T23, dims=[4], keepdim=False, dtype=DataType.Null)\n T27 = fd.ops.mul(T25, T10)\n T28 = fd.ops.mul(T25, T11)\n T29 = fd.ops.neg(T26)\n T30 = fd.ops.mul(T29, T11)\n T31 = fd.ops.add(T27, T30)\n T32 = fd.ops.cast(T31, dtype=DataType.BFloat16)\n T33 = fd.ops.mul(T26, T10)\n T34 = fd.ops.add(T28, T33)\n T35 = fd.ops.cast(T34, dtype=DataType.BFloat16)\n S36 = fd.define_scalar(128, dtype=DataType.Int)\n S37 = fd.define_scalar(256, dtype=DataType.Int)\n S38 = fd.define_scalar(6, dtype=DataType.Int)\n S39 = fd.define_scalar(24, dtype=DataType.Int)\n S40 = fd.define_scalar(1, dtype=DataType.Int)\n T42 = fd.ops.broadcast_in_dim(\n T32, shape=[S36, S37, S38, S39, S40], broadcast_dims=[0, 1, 2, 3]\n )\n S43 = fd.define_scalar(128, dtype=DataType.Int)\n S44 = fd.define_scalar(256, dtype=DataType.Int)\n S45 = fd.define_scalar(6, dtype=DataType.Int)\n S46 = fd.define_scalar(24, dtype=DataType.Int)\n S47 = fd.define_scalar(1, dtype=DataType.Int)\n T49 = fd.ops.broadcast_in_dim(\n T35, shape=[S43, S44, S45, S46, S47], broadcast_dims=[0, 1, 2, 3]\n )\n S50 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T51 = fd.ops.pad(T42, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], S50)\n S52 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T53 = fd.ops.pad(T49, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], S52)\n T54 = fd.ops.cast(T51, dtype=DataType.Float)\n T55 = fd.ops.cast(T53, dtype=DataType.Float)\n T56 = fd.ops.add(T54, T55)\n T57 = fd.ops.cast(T56, dtype=DataType.BFloat16)\n T58 = fd.ops.cast(T12, dtype=DataType.Float)\n T59 = fd.ops.permute(T58, dims=[0, 2, 1, 3])\n S60 = fd.define_scalar(128, dtype=DataType.Int)\n S61 = fd.define_scalar(256, dtype=DataType.Int)\n S62 = fd.define_scalar(6, dtype=DataType.Int)\n S63 = fd.define_scalar(24, dtype=DataType.Int)\n S64 = fd.define_scalar(2, dtype=DataType.Int)\n T66 = fd.ops.reshape(T59, new_shape=[S60, S61, S62, S63, S64])\n T67 = fd.ops.slice(\n T66,\n start_indices=[0, 0, 0, 0, 0],\n end_indices=[128, 256, 6, 24, 1],\n strides=[1, 1, 1, 1, 1],\n )\n T68 = fd.ops.slice(\n T66,\n start_indices=[0, 0, 0, 0, 1],\n end_indices=[128, 256, 6, 24, 2],\n strides=[1, 1, 1, 1, 1],\n )\n T69 = fd.ops.sum(T68, dims=[4], keepdim=False, dtype=DataType.Null)\n T70 = fd.ops.sum(T67, dims=[4], keepdim=False, dtype=DataType.Null)\n T71 = fd.ops.mul(T69, T10)\n T72 = fd.ops.mul(T69, T11)\n T73 = fd.ops.neg(T70)\n T74 = fd.ops.mul(T73, T11)\n T75 = fd.ops.add(T71, T74)\n T76 = fd.ops.cast(T75, dtype=DataType.BFloat16)\n T77 = fd.ops.mul(T70, T10)\n T78 = fd.ops.add(T72, T77)\n T79 = fd.ops.cast(T78, dtype=DataType.BFloat16)\n S80 = fd.define_scalar(128, dtype=DataType.Int)\n S81 = fd.define_scalar(256, dtype=DataType.Int)\n S82 = fd.define_scalar(6, dtype=DataType.Int)\n S83 = fd.define_scalar(24, dtype=DataType.Int)\n S84 = fd.define_scalar(1, dtype=DataType.Int)\n T86 = fd.ops.broadcast_in_dim(\n T76, shape=[S80, S81, S82, S83, S84], broadcast_dims=[0, 1, 2, 3]\n )\n S87 = fd.define_scalar(128, dtype=DataType.Int)\n S88 = fd.define_scalar(256, dtype=DataType.Int)\n S89 = fd.define_scalar(6, dtype=DataType.Int)\n S90 = fd.define_scalar(24, dtype=DataType.Int)\n S91 = fd.define_scalar(1, dtype=DataType.Int)\n T93 = fd.ops.broadcast_in_dim(\n T79, shape=[S87, S88, S89, S90, S91], broadcast_dims=[0, 1, 2, 3]\n )\n S94 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T95 = fd.ops.pad(T86, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], S94)\n S96 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T97 = fd.ops.pad(T93, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], S96)\n T98 = fd.ops.cast(T95, dtype=DataType.Float)\n T99 = fd.ops.cast(T97, dtype=DataType.Float)\n T100 = fd.ops.add(T98, T99)\n T101 = fd.ops.cast(T100, dtype=DataType.BFloat16)\n fd.add_output(T57)\n fd.add_output(T101)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2275_repro1(nvfuser_direct_test):\n \"\"\"\n Test for issue 2275 repro1 - tests unpadded concatenation operations with complex tensor manipulations.\n\n This test verifies that complex operations work correctly with:\n - Large strided tensors with complex memory layouts\n - BFloat16 precision operations\n - Complex tensor operations (cast, mul, sum, broadcast_in_dim, rsqrt, linear, reshape, permute, slice, neg, cat)\n - Broadcasting operations with different shapes\n - Linear operations with weight matrices\n - Multiple slice operations with different indices\n - Concatenation operations with negative dimensions\n - Proper handling of tensor contiguity and stride order\n \"\"\"\n inputs = [\n torch.randn((4096,), dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (2, 4096, 4096), (0, 0, 1)\n ),","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2275_repro1","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2275_repro1#L994-L1146","kind":"function","name":"test_issue2275_repro1","path":"tests/python/direct/test_repro.py","language":"python","start_line":994,"end_line":1146,"context_start_line":974,"context_end_line":1166,"code":" S89 = fd.define_scalar(6, dtype=DataType.Int)\n S90 = fd.define_scalar(24, dtype=DataType.Int)\n S91 = fd.define_scalar(1, dtype=DataType.Int)\n T93 = fd.ops.broadcast_in_dim(\n T79, shape=[S87, S88, S89, S90, S91], broadcast_dims=[0, 1, 2, 3]\n )\n S94 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T95 = fd.ops.pad(T86, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], S94)\n S96 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T97 = fd.ops.pad(T93, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], S96)\n T98 = fd.ops.cast(T95, dtype=DataType.Float)\n T99 = fd.ops.cast(T97, dtype=DataType.Float)\n T100 = fd.ops.add(T98, T99)\n T101 = fd.ops.cast(T100, dtype=DataType.BFloat16)\n fd.add_output(T57)\n fd.add_output(T101)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2275_repro1(nvfuser_direct_test):\n \"\"\"\n Test for issue 2275 repro1 - tests unpadded concatenation operations with complex tensor manipulations.\n\n This test verifies that complex operations work correctly with:\n - Large strided tensors with complex memory layouts\n - BFloat16 precision operations\n - Complex tensor operations (cast, mul, sum, broadcast_in_dim, rsqrt, linear, reshape, permute, slice, neg, cat)\n - Broadcasting operations with different shapes\n - Linear operations with weight matrices\n - Multiple slice operations with different indices\n - Concatenation operations with negative dimensions\n - Proper handling of tensor contiguity and stride order\n \"\"\"\n inputs = [\n torch.randn((4096,), dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (2, 4096, 4096), (0, 0, 1)\n ),\n torch.randn((33554432,), dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (2, 4096, 4096), (16777216, 4096, 1)\n ),\n torch.randn((524288,), dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (2, 32, 4096, 128), (0, 0, 128, 1)\n ),\n torch.randn((524288,), dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (2, 32, 4096, 128), (0, 0, 128, 1)\n ),\n torch.randn((25165824,), dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (6144, 4096), (4096, 1)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[None, None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T3 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T5 = fd.ops.cast(T1, dtype=DataType.Float)\n T6 = fd.ops.mul(T5, T5)\n T7 = fd.ops.sum(T6, dims=[2], keepdim=False, dtype=DataType.Null)\n S8 = fd.define_scalar(2, dtype=DataType.Int)\n S9 = fd.define_scalar(4096, dtype=DataType.Int)\n S10 = fd.define_scalar(1, dtype=DataType.Int)\n T12 = fd.ops.broadcast_in_dim(T7, shape=[S8, S9, S10], broadcast_dims=[0, 1])\n S13 = fd.define_scalar(4096.00, dtype=DataType.Double)\n S14 = fd.ops.reciprocal(S13)\n T15 = fd.ops.mul(T12, S14)\n S16 = fd.define_scalar(1.00000e-05, dtype=DataType.Double)\n T17 = fd.ops.add(T15, S16)\n T18 = fd.ops.rsqrt(T17)\n S19 = fd.define_scalar(2, dtype=DataType.Int)\n S20 = fd.define_scalar(4096, dtype=DataType.Int)\n S21 = fd.define_scalar(4096, dtype=DataType.Int)\n T23 = fd.ops.broadcast_in_dim(\n T18, shape=[S19, S20, S21], broadcast_dims=[0, 1, 2]\n )\n T24 = fd.ops.mul(T5, T23)\n T25 = fd.ops.cast(T0, dtype=DataType.Float)\n T26 = fd.ops.mul(T24, T25)\n T27 = fd.ops.cast(T26, dtype=DataType.BFloat16)\n T28 = fd.ops.linear(T27, T4)\n S29 = fd.define_scalar(2, dtype=DataType.Int)\n S30 = fd.define_scalar(4096, dtype=DataType.Int)\n S31 = fd.define_scalar(8, dtype=DataType.Int)\n S32 = fd.define_scalar(6, dtype=DataType.Int)\n S33 = fd.define_scalar(128, dtype=DataType.Int)\n T35 = fd.ops.reshape(T28, new_shape=[S29, S30, S31, S32, S33])\n T36 = fd.ops.permute(T35, dims=[0, 2, 3, 1, 4])\n T37 = fd.ops.slice(\n T36,\n start_indices=[0, 0, 0, 0, 0],\n end_indices=[2, 8, 4, 4096, 128],\n strides=[1, 1, 1, 1, 1],\n )\n\n S47 = fd.define_scalar(2, dtype=DataType.Int)\n S48 = fd.define_scalar(32, dtype=DataType.Int)\n S49 = fd.define_scalar(4096, dtype=DataType.Int)\n S50 = fd.define_scalar(128, dtype=DataType.Int)\n T52 = fd.ops.reshape(T37, new_shape=[S47, S48, S49, S50])\n T59 = fd.ops.slice(\n T52,\n start_indices=[0, 0, 0, 0],\n end_indices=[2, 32, 4096, 128],\n strides=[1, 1, 1, 1],\n )\n T60 = fd.ops.slice(\n T59,\n start_indices=[0, 0, 0, 0],\n end_indices=[2, 32, 4096, 64],\n strides=[1, 1, 1, 1],\n )\n T61 = fd.ops.slice(\n T59,\n start_indices=[0, 0, 0, 64],\n end_indices=[2, 32, 4096, 128],\n strides=[1, 1, 1, 1],\n )\n T62 = fd.ops.cast(T61, dtype=DataType.Float)\n T63 = fd.ops.neg(T62)\n T64 = fd.ops.cast(T63, dtype=DataType.BFloat16)\n T65 = fd.ops.cat([T64, T60], dim=-1)\n T66 = fd.ops.cast(T59, dtype=DataType.Float)\n T67 = fd.ops.cast(T2, dtype=DataType.Float)\n T68 = fd.ops.mul(T66, T67)\n T69 = fd.ops.cast(T65, dtype=DataType.Float)\n T70 = fd.ops.cast(T3, dtype=DataType.Float)\n T71 = fd.ops.mul(T69, T70)\n T72 = fd.ops.add(T68, T71)\n T73 = fd.ops.cast(T72, dtype=DataType.BFloat16)\n\n T87 = fd.ops.slice(\n T52,\n start_indices=[0, 0, 0, 0],\n end_indices=[2, 32, 4096, 0],\n strides=[1, 1, 1, 1],\n )\n T88 = fd.ops.cat([T73, T87], dim=-1)\n\n fd.add_output(T88)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2275_repro2(nvfuser_direct_test):\n \"\"\"\n Test for issue 2275 repro2 - tests unpadded concatenation operations with trigonometric functions.\n\n This test verifies that complex operations work correctly with:\n - Large tensors with BFloat16 precision\n - Multiple slice operations with different indices\n - Trigonometric operations (sin, cos)\n - Negation and casting operations\n - Concatenation operations with negative dimensions\n - Proper handling of tensor shapes and operations\n \"\"\"\n inputs = [torch.randn((2, 32, 4096, 128), dtype=torch.bfloat16, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n\n T1 = fd.ops.slice(","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2275_repro2","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2275_repro2#L1149-L1198","kind":"function","name":"test_issue2275_repro2","path":"tests/python/direct/test_repro.py","language":"python","start_line":1149,"end_line":1198,"context_start_line":1129,"context_end_line":1218,"code":" T68 = fd.ops.mul(T66, T67)\n T69 = fd.ops.cast(T65, dtype=DataType.Float)\n T70 = fd.ops.cast(T3, dtype=DataType.Float)\n T71 = fd.ops.mul(T69, T70)\n T72 = fd.ops.add(T68, T71)\n T73 = fd.ops.cast(T72, dtype=DataType.BFloat16)\n\n T87 = fd.ops.slice(\n T52,\n start_indices=[0, 0, 0, 0],\n end_indices=[2, 32, 4096, 0],\n strides=[1, 1, 1, 1],\n )\n T88 = fd.ops.cat([T73, T87], dim=-1)\n\n fd.add_output(T88)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2275_repro2(nvfuser_direct_test):\n \"\"\"\n Test for issue 2275 repro2 - tests unpadded concatenation operations with trigonometric functions.\n\n This test verifies that complex operations work correctly with:\n - Large tensors with BFloat16 precision\n - Multiple slice operations with different indices\n - Trigonometric operations (sin, cos)\n - Negation and casting operations\n - Concatenation operations with negative dimensions\n - Proper handling of tensor shapes and operations\n \"\"\"\n inputs = [torch.randn((2, 32, 4096, 128), dtype=torch.bfloat16, device=\"cuda:0\")]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n\n T1 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 0, 0],\n end_indices=[2, 32, 4096, 128],\n strides=[1, 1, 1, 1],\n )\n T2 = fd.ops.slice(\n T1,\n start_indices=[0, 0, 0, 0],\n end_indices=[2, 32, 4096, 64],\n strides=[1, 1, 1, 1],\n )\n T3 = fd.ops.slice(\n T1,\n start_indices=[0, 0, 0, 64],\n end_indices=[2, 32, 4096, 128],\n strides=[1, 1, 1, 1],\n )\n T4 = fd.ops.cast(fd.ops.neg(T3), DataType.BFloat16)\n T5 = fd.ops.cat([T4, T2], dim=-1)\n T6 = fd.ops.add(fd.ops.sin(T5), fd.ops.cos(T5))\n T7 = fd.ops.cast(T6, DataType.BFloat16)\n\n T100 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 0, 0],\n end_indices=[2, 32, 4096, 0],\n strides=[1, 1, 1, 1],\n )\n T101 = fd.ops.cat([T7, T100], dim=-1)\n fd.add_output(T101)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\n# See https://github.com/NVIDIA/Fuser/issues/2317\ndef test_issue2317(nvfuser_direct_test):\n \"\"\"\n Test case for issue #2317: Complex fusion with permute, reshape, and linear operations.\n\n This test verifies a fusion that performs:\n 1. Permute operation on a 4D tensor (16, 25, 128, 64) -> (16, 128, 25, 64)\n 2. Stride reordering to optimize memory layout\n 3. Reshape to match the shape of the second input tensor (16, 128, 1600)\n 4. Linear transformation using a weight matrix (1600, 1600)\n 5. Element-wise addition with residual connection\n 6. Type casting to BFloat16\n 7. Second linear transformation with residual connection\n\n The test uses BFloat16 precision and requires Ampere or newer GPU architecture.\n \"\"\"\n inputs = [\n torch.randn((16, 25, 128, 64), dtype=torch.bfloat16, device=\"cuda:0\"),","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2317","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2317#L1202-L1239","kind":"function","name":"test_issue2317","path":"tests/python/direct/test_repro.py","language":"python","start_line":1202,"end_line":1239,"context_start_line":1182,"context_end_line":1259,"code":" strides=[1, 1, 1, 1],\n )\n T4 = fd.ops.cast(fd.ops.neg(T3), DataType.BFloat16)\n T5 = fd.ops.cat([T4, T2], dim=-1)\n T6 = fd.ops.add(fd.ops.sin(T5), fd.ops.cos(T5))\n T7 = fd.ops.cast(T6, DataType.BFloat16)\n\n T100 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 0, 0],\n end_indices=[2, 32, 4096, 0],\n strides=[1, 1, 1, 1],\n )\n T101 = fd.ops.cat([T7, T100], dim=-1)\n fd.add_output(T101)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\n# See https://github.com/NVIDIA/Fuser/issues/2317\ndef test_issue2317(nvfuser_direct_test):\n \"\"\"\n Test case for issue #2317: Complex fusion with permute, reshape, and linear operations.\n\n This test verifies a fusion that performs:\n 1. Permute operation on a 4D tensor (16, 25, 128, 64) -> (16, 128, 25, 64)\n 2. Stride reordering to optimize memory layout\n 3. Reshape to match the shape of the second input tensor (16, 128, 1600)\n 4. Linear transformation using a weight matrix (1600, 1600)\n 5. Element-wise addition with residual connection\n 6. Type casting to BFloat16\n 7. Second linear transformation with residual connection\n\n The test uses BFloat16 precision and requires Ampere or newer GPU architecture.\n \"\"\"\n inputs = [\n torch.randn((16, 25, 128, 64), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((16, 128, 1600), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((1600, 1600), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.from_pytorch(inputs[2])\n\n T10 = fd.ops.permute(T0, dims=[0, 2, 1, 3])\n T11 = fd.ops.stride_order(T10, stride_order=[3, 2, 1, 0])\n T16 = fd.ops.reshape(T11, new_shape=T1.shape())\n T17 = fd.ops.linear(T16, T2)\n T33 = fd.ops.add(T17, T1)\n\n T33 = fd.ops.cast(T33, dtype=DataType.BFloat16)\n T34 = fd.ops.linear(T33, T2)\n T35 = fd.ops.add(T34, T33)\n fd.add_output(T35)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2354(nvfuser_direct_test):\n \"\"\"\n Test for issue 2354 - tests complex operations with linear and mul operations.\n\n This test verifies that complex operations work correctly with:\n - Linear operations with different shapes\n - Mul operations with different shapes\n - Proper handling of tensor shapes and operations\n \"\"\"\n inputs = [\n torch.randn((8, 4), dtype=torch.float32, device=\"cuda:0\"),\n torch.randn(\n (\n 6,\n 2,\n 4,\n ),\n dtype=torch.float32,","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2354","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2354#L1242-L1285","kind":"function","name":"test_issue2354","path":"tests/python/direct/test_repro.py","language":"python","start_line":1242,"end_line":1285,"context_start_line":1222,"context_end_line":1305,"code":"\n def fusion_func(fd: FusionDefinition):\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.from_pytorch(inputs[2])\n\n T10 = fd.ops.permute(T0, dims=[0, 2, 1, 3])\n T11 = fd.ops.stride_order(T10, stride_order=[3, 2, 1, 0])\n T16 = fd.ops.reshape(T11, new_shape=T1.shape())\n T17 = fd.ops.linear(T16, T2)\n T33 = fd.ops.add(T17, T1)\n\n T33 = fd.ops.cast(T33, dtype=DataType.BFloat16)\n T34 = fd.ops.linear(T33, T2)\n T35 = fd.ops.add(T34, T33)\n fd.add_output(T35)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2354(nvfuser_direct_test):\n \"\"\"\n Test for issue 2354 - tests complex operations with linear and mul operations.\n\n This test verifies that complex operations work correctly with:\n - Linear operations with different shapes\n - Mul operations with different shapes\n - Proper handling of tensor shapes and operations\n \"\"\"\n inputs = [\n torch.randn((8, 4), dtype=torch.float32, device=\"cuda:0\"),\n torch.randn(\n (\n 6,\n 2,\n 4,\n ),\n dtype=torch.float32,\n device=\"cuda:0\",\n ),\n ]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.ops.linear(T1, T0)\n S3 = fd.define_scalar(1.41421, dtype=DataType.Double)\n T4 = fd.ops.mul(T2, S3)\n fd.add_output(T2)\n fd.add_output(T4)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2395(nvfuser_direct_test):\n \"\"\"\n Test for issue 2395 - tests complex operations with strided tensors and multiple data types.\n\n Migrated from `test_issue_2395` in legacy test_pointwise.py\n\n This test verifies that complex operations work correctly with:\n - Large strided tensors with complex memory layouts\n - Multiple data types (Float32 and BFloat16)\n - Complex tensor operations (permute, reshape, slice, sum, mul, neg, add)\n - Broadcasting operations with different shapes\n - Padding operations with scalar values\n - Multiple output tensors from a single fusion\n - Proper handling of tensor contiguity and stride order\n \"\"\"\n\n def create_fusion(fd: FusionDefinition) -> None:\n cond0 = fd.define_tensor(","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2395","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2395#L1288-L1360","kind":"function","name":"test_issue2395","path":"tests/python/direct/test_repro.py","language":"python","start_line":1288,"end_line":1360,"context_start_line":1268,"context_end_line":1380,"code":" dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.ops.linear(T1, T0)\n S3 = fd.define_scalar(1.41421, dtype=DataType.Double)\n T4 = fd.ops.mul(T2, S3)\n fd.add_output(T2)\n fd.add_output(T4)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2395(nvfuser_direct_test):\n \"\"\"\n Test for issue 2395 - tests complex operations with strided tensors and multiple data types.\n\n Migrated from `test_issue_2395` in legacy test_pointwise.py\n\n This test verifies that complex operations work correctly with:\n - Large strided tensors with complex memory layouts\n - Multiple data types (Float32 and BFloat16)\n - Complex tensor operations (permute, reshape, slice, sum, mul, neg, add)\n - Broadcasting operations with different shapes\n - Padding operations with scalar values\n - Multiple output tensors from a single fusion\n - Proper handling of tensor contiguity and stride order\n \"\"\"\n\n def create_fusion(fd: FusionDefinition) -> None:\n cond0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, None],\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n values = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n cond1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[1, 0],\n )\n cond1 = fd.ops.broadcast_in_dim(\n cond1, shape=[16, 16, 32], broadcast_dims=[0, 1]\n )\n sliced = fd.ops.slice(\n values,\n start_indices=[0, 0, 16],\n end_indices=[16, 16, 32],\n strides=[1, 1, 1],\n )\n zero = fd.define_scalar(0.00000, dtype=DataType.Double)\n masked = fd.ops.where(cond1, zero, values)\n masked = fd.ops.where(cond0, zero, masked)\n fd.add_output(sliced)\n fd.add_output(masked)\n\n ins = [\n torch.randint(0, 2, (256,), dtype=torch.bool, device=\"cuda:0\").as_strided(\n (16, 16, 32), (16, 1, 0)\n ),\n torch.randn((8192,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (16, 16, 32), (512, 32, 1)\n ),\n torch.randint(0, 2, (256,), dtype=torch.bool, device=\"cuda:0\").as_strided(\n (16, 16), (16, 1)\n ),\n ]\n outs, _ = nvfuser_direct_test.exec_nvfuser(create_fusion, ins)\n\n nvfuser_direct_test.assertEqual(outs[0], ins[1][:, :, 16:], rtol=0, atol=0)\n nvfuser_direct_test.assertEqual(\n outs[1],\n torch.where(\n torch.logical_or(ins[0] == 1, ins[2].unsqueeze(-1) == 1), 0, ins[1]\n ),\n )\n\n\ndef test_issue2532(nvfuser_direct_test):\n \"\"\"\n Test for issue 2532 - tests broadcast reduction axis in matmul.\n\n This test verifies that broadcast reduction axis in matmul works correctly.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, 1],\n contiguity=[True, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T1 = fd.define_tensor(\n shape=[-1, 1, -1],\n contiguity=[True, None, True],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2532","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2532#L1363-L1399","kind":"function","name":"test_issue2532","path":"tests/python/direct/test_repro.py","language":"python","start_line":1363,"end_line":1399,"context_start_line":1343,"context_end_line":1419,"code":" (16, 16, 32), (16, 1, 0)\n ),\n torch.randn((8192,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (16, 16, 32), (512, 32, 1)\n ),\n torch.randint(0, 2, (256,), dtype=torch.bool, device=\"cuda:0\").as_strided(\n (16, 16), (16, 1)\n ),\n ]\n outs, _ = nvfuser_direct_test.exec_nvfuser(create_fusion, ins)\n\n nvfuser_direct_test.assertEqual(outs[0], ins[1][:, :, 16:], rtol=0, atol=0)\n nvfuser_direct_test.assertEqual(\n outs[1],\n torch.where(\n torch.logical_or(ins[0] == 1, ins[2].unsqueeze(-1) == 1), 0, ins[1]\n ),\n )\n\n\ndef test_issue2532(nvfuser_direct_test):\n \"\"\"\n Test for issue 2532 - tests broadcast reduction axis in matmul.\n\n This test verifies that broadcast reduction axis in matmul works correctly.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, 1],\n contiguity=[True, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T1 = fd.define_tensor(\n shape=[-1, 1, -1],\n contiguity=[True, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.ops.sum(T1, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T3 = fd.ops.matmul(T0, T1)\n T4 = fd.ops.sum(T3, dims=[0], keepdim=False, dtype=DataType.Null)\n fd.add_output(T2)\n fd.add_output(T4)\n\n inputs = [\n torch.randn((2 * 32,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 32, 1), (32, 1, 32)\n ),\n torch.randn((2 * 16,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 1, 16), (16, 16, 1)\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n # TODO fd.validate fails with this test\n\n\ndef test_issue2545(nvfuser_direct_test):\n \"\"\"\n Test for issue 2545 - tests empty tensor handling with concatenation operations.\n\n This test verifies that operations with empty tensors work correctly,\n particularly when concatenating tensors where one or more inputs\n are empty tensors.\n \"\"\"\n inputs = [\n torch.randint(0, 10, (2,), dtype=torch.int64, device=\"cuda:0\").as_strided(\n (2,), (1,)\n ),\n torch.randint(0, 10, (0,), dtype=torch.int64, device=\"cuda:0\").as_strided(\n (0,), (1,)\n ),\n ]\n","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2545","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2545#L1403-L1455","kind":"function","name":"test_issue2545","path":"tests/python/direct/test_repro.py","language":"python","start_line":1403,"end_line":1455,"context_start_line":1383,"context_end_line":1475,"code":" stride_order=[2, 1, 0],\n )\n T2 = fd.ops.sum(T1, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T3 = fd.ops.matmul(T0, T1)\n T4 = fd.ops.sum(T3, dims=[0], keepdim=False, dtype=DataType.Null)\n fd.add_output(T2)\n fd.add_output(T4)\n\n inputs = [\n torch.randn((2 * 32,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 32, 1), (32, 1, 32)\n ),\n torch.randn((2 * 16,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (2, 1, 16), (16, 16, 1)\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n # TODO fd.validate fails with this test\n\n\ndef test_issue2545(nvfuser_direct_test):\n \"\"\"\n Test for issue 2545 - tests empty tensor handling with concatenation operations.\n\n This test verifies that operations with empty tensors work correctly,\n particularly when concatenating tensors where one or more inputs\n are empty tensors.\n \"\"\"\n inputs = [\n torch.randint(0, 10, (2,), dtype=torch.int64, device=\"cuda:0\").as_strided(\n (2,), (1,)\n ),\n torch.randint(0, 10, (0,), dtype=torch.int64, device=\"cuda:0\").as_strided(\n (0,), (1,)\n ),\n ]\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[0],\n )\n T1 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[0],\n )\n S2 = fd.define_scalar(0, dtype=DataType.Int)\n T3 = fd.ops.lt(T0, S2)\n S4 = fd.define_scalar(5, dtype=DataType.Int)\n S5 = fd.define_scalar(0, dtype=DataType.Int)\n T6 = fd.ops.where(T3, S4, S5)\n T7 = fd.ops.add(T0, T6)\n S8 = fd.define_scalar(0, dtype=DataType.Int)\n T9 = fd.ops.add(T7, S8)\n T10 = fd.ops.cat([T1, T9], dim=0)\n S11 = fd.define_scalar(0, dtype=DataType.Int)\n T12 = fd.ops.add(T10, S11)\n T13 = fd.ops.cat([T1, T12], dim=0)\n S14 = fd.define_scalar(5, dtype=DataType.Int)\n T15 = fd.ops.add(T10, S14)\n T16 = fd.ops.cat([T13, T15], dim=0)\n S17 = fd.define_scalar(10, dtype=DataType.Int)\n T18 = fd.ops.add(T10, S17)\n fd.add_output(T18)\n fd.add_output(T16)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2549(nvfuser_direct_test):\n \"\"\"\n Test for issue 2549 - tests broadcast_in_dim and division operations.\n\n This test verifies that broadcast_in_dim operations work correctly\n with division operations, particularly when broadcasting tensors\n with different shapes.\n \"\"\"\n a = torch.ones(4, 1, dtype=torch.double, device=\"cuda\")\n b = torch.ones(4, 4, dtype=torch.double, device=\"cuda\")\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n sizes=a.shape, strides=a.stride(), dtype=DataType.Double, is_cpu=False\n )\n T1 = fd.define_tensor(\n sizes=b.shape, strides=b.stride(), dtype=DataType.Double, is_cpu=False\n )","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2549","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2549#L1458-L1481","kind":"function","name":"test_issue2549","path":"tests/python/direct/test_repro.py","language":"python","start_line":1458,"end_line":1481,"context_start_line":1438,"context_end_line":1501,"code":" S5 = fd.define_scalar(0, dtype=DataType.Int)\n T6 = fd.ops.where(T3, S4, S5)\n T7 = fd.ops.add(T0, T6)\n S8 = fd.define_scalar(0, dtype=DataType.Int)\n T9 = fd.ops.add(T7, S8)\n T10 = fd.ops.cat([T1, T9], dim=0)\n S11 = fd.define_scalar(0, dtype=DataType.Int)\n T12 = fd.ops.add(T10, S11)\n T13 = fd.ops.cat([T1, T12], dim=0)\n S14 = fd.define_scalar(5, dtype=DataType.Int)\n T15 = fd.ops.add(T10, S14)\n T16 = fd.ops.cat([T13, T15], dim=0)\n S17 = fd.define_scalar(10, dtype=DataType.Int)\n T18 = fd.ops.add(T10, S17)\n fd.add_output(T18)\n fd.add_output(T16)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2549(nvfuser_direct_test):\n \"\"\"\n Test for issue 2549 - tests broadcast_in_dim and division operations.\n\n This test verifies that broadcast_in_dim operations work correctly\n with division operations, particularly when broadcasting tensors\n with different shapes.\n \"\"\"\n a = torch.ones(4, 1, dtype=torch.double, device=\"cuda\")\n b = torch.ones(4, 4, dtype=torch.double, device=\"cuda\")\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n sizes=a.shape, strides=a.stride(), dtype=DataType.Double, is_cpu=False\n )\n T1 = fd.define_tensor(\n sizes=b.shape, strides=b.stride(), dtype=DataType.Double, is_cpu=False\n )\n T2 = fd.ops.broadcast_in_dim(T0, shape=[4, 4], broadcast_dims=[0, 1])\n T3 = fd.ops.div(T1, T2)\n fd.add_output(T3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [a, b])\n nvfuser_direct_test.assertEqual(nvf_out[0], b / a)\n\n\ndef test_issue2664_repro1(nvfuser_direct_test):\n \"\"\"\n Test for issue 2664 - tests broadcast in dim and inplace update.\n\n Migrated from `test_inplace_issue2664` in legacy test_pointwise.py\n\n Example 1: Repro from https://github.com/NVIDIA/Fuser/issues/2664\n T4 (scalar) is broadcasted and used in mul computation. It is also used to update T2 inplace.\n This causes a RW race. In this case, the aliased tensor is a producer of bcast op.\n \"\"\"\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2664_repro1","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2664_repro1#L1484-L1526","kind":"function","name":"test_issue2664_repro1","path":"tests/python/direct/test_repro.py","language":"python","start_line":1484,"end_line":1526,"context_start_line":1464,"context_end_line":1546,"code":" with different shapes.\n \"\"\"\n a = torch.ones(4, 1, dtype=torch.double, device=\"cuda\")\n b = torch.ones(4, 4, dtype=torch.double, device=\"cuda\")\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n sizes=a.shape, strides=a.stride(), dtype=DataType.Double, is_cpu=False\n )\n T1 = fd.define_tensor(\n sizes=b.shape, strides=b.stride(), dtype=DataType.Double, is_cpu=False\n )\n T2 = fd.ops.broadcast_in_dim(T0, shape=[4, 4], broadcast_dims=[0, 1])\n T3 = fd.ops.div(T1, T2)\n fd.add_output(T3)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [a, b])\n nvfuser_direct_test.assertEqual(nvf_out[0], b / a)\n\n\ndef test_issue2664_repro1(nvfuser_direct_test):\n \"\"\"\n Test for issue 2664 - tests broadcast in dim and inplace update.\n\n Migrated from `test_inplace_issue2664` in legacy test_pointwise.py\n\n Example 1: Repro from https://github.com/NVIDIA/Fuser/issues/2664\n T4 (scalar) is broadcasted and used in mul computation. It is also used to update T2 inplace.\n This causes a RW race. In this case, the aliased tensor is a producer of bcast op.\n \"\"\"\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.define_tensor(\n shape=[], contiguity=[], dtype=DataType.Float, is_cpu=False\n )\n S3 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T4 = fd.ops.add(T2, S3)\n S5 = fd.define_scalar(4194304, dtype=DataType.Int)\n T7 = fd.ops.broadcast_in_dim(T4, shape=[S5], broadcast_dims=[])\n T8 = fd.ops.mul(T1, T7)\n fd.add_output(T4, T2)\n fd.add_output(T8)\n\n inputs = [\n torch.randn((4194304,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4194304,), (1,)\n ),\n torch.randn((1,), dtype=torch.float32, device=\"cuda:0\").as_strided((), ()),\n ]\n # Reference out = T4 (aliased to inputs[-1]), T8\n ref_out = [inputs[-1] + 1.0, (inputs[-1] + 1.0) * inputs[0]]\n\n out, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n\n torch.testing.assert_close(inputs[-1], ref_out[0])\n torch.testing.assert_close(out[0], ref_out[1])\n\n\ndef test_issue2664_repro2(nvfuser_direct_test):\n \"\"\"\n Test for issue 2664 - tests broadcast in dim and inplace update.\n\n Migrated from `test_inplace_post_bcast` in legacy test_pointwise.py\n\n Example 2 for Issue 2664:\n T2 is broadcasted and used in mul/add compute. It is also summed (T8) and used to inplace update T2.\n In this case, the aliased tensor (T8) is a consumer of the bcast op.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2664_repro2","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2664_repro2#L1529-L1578","kind":"function","name":"test_issue2664_repro2","path":"tests/python/direct/test_repro.py","language":"python","start_line":1529,"end_line":1578,"context_start_line":1509,"context_end_line":1598,"code":" T7 = fd.ops.broadcast_in_dim(T4, shape=[S5], broadcast_dims=[])\n T8 = fd.ops.mul(T1, T7)\n fd.add_output(T4, T2)\n fd.add_output(T8)\n\n inputs = [\n torch.randn((4194304,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4194304,), (1,)\n ),\n torch.randn((1,), dtype=torch.float32, device=\"cuda:0\").as_strided((), ()),\n ]\n # Reference out = T4 (aliased to inputs[-1]), T8\n ref_out = [inputs[-1] + 1.0, (inputs[-1] + 1.0) * inputs[0]]\n\n out, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs)\n\n torch.testing.assert_close(inputs[-1], ref_out[0])\n torch.testing.assert_close(out[0], ref_out[1])\n\n\ndef test_issue2664_repro2(nvfuser_direct_test):\n \"\"\"\n Test for issue 2664 - tests broadcast in dim and inplace update.\n\n Migrated from `test_inplace_post_bcast` in legacy test_pointwise.py\n\n Example 2 for Issue 2664:\n T2 is broadcasted and used in mul/add compute. It is also summed (T8) and used to inplace update T2.\n In this case, the aliased tensor (T8) is a consumer of the bcast op.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.define_tensor(\n shape=[], contiguity=[], dtype=DataType.Float, is_cpu=False\n )\n S5 = fd.define_scalar(4194304, dtype=DataType.Int)\n T7 = fd.ops.broadcast_in_dim(T2, shape=[S5], broadcast_dims=[])\n T8 = fd.ops.sum(T7, dims=[0], keepdim=False)\n T9 = fd.ops.mul(T1, T7)\n T10 = fd.ops.add(T1, T7)\n fd.add_output(T8, T2)\n fd.add_output(T9)\n fd.add_output(T10)\n\n inputs = [\n torch.randn((4194304,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4194304,), (1,)\n ),\n torch.randn((1,), dtype=torch.float32, device=\"cuda:0\").as_strided((), ()),\n ]\n\n # Reference out = T8 (aliased to inputs[-1]), T9, T10\n ref_out = [\n inputs[-1] * inputs[0].size(0),\n inputs[-1] * inputs[0],\n inputs[0] + inputs[1],\n ]\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(inputs[-1], ref_out[0])\n nvfuser_direct_test.assertEqual(out[0], ref_out[1])\n nvfuser_direct_test.assertEqual(out[1], ref_out[2])\n\n\ndef test_issue2664_repro3(nvfuser_direct_test):\n \"\"\"\n Test for issue 2664 - tests broadcast in dim and inplace update.\n\n Migrated from `test_multi_inplace` in legacy test_pointwise.py\n\n Example 3 for Issue 2664: This case involves two inplace updates.\n T7 is aliased to T2: T7 is not a producer/consumer of the bcast op, but the aliased input T2 is a producer of the bcast op.\n T6 is aliased to T3: T6 is a consumer of the bcast op.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2664_repro3","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2664_repro3#L1581-L1628","kind":"function","name":"test_issue2664_repro3","path":"tests/python/direct/test_repro.py","language":"python","start_line":1581,"end_line":1628,"context_start_line":1561,"context_end_line":1648,"code":" torch.randn((4194304,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4194304,), (1,)\n ),\n torch.randn((1,), dtype=torch.float32, device=\"cuda:0\").as_strided((), ()),\n ]\n\n # Reference out = T8 (aliased to inputs[-1]), T9, T10\n ref_out = [\n inputs[-1] * inputs[0].size(0),\n inputs[-1] * inputs[0],\n inputs[0] + inputs[1],\n ]\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(inputs[-1], ref_out[0])\n nvfuser_direct_test.assertEqual(out[0], ref_out[1])\n nvfuser_direct_test.assertEqual(out[1], ref_out[2])\n\n\ndef test_issue2664_repro3(nvfuser_direct_test):\n \"\"\"\n Test for issue 2664 - tests broadcast in dim and inplace update.\n\n Migrated from `test_multi_inplace` in legacy test_pointwise.py\n\n Example 3 for Issue 2664: This case involves two inplace updates.\n T7 is aliased to T2: T7 is not a producer/consumer of the bcast op, but the aliased input T2 is a producer of the bcast op.\n T6 is aliased to T3: T6 is a consumer of the bcast op.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.define_tensor(\n shape=[], contiguity=[], dtype=DataType.Float, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[], contiguity=[], dtype=DataType.Float, is_cpu=False\n )\n T4 = fd.ops.broadcast_in_dim(T2, shape=T1.shape(), broadcast_dims=[])\n T5 = fd.ops.add(T1, T4)\n T6 = fd.ops.sum(T5, dims=[0], keepdim=False)\n S0 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T7 = fd.ops.add(T3, S0)\n fd.add_output(T6, T3)\n fd.add_output(T7, T2)\n\n inputs = [\n torch.randn((4194304,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4194304,), (1,)\n ),\n torch.randn((1,), dtype=torch.float32, device=\"cuda:0\").as_strided((), ()),\n torch.randn((1,), dtype=torch.float32, device=\"cuda:0\").as_strided((), ()),\n ]\n\n # Reference out = T6 (aliased to inputs[2]), T7 (aliased to inputs[1])\n ref_out = [inputs[-1] + 1.0, (inputs[0] + inputs[1]).sum(dim=-1)]\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(inputs[1], ref_out[0])\n nvfuser_direct_test.assertEqual(inputs[2], ref_out[1])\n\n\ndef test_issue2664_repro4(nvfuser_direct_test):\n \"\"\"\n Test for issue 2664 - tests broadcast in dim and inplace update.\n\n Migrated from `test_implicit_bcast_inplace` in legacy test_pointwise.py\n\n Example 4 for Issue 2664: There is no explicit broadcast. However, the\n aliased input has a broadcast dimension that is concretized in the fusion.\n T0 has a implicit broadcast which is used in add(T3) and neg (T4). T4 is\n used to inplace update T0, which causes RW race.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1],\n contiguity=[True, None],\n dtype=DataType.Float,","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2664_repro4","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2664_repro4#L1631-L1673","kind":"function","name":"test_issue2664_repro4","path":"tests/python/direct/test_repro.py","language":"python","start_line":1631,"end_line":1673,"context_start_line":1611,"context_end_line":1693,"code":" fd.add_output(T6, T3)\n fd.add_output(T7, T2)\n\n inputs = [\n torch.randn((4194304,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4194304,), (1,)\n ),\n torch.randn((1,), dtype=torch.float32, device=\"cuda:0\").as_strided((), ()),\n torch.randn((1,), dtype=torch.float32, device=\"cuda:0\").as_strided((), ()),\n ]\n\n # Reference out = T6 (aliased to inputs[2]), T7 (aliased to inputs[1])\n ref_out = [inputs[-1] + 1.0, (inputs[0] + inputs[1]).sum(dim=-1)]\n\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(inputs[1], ref_out[0])\n nvfuser_direct_test.assertEqual(inputs[2], ref_out[1])\n\n\ndef test_issue2664_repro4(nvfuser_direct_test):\n \"\"\"\n Test for issue 2664 - tests broadcast in dim and inplace update.\n\n Migrated from `test_implicit_bcast_inplace` in legacy test_pointwise.py\n\n Example 4 for Issue 2664: There is no explicit broadcast. However, the\n aliased input has a broadcast dimension that is concretized in the fusion.\n T0 has a implicit broadcast which is used in add(T3) and neg (T4). T4 is\n used to inplace update T0, which causes RW race.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1],\n contiguity=[True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.ops.add(T1, T0)\n T4 = fd.ops.neg(T0)\n fd.add_output(T3)\n fd.add_output(T4, T0)\n\n inputs = [\n torch.randn((4194304, 1), dtype=torch.float32, device=\"cuda:0\"),\n torch.randn((4194304, 128), dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n ref_out = [inputs[0] + inputs[1], -inputs[0]]\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(ref_out[0], out[0])\n nvfuser_direct_test.assertEqual(ref_out[1], inputs[0])\n\n\ndef test_issue2755(nvfuser_direct_test):\n \"\"\"\n Test for issue 2755 - tests slice operations with negation.\n\n This test verifies that slice operations work correctly with:\n - Basic tensor slicing with different start and end indices\n - Negation operations on sliced tensors\n - Multiple slice operations in sequence\n - Proper handling of tensor shapes and operations\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.define_tensor(shape=[-1])\n t1 = fd.ops.slice(\n t0,\n start_indices=[0],\n end_indices=[5],\n )","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2755","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2755#L1676-L1704","kind":"function","name":"test_issue2755","path":"tests/python/direct/test_repro.py","language":"python","start_line":1676,"end_line":1704,"context_start_line":1656,"context_end_line":1724,"code":" is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.ops.add(T1, T0)\n T4 = fd.ops.neg(T0)\n fd.add_output(T3)\n fd.add_output(T4, T0)\n\n inputs = [\n torch.randn((4194304, 1), dtype=torch.float32, device=\"cuda:0\"),\n torch.randn((4194304, 128), dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n ref_out = [inputs[0] + inputs[1], -inputs[0]]\n out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n nvfuser_direct_test.assertEqual(ref_out[0], out[0])\n nvfuser_direct_test.assertEqual(ref_out[1], inputs[0])\n\n\ndef test_issue2755(nvfuser_direct_test):\n \"\"\"\n Test for issue 2755 - tests slice operations with negation.\n\n This test verifies that slice operations work correctly with:\n - Basic tensor slicing with different start and end indices\n - Negation operations on sliced tensors\n - Multiple slice operations in sequence\n - Proper handling of tensor shapes and operations\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.define_tensor(shape=[-1])\n t1 = fd.ops.slice(\n t0,\n start_indices=[0],\n end_indices=[5],\n )\n t2 = fd.ops.neg(t1)\n t3 = fd.ops.slice(\n t2,\n start_indices=[0],\n end_indices=[2],\n )\n t4 = fd.ops.neg(t3)\n fd.add_output(t4)\n\n inputs = [torch.randn((10,), dtype=torch.float32, device=\"cuda:0\")]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2853(nvfuser_direct_test):\n \"\"\"\n Test for issue 2853 - tests that an error is raised if there are segments\n with CPU outputs.\n\n See https://github.com/NVIDIA/Fuser/issues/2853.\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n torch.randn(3, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0]) # CPU scalar tensor\n tv1 = fd.from_pytorch(inputs[1]) # CUDA input\n s0 = fd.define_scalar(3.0)\n # CPU scalar only segment that should raise an error\n t2 = fd.ops.add(tv0, s0) # Should be a CPU scalar tensor","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue2853","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue2853#L1707-L1735","kind":"function","name":"test_issue2853","path":"tests/python/direct/test_repro.py","language":"python","start_line":1707,"end_line":1735,"context_start_line":1687,"context_end_line":1755,"code":" def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.define_tensor(shape=[-1])\n t1 = fd.ops.slice(\n t0,\n start_indices=[0],\n end_indices=[5],\n )\n t2 = fd.ops.neg(t1)\n t3 = fd.ops.slice(\n t2,\n start_indices=[0],\n end_indices=[2],\n )\n t4 = fd.ops.neg(t3)\n fd.add_output(t4)\n\n inputs = [torch.randn((10,), dtype=torch.float32, device=\"cuda:0\")]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2853(nvfuser_direct_test):\n \"\"\"\n Test for issue 2853 - tests that an error is raised if there are segments\n with CPU outputs.\n\n See https://github.com/NVIDIA/Fuser/issues/2853.\n \"\"\"\n inputs = [\n torch.tensor(2.0, device=\"cpu\", dtype=torch.float),\n torch.randn(3, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0]) # CPU scalar tensor\n tv1 = fd.from_pytorch(inputs[1]) # CUDA input\n s0 = fd.define_scalar(3.0)\n # CPU scalar only segment that should raise an error\n t2 = fd.ops.add(tv0, s0) # Should be a CPU scalar tensor\n t3 = fd.ops.add(tv1, s0)\n fd.add_output(t2)\n fd.add_output(t3)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n with pytest.raises(\n RuntimeError, match=\"KernelExecutor does not support the Fusion provided.\"\n ):\n _ = fd.execute(inputs)\n\n\ndef test_issue3192(nvfuser_direct_test):\n \"\"\"\n Test for issue 3192 - tests squeeze and slice operations.\n\n This test verifies that squeeze and slice operations work correctly with:\n - Squeeze operation with two dimensions\n - Slice operation with one dimension\n - Negation operation\n \"\"\"\n\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 1, 2], contiguity=True)\n out = fd.ops.squeeze(inp, [0, 1])\n out = fd.ops.slice(out, [1], [2])\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 1, 2, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue3192","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue3192#L1738-L1758","kind":"function","name":"test_issue3192","path":"tests/python/direct/test_repro.py","language":"python","start_line":1738,"end_line":1758,"context_start_line":1718,"context_end_line":1778,"code":"\n def fusion_func(fd: FusionDefinition):\n tv0 = fd.from_pytorch(inputs[0]) # CPU scalar tensor\n tv1 = fd.from_pytorch(inputs[1]) # CUDA input\n s0 = fd.define_scalar(3.0)\n # CPU scalar only segment that should raise an error\n t2 = fd.ops.add(tv0, s0) # Should be a CPU scalar tensor\n t3 = fd.ops.add(tv1, s0)\n fd.add_output(t2)\n fd.add_output(t3)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n with pytest.raises(\n RuntimeError, match=\"KernelExecutor does not support the Fusion provided.\"\n ):\n _ = fd.execute(inputs)\n\n\ndef test_issue3192(nvfuser_direct_test):\n \"\"\"\n Test for issue 3192 - tests squeeze and slice operations.\n\n This test verifies that squeeze and slice operations work correctly with:\n - Squeeze operation with two dimensions\n - Slice operation with one dimension\n - Negation operation\n \"\"\"\n\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 1, 2], contiguity=True)\n out = fd.ops.squeeze(inp, [0, 1])\n out = fd.ops.slice(out, [1], [2])\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 1, 2, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(\n out_tensors[0], in_tensor.squeeze([0, 1])[1:2], rtol=0, atol=0\n )\n\n\ndef test_issue3227(nvfuser_direct_test):\n \"\"\"\n Test for issue 3227 - tests broadcast to different extents.\n\n Migrated from `test_bcast_different_extent` in legacy test_pointwise.py\n\n This test verifies that broadcast operations work correctly with:\n - Different extents for broadcasting\n - Multiple broadcast operations in sequence\n - Proper handling of tensor shapes and operations\n \"\"\"\n\n def nvfuser_fusion(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, 4, 2, 3],\n contiguity=[None, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue3227","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue3227#L1761-L1838","kind":"function","name":"test_issue3227","path":"tests/python/direct/test_repro.py","language":"python","start_line":1761,"end_line":1838,"context_start_line":1741,"context_end_line":1858,"code":"\n This test verifies that squeeze and slice operations work correctly with:\n - Squeeze operation with two dimensions\n - Slice operation with one dimension\n - Negation operation\n \"\"\"\n\n def fusion_func(fd: FusionDefinition):\n inp = fd.define_tensor([1, 1, 2], contiguity=True)\n out = fd.ops.squeeze(inp, [0, 1])\n out = fd.ops.slice(out, [1], [2])\n fd.add_output(out)\n\n in_tensor = torch.randn(1, 1, 2, device=\"cuda\")\n out_tensors, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, [in_tensor])\n nvfuser_direct_test.assertEqual(\n out_tensors[0], in_tensor.squeeze([0, 1])[1:2], rtol=0, atol=0\n )\n\n\ndef test_issue3227(nvfuser_direct_test):\n \"\"\"\n Test for issue 3227 - tests broadcast to different extents.\n\n Migrated from `test_bcast_different_extent` in legacy test_pointwise.py\n\n This test verifies that broadcast operations work correctly with:\n - Different extents for broadcasting\n - Multiple broadcast operations in sequence\n - Proper handling of tensor shapes and operations\n \"\"\"\n\n def nvfuser_fusion(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, 4, 2, 3],\n contiguity=[None, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 5, 2, 3],\n contiguity=[None, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, 2, 3],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n S1 = fd.define_scalar(1, dtype=DataType.Int)\n S2 = fd.define_scalar(1, dtype=DataType.Int)\n S3 = fd.define_scalar(2, dtype=DataType.Int)\n S4 = fd.define_scalar(3, dtype=DataType.Int)\n T3 = fd.ops.broadcast_in_dim(\n T2, shape=[S1, S2, S3, S4], broadcast_dims=[1, 2, 3]\n )\n # bcast T2 to [1, 4, 2, 3]\n S5 = fd.define_scalar(1, dtype=DataType.Int)\n S6 = fd.define_scalar(4, dtype=DataType.Int)\n S7 = fd.define_scalar(2, dtype=DataType.Int)\n S8 = fd.define_scalar(3, dtype=DataType.Int)\n T4 = fd.ops.broadcast_in_dim(\n T3, shape=[S5, S6, S7, S8], broadcast_dims=[0, 1, 2, 3]\n )\n # bcast T2 to [1, 5, 2, 3]\n S9 = fd.define_scalar(1, dtype=DataType.Int)\n S10 = fd.define_scalar(5, dtype=DataType.Int)\n S11 = fd.define_scalar(2, dtype=DataType.Int)\n S12 = fd.define_scalar(3, dtype=DataType.Int)\n T5 = fd.ops.broadcast_in_dim(\n T3, shape=[S9, S10, S11, S12], broadcast_dims=[0, 1, 2, 3]\n )\n # add with T0\n T6 = fd.ops.add(T4, T0)\n # add with T1\n T7 = fd.ops.add(T5, T1)\n fd.add_output(T6)\n fd.add_output(T7)\n\n inputs = [\n torch.rand(24, dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 4, 2, 3), (24, 6, 3, 1)\n ),\n torch.rand(30, dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 5, 2, 3), (30, 6, 3, 1)\n ),\n torch.rand(6, dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 2, 3), (6, 3, 1)\n ),\n ]\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion, inputs)\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0] + inputs[2])\n nvfuser_direct_test.assertEqual(nvf_out[1], inputs[1] + inputs[2])\n\n\ndef test_issue3292(nvfuser_direct_test):\n \"\"\"\n Test for issue 3292 - tests complex tensor operations with manual normalization and padding.\n\n This test verifies that complex operations work correctly with:\n - Tensor reshaping and permutation operations\n - Multiple slice operations with manual normalization\n - Negation and concatenation operations with manual padding\n - Multiplication and addition operations\n - Complex tensor manipulation sequences\n - Proper handling of tensor shapes and operations\n \"\"\"\n inputs = [\n torch.testing.make_tensor((5, 5, 576), dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T2 = fd.define_tensor(","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue3292","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue3292#L1841-L1921","kind":"function","name":"test_issue3292","path":"tests/python/direct/test_repro.py","language":"python","start_line":1841,"end_line":1921,"context_start_line":1821,"context_end_line":1941,"code":" T7 = fd.ops.add(T5, T1)\n fd.add_output(T6)\n fd.add_output(T7)\n\n inputs = [\n torch.rand(24, dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 4, 2, 3), (24, 6, 3, 1)\n ),\n torch.rand(30, dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 5, 2, 3), (30, 6, 3, 1)\n ),\n torch.rand(6, dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 2, 3), (6, 3, 1)\n ),\n ]\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion, inputs)\n nvfuser_direct_test.assertEqual(nvf_out[0], inputs[0] + inputs[2])\n nvfuser_direct_test.assertEqual(nvf_out[1], inputs[1] + inputs[2])\n\n\ndef test_issue3292(nvfuser_direct_test):\n \"\"\"\n Test for issue 3292 - tests complex tensor operations with manual normalization and padding.\n\n This test verifies that complex operations work correctly with:\n - Tensor reshaping and permutation operations\n - Multiple slice operations with manual normalization\n - Negation and concatenation operations with manual padding\n - Multiplication and addition operations\n - Complex tensor manipulation sequences\n - Proper handling of tensor shapes and operations\n \"\"\"\n inputs = [\n torch.testing.make_tensor((5, 5, 576), dtype=torch.float32, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T2 = fd.define_tensor(\n shape=[5, 5, 576],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T30 = fd.ops.reshape(T2, new_shape=[5, 5, 1, 9, 64])\n T31 = fd.ops.permute(T30, dims=[0, 2, 3, 1, 4])\n T50 = fd.ops.slice(\n T31,\n start_indices=[0, 0, 0, 0, 0],\n end_indices=[5, 1, 7, 5, 64],\n strides=[1, 1, 1, 1, 1],\n manual_normalization=0,\n )\n T108 = fd.ops.reshape(T50, new_shape=[5, 7, 5, 64])\n T136 = fd.ops.slice(\n T108,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 7, 5, 32],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T152 = fd.ops.slice(\n T108,\n start_indices=[0, 0, 0, 32],\n end_indices=[5, 7, 5, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T153 = fd.ops.neg(T152)\n T154 = fd.ops.cat([T153, T136], dim=-1, manual_padding=0)\n T161 = fd.ops.mul(T108, T108)\n T168 = fd.ops.mul(T154, T154)\n T169 = fd.ops.add(T161, T168)\n T185 = fd.ops.slice(\n T108,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 7, 5, 32],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T201 = fd.ops.slice(\n T108,\n start_indices=[0, 0, 0, 32],\n end_indices=[5, 7, 5, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T202 = fd.ops.neg(T201)\n T203 = fd.ops.cat([T202, T185], dim=-1, manual_padding=0)\n T205 = fd.ops.mul(T203, T203)\n T222 = fd.ops.slice(\n T108,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 7, 5, 0],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T223 = fd.ops.cat([T169, T222], dim=-1, manual_padding=0)\n fd.add_output(T223)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_issue3369(nvfuser_direct_test):\n \"\"\"\n Test for issue 3369 - tests square linear operations.\n\n This test verifies that square linear operations work correctly.\n \"\"\"\n\n def nvfuser_fusion_id28(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[5, 5],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[5, 5],\n contiguity=[True, True],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue3369","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue3369#L1924-L1961","kind":"function","name":"test_issue3369","path":"tests/python/direct/test_repro.py","language":"python","start_line":1924,"end_line":1961,"context_start_line":1904,"context_end_line":1981,"code":" end_indices=[5, 7, 5, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T202 = fd.ops.neg(T201)\n T203 = fd.ops.cat([T202, T185], dim=-1, manual_padding=0)\n T205 = fd.ops.mul(T203, T203)\n T222 = fd.ops.slice(\n T108,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 7, 5, 0],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T223 = fd.ops.cat([T169, T222], dim=-1, manual_padding=0)\n fd.add_output(T223)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_issue3369(nvfuser_direct_test):\n \"\"\"\n Test for issue 3369 - tests square linear operations.\n\n This test verifies that square linear operations work correctly.\n \"\"\"\n\n def nvfuser_fusion_id28(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[5, 5],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[5, 5],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[5],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T3 = fd.ops.linear(T0, T1, T2)\n fd.add_output(T3)\n\n inputs = [\n torch.testing.make_tensor((5, 5), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((5, 5), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((5,), dtype=torch.float32, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id28, inputs, validate_results=True)\n\n\ndef test_issue4444(nvfuser_direct_test):\n \"\"\"\n Test for issue 4444 - complex tensor operations with multiple slice operations,\n manual normalization, padding, and reshaping operations.\n\n This test validates:\n - Multiple slice operations with manual normalization\n - Complex tensor reshaping and permutation operations\n - Manual padding operations with scalar values\n - Broadcast operations with specific dimensions\n - Cast operations between different data types\n - Complex mathematical sequences involving negation, addition, and multiplication\n - Proper handling of tensor shapes and operations\n - Scalar definition and vector operations\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue4444","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue4444#L1964-L2169","kind":"function","name":"test_issue4444","path":"tests/python/direct/test_repro.py","language":"python","start_line":1964,"end_line":2169,"context_start_line":1944,"context_end_line":2189,"code":" stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[5],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T3 = fd.ops.linear(T0, T1, T2)\n fd.add_output(T3)\n\n inputs = [\n torch.testing.make_tensor((5, 5), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((5, 5), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((5,), dtype=torch.float32, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id28, inputs, validate_results=True)\n\n\ndef test_issue4444(nvfuser_direct_test):\n \"\"\"\n Test for issue 4444 - complex tensor operations with multiple slice operations,\n manual normalization, padding, and reshaping operations.\n\n This test validates:\n - Multiple slice operations with manual normalization\n - Complex tensor reshaping and permutation operations\n - Manual padding operations with scalar values\n - Broadcast operations with specific dimensions\n - Cast operations between different data types\n - Complex mathematical sequences involving negation, addition, and multiplication\n - Proper handling of tensor shapes and operations\n - Scalar definition and vector operations\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, 64, 16384, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[16384, 128],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[16384, 128],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 64, 16384, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 64, 16384, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T20 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 64, 16384, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T21 = fd.ops.cast(T20, dtype=DataType.Float)\n T27 = fd.ops.broadcast_in_dim(\n T1, shape=[1, 64, 16384, 128], broadcast_dims=[2, 3]\n )\n T28 = fd.ops.mul(T27, T21)\n T29 = fd.ops.cast(T28, dtype=DataType.BFloat16)\n T35 = fd.ops.broadcast_in_dim(\n T2, shape=[1, 64, 16384, 128], broadcast_dims=[2, 3]\n )\n T51 = fd.ops.slice(\n T29,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 64, 16384, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T52 = fd.ops.mul(T35, T21)\n S53 = fd.define_scalar(0, dtype=DataType.Int)\n T59 = fd.ops.full(\n shape=[1, 64, 16384, 0], fill_value=S53, dtype=DataType.BFloat16\n )\n T75 = fd.ops.slice(\n T3,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 64, 16384, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T76 = fd.ops.cast(T51, dtype=DataType.Float)\n S77 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T87 = fd.ops.pad(T59, [0, 128, 0, 0, 0, 0, 0, 0], S77)\n T88 = fd.ops.cast(T75, dtype=DataType.Float)\n T89 = fd.ops.neg(T76)\n T90 = fd.ops.cast(T87, dtype=DataType.Float)\n T91 = fd.ops.mul(T27, T88)\n T92 = fd.ops.cast(T89, dtype=DataType.BFloat16)\n T93 = fd.ops.add(T90, T52)\n T94 = fd.ops.cast(T91, dtype=DataType.BFloat16)\n S95 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T105 = fd.ops.pad(T92, [64, 0, 0, 0, 0, 0, 0, 0], S95)\n T121 = fd.ops.slice(\n T94,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 64, 16384, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T122 = fd.ops.mul(T35, T88)\n T123 = fd.ops.cast(T105, dtype=DataType.Float)\n T124 = fd.ops.cast(T121, dtype=DataType.Float)\n T140 = fd.ops.slice(\n T29,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 64, 16384, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T141 = fd.ops.add(T93, T123)\n T142 = fd.ops.neg(T124)\n S143 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T153 = fd.ops.pad(T140, [0, 64, 0, 0, 0, 0, 0, 0], S143)\n T154 = fd.ops.cast(T142, dtype=DataType.BFloat16)\n T155 = fd.ops.add(T90, T122)\n T156 = fd.ops.cast(T153, dtype=DataType.Float)\n S157 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T167 = fd.ops.pad(T154, [64, 0, 0, 0, 0, 0, 0, 0], S157)\n T168 = fd.ops.add(T141, T156)\n T169 = fd.ops.cast(T167, dtype=DataType.Float)\n T170 = fd.ops.cast(T168, dtype=DataType.BFloat16)\n T186 = fd.ops.slice(\n T94,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 64, 16384, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T187 = fd.ops.add(T155, T169)\n T194 = fd.ops.reshape(T4, new_shape=[1, 8, 8, 16384, 128])\n T201 = fd.ops.reshape(T170, new_shape=[1, 8, 8, 16384, 128])\n S202 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T212 = fd.ops.pad(T186, [0, 64, 0, 0, 0, 0, 0, 0], S202)\n T213 = fd.ops.cast(T194, dtype=DataType.Float)\n T214 = fd.ops.cast(T201, dtype=DataType.Float)\n T215 = fd.ops.cast(T212, dtype=DataType.Float)\n T216 = fd.ops.sum(T213, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T217 = fd.ops.sum(T214, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T218 = fd.ops.add(T187, T215)\n T219 = fd.ops.cast(T216, dtype=DataType.BFloat16)\n T220 = fd.ops.cast(T217, dtype=DataType.BFloat16)\n T221 = fd.ops.cast(T218, dtype=DataType.BFloat16)\n T228 = fd.ops.broadcast_in_dim(\n T219, shape=[1, 8, 1, 16384, 128], broadcast_dims=[1, 3, 4]\n )\n T235 = fd.ops.broadcast_in_dim(\n T220, shape=[1, 8, 1, 16384, 128], broadcast_dims=[1, 3, 4]\n )\n T242 = fd.ops.reshape(T221, new_shape=[1, 8, 8, 16384, 128])\n T243 = fd.ops.cat([T242, T235, T228], dim=2, manual_padding=0)\n T244 = fd.ops.permute(T243, dims=[0, 3, 1, 2, 4])\n T249 = fd.ops.reshape(T244, new_shape=[1, 16384, 10240])\n T253 = fd.ops.reshape(T249, new_shape=[16384, 10240])\n T254 = fd.ops.permute(T253, dims=[1, 0])\n fd.add_output(T253)\n fd.add_output(T254)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.testing.make_tensor(\n (1, 64, 16384, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (16384, 128),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (16384, 128),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 64, 16384, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 64, 16384, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue4459(nvfuser_direct_test):\n \"\"\"\n Test for issue 4459 - complex tensor operations with broadcast, reshape, and mathematical operations.\n\n This test verifies complex tensor operations involving broadcast operations,\n tensor reshaping, and mathematical sequences with multiple operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4, 32],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0, 1],\n )\n T1 = fd.define_tensor(\n shape=[4, 32, 1, 1, 1],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue4459","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue4459#L2172-L2372","kind":"function","name":"test_issue4459","path":"tests/python/direct/test_repro.py","language":"python","start_line":2172,"end_line":2372,"context_start_line":2152,"context_end_line":2392,"code":" high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 64, 16384, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 64, 16384, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue4459(nvfuser_direct_test):\n \"\"\"\n Test for issue 4459 - complex tensor operations with broadcast, reshape, and mathematical operations.\n\n This test verifies complex tensor operations involving broadcast operations,\n tensor reshaping, and mathematical sequences with multiple operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4, 32],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0, 1],\n )\n T1 = fd.define_tensor(\n shape=[4, 32, 1, 1, 1],\n contiguity=[True, True, None, None, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[4, 3, 2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[4, 32, 10, 64, 64],\n contiguity=[True, True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[4, 3, 2, 1, 0],\n )\n T3 = fd.define_tensor(\n shape=[320],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T4 = fd.define_tensor(\n shape=[320],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T5 = fd.define_tensor(\n shape=[4, 320, 66, 66],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T12 = fd.ops.broadcast_in_dim(T0, shape=[4, 32, 1, 1, 1], broadcast_dims=[0, 1])\n T19 = fd.ops.broadcast_in_dim(\n T12, shape=[4, 32, 10, 64, 64], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T26 = fd.ops.broadcast_in_dim(\n T1, shape=[4, 32, 10, 64, 64], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T27 = fd.ops.sub(T2, T19)\n T33 = fd.ops.reshape(T3, new_shape=[1, 320, 1, 1])\n T34 = fd.ops.mul(T27, T26)\n T40 = fd.ops.reshape(T4, new_shape=[1, 320, 1, 1])\n T46 = fd.ops.broadcast_in_dim(\n T33, shape=[4, 320, 64, 64], broadcast_dims=[0, 1, 2, 3]\n )\n T52 = fd.ops.reshape(T34, new_shape=[4, 320, 64, 64])\n T58 = fd.ops.broadcast_in_dim(\n T40, shape=[4, 320, 64, 64], broadcast_dims=[0, 1, 2, 3]\n )\n T59 = fd.ops.mul(T52, T46)\n T60 = fd.ops.add(T59, T58)\n T61 = fd.ops.neg(T60)\n T62 = fd.ops.exp(T61)\n S63 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T73 = fd.ops.pad(T5, [-1, -1, -1, -1, 0, 0, 0, 0], S63)\n S74 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T75 = fd.ops.add(S74, T62)\n T76 = fd.ops.mul(T60, T73)\n T77 = fd.ops.reciprocal(T75)\n T78 = fd.ops.neg(T76)\n T79 = fd.ops.mul(T78, T77)\n T80 = fd.ops.mul(T79, T77)\n T81 = fd.ops.mul(T80, T62)\n T82 = fd.ops.neg(T81)\n T83 = fd.ops.mul(T77, T73)\n T84 = fd.ops.add(T83, T82)\n T85 = fd.ops.mul(T46, T84)\n T92 = fd.ops.reshape(T85, new_shape=[4, 32, 10, 64, 64])\n T93 = fd.ops.mul(T27, T92)\n T94 = fd.ops.sum(T93, dims=[2, 3, 4], keepdim=False, dtype=DataType.Null)\n T101 = fd.ops.broadcast_in_dim(\n T94, shape=[4, 32, 1, 1, 1], broadcast_dims=[0, 1]\n )\n S102 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T103 = fd.ops.pow(T1, S102)\n S104 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T105 = fd.ops.mul(S104, T101)\n T106 = fd.ops.mul(T26, T92)\n T107 = fd.ops.mul(T105, T103)\n T108 = fd.ops.neg(T106)\n T109 = fd.ops.sum(T107, dims=[2, 3, 4], keepdim=False, dtype=DataType.Null)\n T110 = fd.ops.sum(T108, dims=[2, 3, 4], keepdim=False, dtype=DataType.Null)\n T117 = fd.ops.broadcast_in_dim(\n T0, shape=[4, 32, 1, 1, 1], broadcast_dims=[0, 1]\n )\n T124 = fd.ops.broadcast_in_dim(\n T109, shape=[4, 32, 1, 1, 1], broadcast_dims=[0, 1]\n )\n T131 = fd.ops.broadcast_in_dim(\n T110, shape=[4, 32, 1, 1, 1], broadcast_dims=[0, 1]\n )\n T138 = fd.ops.broadcast_in_dim(\n T117, shape=[4, 32, 10, 64, 64], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T145 = fd.ops.broadcast_in_dim(\n T124, shape=[4, 32, 10, 64, 64], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T146 = fd.ops.sum(T131, dims=[2, 3, 4], keepdim=False, dtype=DataType.Null)\n T147 = fd.ops.sub(T2, T138)\n S148 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T149 = fd.ops.mul(S148, T145)\n T156 = fd.ops.broadcast_in_dim(\n T146, shape=[4, 32, 1, 1, 1], broadcast_dims=[0, 1]\n )\n T157 = fd.ops.mul(T149, T147)\n T164 = fd.ops.broadcast_in_dim(\n T156, shape=[4, 32, 10, 64, 64], broadcast_dims=[0, 1, 2, 3, 4]\n )\n S165 = fd.define_scalar(40960.0, dtype=DataType.Double)\n S166 = fd.ops.reciprocal(S165)\n T167 = fd.ops.mul(T157, S166)\n S168 = fd.define_scalar(2.44141e-05, dtype=DataType.Double)\n T169 = fd.ops.mul(S168, T164)\n T170 = fd.ops.add(T169, T167)\n T171 = fd.ops.add(T106, T170)\n T177 = fd.ops.reshape(T171, new_shape=[4, 320, 64, 64])\n T184 = fd.ops.reshape(T177, new_shape=[1, 4, 320, 64, 64])\n T185 = fd.ops.permute(T184, dims=[0, 3, 4, 1, 2])\n T192 = fd.ops.reshape(T185, new_shape=[1, 1, 4096, 4, 320])\n T193 = fd.ops.mul(T52, T84)\n T194 = fd.ops.sum(T192, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T195 = fd.ops.sum(T193, dims=[0, 2, 3], keepdim=False, dtype=DataType.Null)\n T196 = fd.ops.sum(T84, dims=[0, 2, 3], keepdim=False, dtype=DataType.Null)\n T200 = fd.ops.reshape(T194, new_shape=[16384, 320])\n T206 = fd.ops.broadcast_in_dim(T195, shape=[1, 320, 1, 1], broadcast_dims=[1])\n T212 = fd.ops.broadcast_in_dim(T196, shape=[1, 320, 1, 1], broadcast_dims=[1])\n T213 = fd.ops.permute(T200, dims=[1, 0])\n T214 = fd.ops.sum(T194, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T217 = fd.ops.reshape(T206, new_shape=[320])\n T220 = fd.ops.reshape(T212, new_shape=[320])\n fd.add_output(T177)\n fd.add_output(T200)\n fd.add_output(T213)\n fd.add_output(T214)\n fd.add_output(T217)\n fd.add_output(T220)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.randn(128, dtype=torch.float32, device=\"cuda:0\").as_strided(\n (4, 32), (1, 4)\n ),\n torch.testing.make_tensor(\n (4, 32, 1, 1, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (4, 32, 10, 64, 64),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (320,),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (320,),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (4, 320, 66, 66),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue4670(nvfuser_direct_test):\n \"\"\"\n Test for issue 4670 - iota operations with broadcast and comparison operations.\n\n This test verifies iota operations with scalar parameters, broadcast operations,\n and comparison operations with conditional logic.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(129, dtype=DataType.Int)\n S1 = fd.define_scalar(0, dtype=DataType.Int)\n S2 = fd.define_scalar(1, dtype=DataType.Int)\n T3 = fd.ops.iota(S0, S1, S2, dtype=DataType.Int)\n T4 = fd.ops.broadcast(T3, is_broadcast_dim=[True, False])\n S5 = fd.define_scalar(128, dtype=DataType.Int)\n S6 = fd.ops.size(T3, dim=0)\n T8 = fd.ops.expand(T4, shape=[S5, S6])\n S9 = fd.define_scalar(128, dtype=DataType.Int)","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue4670","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue4670#L2375-L2419","kind":"function","name":"test_issue4670","path":"tests/python/direct/test_repro.py","language":"python","start_line":2375,"end_line":2419,"context_start_line":2355,"context_end_line":2439,"code":" high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (320,),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (4, 320, 66, 66),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue4670(nvfuser_direct_test):\n \"\"\"\n Test for issue 4670 - iota operations with broadcast and comparison operations.\n\n This test verifies iota operations with scalar parameters, broadcast operations,\n and comparison operations with conditional logic.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(129, dtype=DataType.Int)\n S1 = fd.define_scalar(0, dtype=DataType.Int)\n S2 = fd.define_scalar(1, dtype=DataType.Int)\n T3 = fd.ops.iota(S0, S1, S2, dtype=DataType.Int)\n T4 = fd.ops.broadcast(T3, is_broadcast_dim=[True, False])\n S5 = fd.define_scalar(128, dtype=DataType.Int)\n S6 = fd.ops.size(T3, dim=0)\n T8 = fd.ops.expand(T4, shape=[S5, S6])\n S9 = fd.define_scalar(128, dtype=DataType.Int)\n S10 = fd.define_scalar(0, dtype=DataType.Int)\n S11 = fd.define_scalar(1, dtype=DataType.Int)\n T12 = fd.ops.iota(S9, S10, S11, dtype=DataType.Int)\n T13 = fd.ops.broadcast(T12, is_broadcast_dim=[False, True])\n S14 = fd.ops.size(T12, dim=0)\n S15 = fd.define_scalar(129, dtype=DataType.Int)\n T17 = fd.ops.expand(T13, shape=[S14, S15])\n T18 = fd.ops.gt(T8, T17)\n T19 = fd.ops.broadcast(T3, is_broadcast_dim=[True, False])\n S20 = fd.define_scalar(128, dtype=DataType.Int)\n T22 = fd.ops.expand(T19, shape=[S20, S6])\n T23 = fd.ops.broadcast(T12, is_broadcast_dim=[False, True])\n S24 = fd.define_scalar(129, dtype=DataType.Int)\n T26 = fd.ops.expand(T23, shape=[S14, S24])\n T27 = fd.ops.sub(T22, T26)\n S28 = fd.define_scalar(1, dtype=DataType.Int)\n T29 = fd.ops.ge(T27, S28)\n S30 = fd.define_scalar(-3.38953e38, dtype=DataType.BFloat16)\n S31 = fd.define_scalar(128, dtype=DataType.Int)\n S32 = fd.define_scalar(129, dtype=DataType.Int)\n T34 = fd.ops.full(shape=[S31, S32], fill_value=S30, dtype=DataType.BFloat16)\n S35 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T36 = fd.ops.where(T29, T34, S35)\n fd.add_output(T18)\n fd.add_output(T36)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, [], validate_results=True)\n\n\ndef test_ws_tma_normalization1(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374765 - Gemma-7b model failure with vectorized domains.\n\n This test verifies complex tensor operations with BFloat16 data type,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4096, 3072],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_ws_tma_normalization1","uri":"program://Fuser/function/tests.python.direct.test_repro.test_ws_tma_normalization1#L2422-L2570","kind":"function","name":"test_ws_tma_normalization1","path":"tests/python/direct/test_repro.py","language":"python","start_line":2422,"end_line":2570,"context_start_line":2402,"context_end_line":2590,"code":" S20 = fd.define_scalar(128, dtype=DataType.Int)\n T22 = fd.ops.expand(T19, shape=[S20, S6])\n T23 = fd.ops.broadcast(T12, is_broadcast_dim=[False, True])\n S24 = fd.define_scalar(129, dtype=DataType.Int)\n T26 = fd.ops.expand(T23, shape=[S14, S24])\n T27 = fd.ops.sub(T22, T26)\n S28 = fd.define_scalar(1, dtype=DataType.Int)\n T29 = fd.ops.ge(T27, S28)\n S30 = fd.define_scalar(-3.38953e38, dtype=DataType.BFloat16)\n S31 = fd.define_scalar(128, dtype=DataType.Int)\n S32 = fd.define_scalar(129, dtype=DataType.Int)\n T34 = fd.ops.full(shape=[S31, S32], fill_value=S30, dtype=DataType.BFloat16)\n S35 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T36 = fd.ops.where(T29, T34, S35)\n fd.add_output(T18)\n fd.add_output(T36)\n\n nvfuser_direct_test.exec_nvfuser(fusion_func, [], validate_results=True)\n\n\ndef test_ws_tma_normalization1(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374765 - Gemma-7b model failure with vectorized domains.\n\n This test verifies complex tensor operations with BFloat16 data type,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4096, 3072],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[4096, 3072],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[3072],\n contiguity=[True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n T3 = fd.define_tensor(\n shape=[1, 4096, 3072],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 4096, 1],\n contiguity=[None, True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T5 = fd.define_tensor(\n shape=[1, 4096, 3072],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T10 = fd.ops.reshape(T0, new_shape=[1, 4096, 3072])\n T15 = fd.ops.reshape(T1, new_shape=[1, 4096, 3072])\n T16 = fd.ops.cast(T2, dtype=DataType.Float)\n T17 = fd.ops.cast(T10, dtype=DataType.Float)\n T18 = fd.ops.cast(T15, dtype=DataType.Float)\n S19 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T20 = fd.ops.add(S19, T16)\n T21 = fd.ops.add(T18, T17)\n T26 = fd.ops.broadcast_in_dim(T20, shape=[1, 4096, 3072], broadcast_dims=[2])\n T27 = fd.ops.mul(T26, T21)\n T28 = fd.ops.cast(T3, dtype=DataType.Float)\n T29 = fd.ops.mul(T28, T27)\n T30 = fd.ops.sum(T29, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T35 = fd.ops.broadcast_in_dim(T30, shape=[1, 4096, 1], broadcast_dims=[1])\n S36 = fd.define_scalar(3.00000, dtype=DataType.Float)\n T37 = fd.ops.pow(T4, S36)\n S38 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T39 = fd.ops.mul(S38, T35)\n T40 = fd.ops.mul(T39, T37)\n S41 = fd.define_scalar(3072.00, dtype=DataType.Double)\n S42 = fd.ops.reciprocal(S41)\n T43 = fd.ops.mul(T40, S42)\n T44 = fd.ops.sum(T43, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T48 = fd.ops.broadcast_in_dim(T44, shape=[1, 4096], broadcast_dims=[1])\n T53 = fd.ops.broadcast_in_dim(T48, shape=[1, 4096, 1], broadcast_dims=[0, 1])\n T58 = fd.ops.broadcast_in_dim(\n T53, shape=[1, 4096, 3072], broadcast_dims=[0, 1, 2]\n )\n T63 = fd.ops.broadcast_in_dim(\n T4, shape=[1, 4096, 3072], broadcast_dims=[0, 1, 2]\n )\n T64 = fd.ops.mul(T28, T58)\n T65 = fd.ops.mul(T63, T27)\n T66 = fd.ops.add(T65, T64)\n T67 = fd.ops.add(T66, T64)\n T68 = fd.ops.cast(T5, dtype=DataType.Float)\n T69 = fd.ops.add(T68, T67)\n T70 = fd.ops.mul(T28, T63)\n T71 = fd.ops.mul(T70, T21)\n T72 = fd.ops.sum(T71, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T73 = fd.ops.cast(T69, dtype=DataType.BFloat16)\n T74 = fd.ops.cast(T72, dtype=DataType.BFloat16)\n T78 = fd.ops.reshape(T73, new_shape=[4096, 3072])\n T79 = fd.ops.permute(T78, dims=[1, 0])\n fd.add_output(T79)\n fd.add_output(T78)\n fd.add_output(T73)\n fd.add_output(T74)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.testing.make_tensor(\n (4096, 3072),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (4096, 3072),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (3072,),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 3072),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 3072),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization2(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374766 - multiple model failures with circular-buffer errors.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[147456, 128],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[128],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_ws_tma_normalization2","uri":"program://Fuser/function/tests.python.direct.test_repro.test_ws_tma_normalization2#L2573-L2727","kind":"function","name":"test_ws_tma_normalization2","path":"tests/python/direct/test_repro.py","language":"python","start_line":2573,"end_line":2727,"context_start_line":2553,"context_end_line":2747,"code":" high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 3072),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization2(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374766 - multiple model failures with circular-buffer errors.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[147456, 128],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[128],\n contiguity=[True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.define_tensor(\n shape=[288, 512],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.define_tensor(\n shape=[288, 512, 128],\n contiguity=[True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[288, 512, 1],\n contiguity=[True, True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T9 = fd.ops.reshape(T0, new_shape=[288, 512, 128])\n T14 = fd.ops.broadcast_in_dim(T1, shape=[288, 512, 128], broadcast_dims=[2])\n T19 = fd.ops.broadcast_in_dim(T2, shape=[288, 512, 1], broadcast_dims=[0, 1])\n T20 = fd.ops.cast(T9, dtype=DataType.Float)\n T21 = fd.ops.cast(T14, dtype=DataType.Float)\n T26 = fd.ops.broadcast_in_dim(\n T19, shape=[288, 512, 128], broadcast_dims=[0, 1, 2]\n )\n T27 = fd.ops.cast(T3, dtype=DataType.Float)\n T28 = fd.ops.mul(T21, T20)\n T29 = fd.ops.sub(T27, T26)\n T30 = fd.ops.mul(T29, T28)\n T31 = fd.ops.sum(T30, dims=[2], keepdim=False, dtype=DataType.Null)\n T36 = fd.ops.broadcast_in_dim(T31, shape=[288, 512, 1], broadcast_dims=[0, 1])\n T41 = fd.ops.broadcast_in_dim(\n T4, shape=[288, 512, 128], broadcast_dims=[0, 1, 2]\n )\n S42 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T43 = fd.ops.pow(T4, S42)\n S44 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T45 = fd.ops.mul(S44, T36)\n T46 = fd.ops.mul(T41, T28)\n T47 = fd.ops.mul(T45, T43)\n T48 = fd.ops.neg(T46)\n T49 = fd.ops.sum(T47, dims=[2], keepdim=False, dtype=DataType.Null)\n T50 = fd.ops.sum(T48, dims=[2], keepdim=False, dtype=DataType.Null)\n T55 = fd.ops.broadcast_in_dim(T2, shape=[288, 512, 1], broadcast_dims=[0, 1])\n T60 = fd.ops.broadcast_in_dim(T49, shape=[288, 512, 1], broadcast_dims=[0, 1])\n T65 = fd.ops.broadcast_in_dim(T50, shape=[288, 512, 1], broadcast_dims=[0, 1])\n T70 = fd.ops.broadcast_in_dim(\n T55, shape=[288, 512, 128], broadcast_dims=[0, 1, 2]\n )\n T75 = fd.ops.broadcast_in_dim(\n T60, shape=[288, 512, 128], broadcast_dims=[0, 1, 2]\n )\n T76 = fd.ops.sum(T65, dims=[2], keepdim=False, dtype=DataType.Null)\n T77 = fd.ops.sub(T27, T70)\n S78 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T79 = fd.ops.mul(S78, T75)\n T84 = fd.ops.broadcast_in_dim(T76, shape=[288, 512, 1], broadcast_dims=[0, 1])\n T85 = fd.ops.mul(T79, T77)\n T90 = fd.ops.broadcast_in_dim(\n T84, shape=[288, 512, 128], broadcast_dims=[0, 1, 2]\n )\n S91 = fd.define_scalar(128.000, dtype=DataType.Double)\n S92 = fd.ops.reciprocal(S91)\n T93 = fd.ops.mul(T85, S92)\n S94 = fd.define_scalar(0.00781250, dtype=DataType.Double)\n T95 = fd.ops.mul(S94, T90)\n T96 = fd.ops.add(T95, T93)\n T97 = fd.ops.add(T46, T96)\n T98 = fd.ops.cast(T97, dtype=DataType.BFloat16)\n T99 = fd.ops.mul(T29, T41)\n T100 = fd.ops.mul(T99, T20)\n T101 = fd.ops.cast(T9, dtype=DataType.Float)\n T105 = fd.ops.reshape(T98, new_shape=[147456, 128])\n T106 = fd.ops.sum(T97, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T107 = fd.ops.sum(T100, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T108 = fd.ops.sum(T101, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T109 = fd.ops.permute(T105, dims=[1, 0])\n T110 = fd.ops.cast(T106, dtype=DataType.BFloat16)\n T111 = fd.ops.cast(T107, dtype=DataType.BFloat16)\n T112 = fd.ops.cast(T108, dtype=DataType.BFloat16)\n fd.add_output(T109)\n fd.add_output(T110)\n fd.add_output(T105)\n fd.add_output(T98)\n fd.add_output(T111)\n fd.add_output(T112)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.testing.make_tensor(\n (147456, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (128,),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (288, 512),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (288, 512, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (288, 512, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization3(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374767 - Mistral-7B-v0.1 failure with allocation domain errors.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4096, 4096],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_ws_tma_normalization3","uri":"program://Fuser/function/tests.python.direct.test_repro.test_ws_tma_normalization3#L2730-L2855","kind":"function","name":"test_ws_tma_normalization3","path":"tests/python/direct/test_repro.py","language":"python","start_line":2730,"end_line":2855,"context_start_line":2710,"context_end_line":2875,"code":" high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (288, 512, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (288, 512, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization3(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374767 - Mistral-7B-v0.1 failure with allocation domain errors.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4096, 4096],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[4096],\n contiguity=[True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.define_tensor(\n shape=[1, 4096, 4096],\n contiguity=[True, None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 2, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 4096, 1],\n contiguity=[None, True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 4096, 4096],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T9 = fd.ops.reshape(T0, new_shape=[1, 4096, 4096])\n T10 = fd.ops.cast(T1, dtype=DataType.Float)\n T11 = fd.ops.cast(T9, dtype=DataType.Float)\n T16 = fd.ops.broadcast_in_dim(T10, shape=[1, 4096, 4096], broadcast_dims=[2])\n T17 = fd.ops.mul(T16, T11)\n T18 = fd.ops.cast(T2, dtype=DataType.Float)\n T19 = fd.ops.mul(T18, T17)\n T20 = fd.ops.sum(T19, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T25 = fd.ops.broadcast_in_dim(T20, shape=[1, 4096, 1], broadcast_dims=[1])\n S26 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T27 = fd.ops.pow(T3, S26)\n S28 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T29 = fd.ops.mul(S28, T25)\n T30 = fd.ops.mul(T29, T27)\n S31 = fd.define_scalar(4096.00, dtype=DataType.Double)\n S32 = fd.ops.reciprocal(S31)\n T33 = fd.ops.mul(T30, S32)\n T34 = fd.ops.sum(T33, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T38 = fd.ops.broadcast_in_dim(T34, shape=[1, 4096], broadcast_dims=[1])\n T43 = fd.ops.broadcast_in_dim(T38, shape=[1, 4096, 1], broadcast_dims=[0, 1])\n T48 = fd.ops.broadcast_in_dim(\n T43, shape=[1, 4096, 4096], broadcast_dims=[0, 1, 2]\n )\n T53 = fd.ops.broadcast_in_dim(\n T3, shape=[1, 4096, 4096], broadcast_dims=[0, 1, 2]\n )\n T54 = fd.ops.mul(T18, T48)\n T55 = fd.ops.mul(T53, T17)\n T56 = fd.ops.add(T55, T54)\n T57 = fd.ops.add(T56, T54)\n T58 = fd.ops.mul(T18, T53)\n T59 = fd.ops.cast(T4, dtype=DataType.Float)\n T60 = fd.ops.mul(T58, T11)\n T61 = fd.ops.add(T59, T57)\n T62 = fd.ops.sum(T60, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T63 = fd.ops.cast(T61, dtype=DataType.BFloat16)\n T64 = fd.ops.cast(T62, dtype=DataType.BFloat16)\n fd.add_output(T64)\n fd.add_output(T63)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.testing.make_tensor(\n (4096, 4096),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (4096,),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 4096),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 4096),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization4(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374768 - multiple model failures with boundary index errors.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[28672, 2048],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[2048],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_ws_tma_normalization4","uri":"program://Fuser/function/tests.python.direct.test_repro.test_ws_tma_normalization4#L2858-L2969","kind":"function","name":"test_ws_tma_normalization4","path":"tests/python/direct/test_repro.py","language":"python","start_line":2858,"end_line":2969,"context_start_line":2838,"context_end_line":2989,"code":" high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 4096),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization4(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374768 - multiple model failures with boundary index errors.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[28672, 2048],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[2048],\n contiguity=[True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.define_tensor(\n shape=[14, 2048, 2048],\n contiguity=[True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T3 = fd.define_tensor(\n shape=[14, 2048, 1],\n contiguity=[True, True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T8 = fd.ops.reshape(T0, new_shape=[14, 2048, 2048])\n T9 = fd.ops.cast(T1, dtype=DataType.Float)\n T10 = fd.ops.cast(T8, dtype=DataType.Float)\n T15 = fd.ops.broadcast_in_dim(T9, shape=[14, 2048, 2048], broadcast_dims=[2])\n T16 = fd.ops.mul(T15, T10)\n T17 = fd.ops.cast(T2, dtype=DataType.Float)\n T18 = fd.ops.mul(T17, T16)\n T19 = fd.ops.sum(T18, dims=[2], keepdim=False, dtype=DataType.Null)\n T24 = fd.ops.broadcast_in_dim(T19, shape=[14, 2048, 1], broadcast_dims=[0, 1])\n S25 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T26 = fd.ops.pow(T3, S25)\n S27 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T28 = fd.ops.mul(S27, T24)\n T29 = fd.ops.mul(T28, T26)\n S30 = fd.define_scalar(2048.00, dtype=DataType.Double)\n S31 = fd.ops.reciprocal(S30)\n T32 = fd.ops.mul(T29, S31)\n T33 = fd.ops.sum(T32, dims=[2], keepdim=False, dtype=DataType.Null)\n T38 = fd.ops.broadcast_in_dim(T33, shape=[14, 2048, 1], broadcast_dims=[0, 1])\n T43 = fd.ops.broadcast_in_dim(\n T38, shape=[14, 2048, 2048], broadcast_dims=[0, 1, 2]\n )\n T48 = fd.ops.broadcast_in_dim(\n T3, shape=[14, 2048, 2048], broadcast_dims=[0, 1, 2]\n )\n T49 = fd.ops.mul(T17, T43)\n T50 = fd.ops.mul(T48, T16)\n T51 = fd.ops.add(T50, T49)\n T52 = fd.ops.add(T51, T49)\n T53 = fd.ops.cast(T52, dtype=DataType.BFloat16)\n T54 = fd.ops.mul(T17, T48)\n T55 = fd.ops.mul(T54, T10)\n T59 = fd.ops.reshape(T53, new_shape=[28672, 2048])\n T60 = fd.ops.sum(T55, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T61 = fd.ops.permute(T59, dims=[1, 0])\n T62 = fd.ops.cast(T60, dtype=DataType.BFloat16)\n fd.add_output(T61)\n fd.add_output(T59)\n fd.add_output(T53)\n fd.add_output(T62)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.testing.make_tensor(\n (28672, 2048),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (2048,),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (14, 2048, 2048),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (14, 2048, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization5(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374769 - stablecode-completion-alpha-3b failure with allocation domain errors.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[16384, 2560],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_ws_tma_normalization5","uri":"program://Fuser/function/tests.python.direct.test_repro.test_ws_tma_normalization5#L2972-L3212","kind":"function","name":"test_ws_tma_normalization5","path":"tests/python/direct/test_repro.py","language":"python","start_line":2972,"end_line":3212,"context_start_line":2952,"context_end_line":3232,"code":" high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (14, 2048, 2048),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (14, 2048, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization5(nvfuser_direct_test):\n \"\"\"\n Test for issue 5374769 - stablecode-completion-alpha-3b failure with allocation domain errors.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[16384, 2560],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[2560],\n contiguity=[True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.define_tensor(\n shape=[1, 16384],\n contiguity=[None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 16384, 2560],\n contiguity=[True, None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 2, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 16384, 1],\n contiguity=[None, True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T5 = fd.define_tensor(\n shape=[16384, 2560],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T6 = fd.define_tensor(\n shape=[2560],\n contiguity=[True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n T7 = fd.define_tensor(\n shape=[1, 16384, 2560],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T12 = fd.ops.reshape(T0, new_shape=[1, 16384, 2560])\n T17 = fd.ops.broadcast_in_dim(T1, shape=[1, 16384, 2560], broadcast_dims=[2])\n T22 = fd.ops.broadcast_in_dim(T2, shape=[1, 16384, 1], broadcast_dims=[0, 1])\n T23 = fd.ops.cast(T12, dtype=DataType.Float)\n T24 = fd.ops.cast(T17, dtype=DataType.Float)\n T29 = fd.ops.broadcast_in_dim(\n T22, shape=[1, 16384, 2560], broadcast_dims=[0, 1, 2]\n )\n T30 = fd.ops.cast(T3, dtype=DataType.Float)\n T31 = fd.ops.mul(T24, T23)\n T32 = fd.ops.sub(T30, T29)\n T33 = fd.ops.mul(T32, T31)\n T34 = fd.ops.sum(T33, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T39 = fd.ops.broadcast_in_dim(T34, shape=[1, 16384, 1], broadcast_dims=[1])\n T44 = fd.ops.broadcast_in_dim(\n T4, shape=[1, 16384, 2560], broadcast_dims=[0, 1, 2]\n )\n T49 = fd.ops.reshape(T5, new_shape=[1, 16384, 2560])\n T54 = fd.ops.broadcast_in_dim(T6, shape=[1, 16384, 2560], broadcast_dims=[2])\n S55 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T56 = fd.ops.pow(T4, S55)\n S57 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T58 = fd.ops.mul(S57, T39)\n T59 = fd.ops.mul(T44, T31)\n T60 = fd.ops.cast(T49, dtype=DataType.Float)\n T61 = fd.ops.cast(T54, dtype=DataType.Float)\n T62 = fd.ops.mul(T58, T56)\n T63 = fd.ops.neg(T59)\n T64 = fd.ops.mul(T61, T60)\n T65 = fd.ops.sum(T62, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T66 = fd.ops.sum(T63, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T67 = fd.ops.mul(T32, T64)\n T71 = fd.ops.broadcast_in_dim(T65, shape=[1, 16384], broadcast_dims=[1])\n T76 = fd.ops.broadcast_in_dim(T66, shape=[1, 16384, 1], broadcast_dims=[1])\n T77 = fd.ops.sum(T67, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T82 = fd.ops.broadcast_in_dim(T2, shape=[1, 16384, 1], broadcast_dims=[0, 1])\n T87 = fd.ops.broadcast_in_dim(T71, shape=[1, 16384, 1], broadcast_dims=[0, 1])\n T88 = fd.ops.sum(T76, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T93 = fd.ops.broadcast_in_dim(T77, shape=[1, 16384, 1], broadcast_dims=[1])\n T98 = fd.ops.broadcast_in_dim(\n T82, shape=[1, 16384, 2560], broadcast_dims=[0, 1, 2]\n )\n T103 = fd.ops.broadcast_in_dim(\n T87, shape=[1, 16384, 2560], broadcast_dims=[0, 1, 2]\n )\n T107 = fd.ops.broadcast_in_dim(T88, shape=[1, 16384], broadcast_dims=[1])\n S108 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T109 = fd.ops.mul(S108, T93)\n T110 = fd.ops.mul(T44, T64)\n T111 = fd.ops.sub(T30, T98)\n S112 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T113 = fd.ops.mul(S112, T103)\n T118 = fd.ops.broadcast_in_dim(T107, shape=[1, 16384, 1], broadcast_dims=[0, 1])\n T119 = fd.ops.mul(T109, T56)\n T120 = fd.ops.neg(T110)\n T121 = fd.ops.mul(T113, T111)\n T126 = fd.ops.broadcast_in_dim(\n T118, shape=[1, 16384, 2560], broadcast_dims=[0, 1, 2]\n )\n T127 = fd.ops.sum(T119, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T128 = fd.ops.sum(T120, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n S129 = fd.define_scalar(2560.00, dtype=DataType.Double)\n S130 = fd.ops.reciprocal(S129)\n T131 = fd.ops.mul(T121, S130)\n S132 = fd.define_scalar(0.000390625, dtype=DataType.Double)\n T133 = fd.ops.mul(S132, T126)\n T134 = fd.ops.cast(T7, dtype=DataType.Float)\n T138 = fd.ops.broadcast_in_dim(T127, shape=[1, 16384], broadcast_dims=[1])\n T143 = fd.ops.broadcast_in_dim(T128, shape=[1, 16384, 1], broadcast_dims=[1])\n T144 = fd.ops.add(T133, T131)\n T145 = fd.ops.add(T134, T59)\n T150 = fd.ops.broadcast_in_dim(T138, shape=[1, 16384, 1], broadcast_dims=[0, 1])\n T151 = fd.ops.sum(T143, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T156 = fd.ops.broadcast_in_dim(\n T150, shape=[1, 16384, 2560], broadcast_dims=[0, 1, 2]\n )\n T160 = fd.ops.broadcast_in_dim(T151, shape=[1, 16384], broadcast_dims=[1])\n S161 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T162 = fd.ops.mul(S161, T156)\n T167 = fd.ops.broadcast_in_dim(T160, shape=[1, 16384, 1], broadcast_dims=[0, 1])\n T168 = fd.ops.add(T145, T144)\n T169 = fd.ops.mul(T162, T111)\n T174 = fd.ops.broadcast_in_dim(\n T167, shape=[1, 16384, 2560], broadcast_dims=[0, 1, 2]\n )\n S175 = fd.define_scalar(2560.00, dtype=DataType.Double)\n S176 = fd.ops.reciprocal(S175)\n T177 = fd.ops.mul(T169, S176)\n S178 = fd.define_scalar(0.000390625, dtype=DataType.Double)\n T179 = fd.ops.mul(S178, T174)\n T180 = fd.ops.mul(T32, T44)\n T181 = fd.ops.add(T179, T177)\n T182 = fd.ops.add(T168, T110)\n T183 = fd.ops.mul(T180, T60)\n T184 = fd.ops.mul(T180, T23)\n T185 = fd.ops.cast(T49, dtype=DataType.Float)\n T186 = fd.ops.cast(T12, dtype=DataType.Float)\n T187 = fd.ops.add(T182, T181)\n T188 = fd.ops.sum(T183, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T189 = fd.ops.sum(T185, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T190 = fd.ops.sum(T184, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T191 = fd.ops.sum(T186, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T192 = fd.ops.cast(T187, dtype=DataType.BFloat16)\n T193 = fd.ops.cast(T188, dtype=DataType.BFloat16)\n T194 = fd.ops.cast(T189, dtype=DataType.BFloat16)\n T195 = fd.ops.cast(T190, dtype=DataType.BFloat16)\n T196 = fd.ops.cast(T191, dtype=DataType.BFloat16)\n fd.add_output(T196)\n fd.add_output(T195)\n fd.add_output(T194)\n fd.add_output(T193)\n fd.add_output(T192)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.testing.make_tensor(\n (16384, 2560),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (2560,),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 16384),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 16384, 2560),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 16384, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (16384, 2560),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (2560,),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 16384, 2560),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_loop_promotion_cyclic_war(nvfuser_direct_test):\n \"\"\"\n Test for loop promotion with cyclic WAR (Write-After-Read) dependencies.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations with slice operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4096, 128],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[4096, 128],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_loop_promotion_cyclic_war","uri":"program://Fuser/function/tests.python.direct.test_repro.test_loop_promotion_cyclic_war#L3215-L3516","kind":"function","name":"test_loop_promotion_cyclic_war","path":"tests/python/direct/test_repro.py","language":"python","start_line":3215,"end_line":3516,"context_start_line":3195,"context_end_line":3536,"code":" high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (2560,),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 16384, 2560),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_loop_promotion_cyclic_war(nvfuser_direct_test):\n \"\"\"\n Test for loop promotion with cyclic WAR (Write-After-Read) dependencies.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including reshape, cast, broadcast, and mathematical operations with slice operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[4096, 128],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[4096, 128],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, 4096, 5120],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 4096, 640],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 4096, 640],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T5 = fd.define_tensor(\n shape=[1, 4096, 16640],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T6 = fd.define_tensor(\n shape=[1, 4096, 16640],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T7 = fd.define_tensor(\n shape=[1, 4096, 5120],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T8 = fd.define_tensor(\n shape=[1, 4096, 640],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T9 = fd.define_tensor(\n shape=[1, 4096, 640],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T10 = fd.define_tensor(\n shape=[1, 4096, 16640],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T11 = fd.define_tensor(\n shape=[1, 4096, 16640],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T16 = fd.ops.reshape(T0, new_shape=[1, 4096, 128])\n T22 = fd.ops.broadcast_in_dim(\n T16, shape=[1, 1, 4096, 128], broadcast_dims=[0, 2, 3]\n )\n T27 = fd.ops.reshape(T1, new_shape=[1, 4096, 128])\n T33 = fd.ops.broadcast_in_dim(\n T27, shape=[1, 1, 4096, 128], broadcast_dims=[0, 2, 3]\n )\n T39 = fd.ops.broadcast_in_dim(\n T22, shape=[1, 40, 4096, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T40 = fd.ops.cast(T39, dtype=DataType.Float)\n T46 = fd.ops.broadcast_in_dim(\n T33, shape=[1, 40, 4096, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T47 = fd.ops.cast(T46, dtype=DataType.Float)\n T48 = fd.ops.cast(T2, dtype=DataType.Float)\n T49 = fd.ops.cast(T3, dtype=DataType.Float)\n T50 = fd.ops.cast(T4, dtype=DataType.Float)\n T51 = fd.ops.cast(T5, dtype=DataType.Float)\n T52 = fd.ops.cast(T6, dtype=DataType.Float)\n S53 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T54 = fd.ops.mul(T7, S53)\n S55 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T56 = fd.ops.mul(T8, S55)\n S57 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T58 = fd.ops.mul(T9, S57)\n S59 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T60 = fd.ops.mul(T10, S59)\n S61 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T62 = fd.ops.mul(T11, S61)\n T63 = fd.ops.add(T48, T54)\n T64 = fd.ops.add(T49, T56)\n T65 = fd.ops.add(T50, T58)\n T66 = fd.ops.add(T51, T60)\n T67 = fd.ops.add(T52, T62)\n T68 = fd.ops.cast(T63, dtype=DataType.BFloat16)\n T74 = fd.ops.reshape(T68, new_shape=[1, 4096, 40, 128])\n T75 = fd.ops.cast(T64, dtype=DataType.BFloat16)\n T81 = fd.ops.reshape(T75, new_shape=[1, 4096, 5, 128])\n T82 = fd.ops.cast(T65, dtype=DataType.BFloat16)\n T88 = fd.ops.reshape(T82, new_shape=[1, 4096, 5, 128])\n T89 = fd.ops.cast(T66, dtype=DataType.BFloat16)\n T90 = fd.ops.neg(T66)\n T91 = fd.ops.cast(T67, dtype=DataType.BFloat16)\n T92 = fd.ops.permute(T74, dims=[0, 2, 1, 3])\n T93 = fd.ops.permute(T81, dims=[0, 2, 1, 3])\n T94 = fd.ops.permute(T88, dims=[0, 2, 1, 3])\n T95 = fd.ops.exp(T90)\n T105 = fd.ops.broadcast_in_dim(\n T93, shape=[1, 1, 8, 5, 1, 4096, 1, 128], broadcast_dims=[1, 3, 5, 7]\n )\n T111 = fd.ops.reshape(T105, new_shape=[1, 40, 4096, 128])\n T121 = fd.ops.broadcast_in_dim(\n T94, shape=[1, 1, 8, 5, 1, 4096, 1, 128], broadcast_dims=[1, 3, 5, 7]\n )\n T127 = fd.ops.reshape(T121, new_shape=[1, 40, 4096, 128])\n T128 = fd.ops.cast(T92, dtype=DataType.Float)\n T144 = fd.ops.slice(\n T92,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 40, 4096, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T160 = fd.ops.slice(\n T92,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 40, 4096, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T161 = fd.ops.cast(T160, dtype=DataType.Float)\n T162 = fd.ops.neg(T161)\n T163 = fd.ops.cast(T162, dtype=DataType.BFloat16)\n T164 = fd.ops.cast(T111, dtype=DataType.Float)\n T180 = fd.ops.slice(\n T111,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 40, 4096, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T196 = fd.ops.slice(\n T111,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 40, 4096, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T197 = fd.ops.cast(T196, dtype=DataType.Float)\n T198 = fd.ops.neg(T197)\n T199 = fd.ops.cast(T198, dtype=DataType.BFloat16)\n S200 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T201 = fd.ops.add(S200, T95)\n T202 = fd.ops.mul(T128, T40)\n T203 = fd.ops.cat([T163, T144], dim=-1, manual_padding=0)\n T204 = fd.ops.mul(T164, T40)\n T205 = fd.ops.cat([T199, T180], dim=-1, manual_padding=0)\n T206 = fd.ops.reciprocal(T201)\n T207 = fd.ops.cast(T203, dtype=DataType.Float)\n T208 = fd.ops.cast(T205, dtype=DataType.Float)\n T209 = fd.ops.mul(T207, T47)\n T210 = fd.ops.mul(T208, T47)\n T211 = fd.ops.mul(T66, T206)\n T212 = fd.ops.add(T202, T209)\n T213 = fd.ops.add(T204, T210)\n T214 = fd.ops.mul(T211, T67)\n T215 = fd.ops.cast(T212, dtype=DataType.BFloat16)\n T216 = fd.ops.cast(T213, dtype=DataType.BFloat16)\n T217 = fd.ops.cast(T214, dtype=DataType.BFloat16)\n fd.add_output(T89)\n fd.add_output(T91)\n fd.add_output(T127)\n fd.add_output(T215)\n fd.add_output(T216)\n fd.add_output(T217)\n fd.add_output(T214)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.testing.make_tensor(\n (4096, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (4096, 128),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 5120),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 640),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 640),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 16640),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 16640),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 5120),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 640),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 640),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 16640),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 16640),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_reshape_cancellation(nvfuser_direct_test):\n \"\"\"\n Test for reshape cancellation operations with complex tensor manipulations.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including slice operations, concatenation, reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, 2048, 24, 32],\n contiguity=[None, True, True, False],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 2048, 24, 32],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_reshape_cancellation","uri":"program://Fuser/function/tests.python.direct.test_repro.test_reshape_cancellation#L3519-L3697","kind":"function","name":"test_reshape_cancellation","path":"tests/python/direct/test_repro.py","language":"python","start_line":3519,"end_line":3697,"context_start_line":3499,"context_end_line":3717,"code":" high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 16640),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 16640),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_reshape_cancellation(nvfuser_direct_test):\n \"\"\"\n Test for reshape cancellation operations with complex tensor manipulations.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including slice operations, concatenation, reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, 2048, 24, 32],\n contiguity=[None, True, True, False],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 2048, 24, 32],\n contiguity=[None, True, True, False],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, 2048, 24, 32],\n contiguity=[None, True, True, False],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 2048, 4, 4608],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 2048, 24, 32],\n contiguity=[None, True, True, False],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T5 = fd.define_tensor(\n shape=[1, 2048, 24, 64],\n contiguity=[None, True, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T6 = fd.define_tensor(\n shape=[1, 2048, 24, 64],\n contiguity=[None, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T7 = fd.define_tensor(\n shape=[1, 2048, 24, 64],\n contiguity=[None, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T8 = fd.ops.cast(T0, dtype=DataType.Float)\n T9 = fd.ops.neg(T8)\n T10 = fd.ops.cast(T9, dtype=DataType.BFloat16)\n T17 = fd.ops.broadcast_in_dim(\n T1, shape=[1, 2048, 24, 32, 1], broadcast_dims=[0, 1, 2, 3]\n )\n T24 = fd.ops.broadcast_in_dim(\n T10, shape=[1, 2048, 24, 32, 1], broadcast_dims=[0, 1, 2, 3]\n )\n T25 = fd.ops.cast(T2, dtype=DataType.Float)\n T41 = fd.ops.slice(\n T3,\n start_indices=[0, 0, 0, 3072],\n end_indices=[1, 2048, 4, 4608],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T42 = fd.ops.cat([T24, T17], dim=-1, manual_padding=0)\n T43 = fd.ops.neg(T25)\n T50 = fd.ops.reshape(T41, new_shape=[1, 2048, 4, 6, 256])\n T56 = fd.ops.reshape(T42, new_shape=[1, 2048, 24, 64])\n T57 = fd.ops.cast(T43, dtype=DataType.BFloat16)\n T63 = fd.ops.reshape(T50, new_shape=[1, 2048, 24, 256])\n T64 = fd.ops.cast(T56, dtype=DataType.Float)\n T71 = fd.ops.broadcast_in_dim(\n T4, shape=[1, 2048, 24, 32, 1], broadcast_dims=[0, 1, 2, 3]\n )\n T78 = fd.ops.broadcast_in_dim(\n T57, shape=[1, 2048, 24, 32, 1], broadcast_dims=[0, 1, 2, 3]\n )\n T94 = fd.ops.slice(\n T63,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 2048, 24, 256],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T95 = fd.ops.mul(T64, T5)\n T111 = fd.ops.slice(\n T3,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 2048, 4, 1536],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T112 = fd.ops.cat([T78, T71], dim=-1, manual_padding=0)\n T113 = fd.ops.cast(T94, dtype=DataType.Float)\n T114 = fd.ops.add(T6, T95)\n T121 = fd.ops.reshape(T111, new_shape=[1, 2048, 4, 6, 256])\n T127 = fd.ops.reshape(T112, new_shape=[1, 2048, 24, 64])\n T128 = fd.ops.cat([T114, T113], dim=-1, manual_padding=0)\n T134 = fd.ops.reshape(T121, new_shape=[1, 2048, 24, 256])\n T135 = fd.ops.cast(T127, dtype=DataType.Float)\n T136 = fd.ops.permute(T128, dims=[0, 2, 1, 3])\n T152 = fd.ops.slice(\n T134,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 2048, 24, 256],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T153 = fd.ops.mul(T135, T5)\n T154 = fd.ops.cast(T136, dtype=DataType.BFloat16)\n T155 = fd.ops.cast(T152, dtype=DataType.Float)\n T156 = fd.ops.add(T7, T153)\n T157 = fd.ops.cat([T156, T155], dim=-1, manual_padding=0)\n T158 = fd.ops.permute(T136, dims=[0, 1, 3, 2])\n T159 = fd.ops.permute(T157, dims=[0, 2, 1, 3])\n fd.add_output(T159)\n fd.add_output(T154)\n fd.add_output(T158)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.randn(3145727, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 24, 32), (3145728, 1536, 64, 2)\n ),\n torch.randn(3145727, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 24, 32), (3145728, 1536, 64, 2)\n ),\n torch.randn(3145727, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 24, 32), (3145728, 1536, 64, 2)\n ),\n torch.testing.make_tensor(\n (1, 2048, 4, 4608),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.randn(3145727, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 24, 32), (3145728, 1536, 64, 2)\n ),\n torch.randn(131072, dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 2048, 24, 64), (131072, 64, 0, 1)\n ),\n torch.testing.make_tensor(\n (1, 2048, 24, 64),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 2048, 24, 64),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_reduction_reference_missing_input_ids(nvfuser_direct_test):\n \"\"\"\n Test for issue 4840 - reduction reference missing input IDs.\n\n This test verifies complex tensor operations with Half and Float data types,\n including slice operations, concatenation, reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, 16, 4096, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 4096, 16, 128],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_reduction_reference_missing_input_ids","uri":"program://Fuser/function/tests.python.direct.test_repro.test_reduction_reference_missing_input_ids#L3700-L3986","kind":"function","name":"test_reduction_reference_missing_input_ids","path":"tests/python/direct/test_repro.py","language":"python","start_line":3700,"end_line":3986,"context_start_line":3680,"context_end_line":4006,"code":" (1, 2048, 24, 64), (131072, 64, 0, 1)\n ),\n torch.testing.make_tensor(\n (1, 2048, 24, 64),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 2048, 24, 64),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_reduction_reference_missing_input_ids(nvfuser_direct_test):\n \"\"\"\n Test for issue 4840 - reduction reference missing input IDs.\n\n This test verifies complex tensor operations with Half and Float data types,\n including slice operations, concatenation, reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, 16, 4096, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 4096, 16, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, 16, 4096, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 4096, 16, 128],\n contiguity=[None, True, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 4096, 6144],\n contiguity=[None, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T5 = fd.define_tensor(\n shape=[1, 16, 4096, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T6 = fd.define_tensor(\n shape=[1, 4096, 16, 128],\n contiguity=[None, True, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T7 = fd.define_tensor(\n shape=[1, 4096, 16, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T8 = fd.ops.permute(T0, dims=[0, 2, 1, 3])\n T9 = fd.ops.cast(T8, dtype=DataType.Float)\n T10 = fd.ops.cast(T1, dtype=DataType.Float)\n T11 = fd.ops.add(T10, T9)\n T12 = fd.ops.permute(T2, dims=[0, 2, 1, 3])\n T13 = fd.ops.cast(T12, dtype=DataType.Float)\n T29 = fd.ops.slice(\n T11,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 4096, 16, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T45 = fd.ops.slice(\n T13,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 4096, 16, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T46 = fd.ops.mul(T3, T29)\n T47 = fd.ops.mul(T3, T45)\n T63 = fd.ops.slice(\n T46,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 4096, 16, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T79 = fd.ops.slice(\n T47,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 4096, 16, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T95 = fd.ops.slice(\n T46,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 4096, 16, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T96 = fd.ops.neg(T63)\n T112 = fd.ops.slice(\n T47,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 4096, 16, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T113 = fd.ops.neg(T79)\n T120 = fd.ops.broadcast_in_dim(\n T95, shape=[1, 4096, 16, 1, 64], broadcast_dims=[0, 1, 2, 4]\n )\n T127 = fd.ops.broadcast_in_dim(\n T96, shape=[1, 4096, 16, 1, 64], broadcast_dims=[0, 1, 2, 4]\n )\n T134 = fd.ops.broadcast_in_dim(\n T112, shape=[1, 4096, 16, 1, 64], broadcast_dims=[0, 1, 2, 4]\n )\n T141 = fd.ops.broadcast_in_dim(\n T113, shape=[1, 4096, 16, 1, 64], broadcast_dims=[0, 1, 2, 4]\n )\n S142 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T154 = fd.ops.pad(T120, [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], S142)\n S155 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T167 = fd.ops.pad(T127, [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], S155)\n S168 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T180 = fd.ops.pad(T134, [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], S168)\n S181 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T193 = fd.ops.pad(T141, [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], S181)\n T206 = fd.ops.slice(\n T4,\n start_indices=[0, 0, 0],\n end_indices=[1, 4096, 2048],\n strides=[1, 1, 1],\n manual_normalization=0,\n )\n T219 = fd.ops.slice(\n T4,\n start_indices=[0, 0, 2048],\n end_indices=[1, 4096, 4096],\n strides=[1, 1, 1],\n manual_normalization=0,\n )\n T220 = fd.ops.add(T167, T154)\n T221 = fd.ops.add(T193, T180)\n T227 = fd.ops.reshape(T206, new_shape=[1, 4096, 16, 128])\n T233 = fd.ops.reshape(T219, new_shape=[1, 4096, 16, 128])\n T234 = fd.ops.permute(T5, dims=[0, 2, 1, 3])\n S235 = fd.define_scalar(0, dtype=DataType.Int)\n T241 = fd.ops.full(\n shape=[1, 4096, 16, 0], fill_value=S235, dtype=DataType.Float\n )\n T242 = fd.ops.mul(T6, T29)\n T248 = fd.ops.reshape(T220, new_shape=[1, 4096, 16, 128])\n T249 = fd.ops.mul(T6, T45)\n T255 = fd.ops.reshape(T221, new_shape=[1, 4096, 16, 128])\n T256 = fd.ops.cast(T227, dtype=DataType.Float)\n T257 = fd.ops.cast(T233, dtype=DataType.Float)\n T258 = fd.ops.cast(T234, dtype=DataType.Float)\n T259 = fd.ops.cast(T7, dtype=DataType.Float)\n S260 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T270 = fd.ops.pad(T241, [0, 128, 0, 0, 0, 0, 0, 0], S260)\n T271 = fd.ops.add(T248, T242)\n T272 = fd.ops.add(T255, T249)\n T279 = fd.ops.reshape(T256, new_shape=[1, 4096, 16, 2, 64])\n T286 = fd.ops.reshape(T257, new_shape=[1, 4096, 16, 2, 64])\n T287 = fd.ops.add(T259, T258)\n T288 = fd.ops.add(T271, T270)\n T289 = fd.ops.add(T272, T270)\n T308 = fd.ops.slice(\n T279,\n start_indices=[0, 0, 0, 1, 0],\n end_indices=[1, 4096, 16, 2, 64],\n strides=[1, 1, 1, 1, 1],\n manual_normalization=0,\n )\n T327 = fd.ops.slice(\n T286,\n start_indices=[0, 0, 0, 1, 0],\n end_indices=[1, 4096, 16, 2, 64],\n strides=[1, 1, 1, 1, 1],\n manual_normalization=0,\n )\n T328 = fd.ops.cast(T287, dtype=DataType.Half)\n T329 = fd.ops.cast(T288, dtype=DataType.Half)\n T330 = fd.ops.cast(T289, dtype=DataType.Half)\n T349 = fd.ops.slice(\n T279,\n start_indices=[0, 0, 0, 0, 0],\n end_indices=[1, 4096, 16, 1, 64],\n strides=[1, 1, 1, 1, 1],\n manual_normalization=0,\n )\n T350 = fd.ops.squeeze(T308, dims=[3], squeeze_expanded=False)\n T369 = fd.ops.slice(\n T286,\n start_indices=[0, 0, 0, 0, 0],\n end_indices=[1, 4096, 16, 1, 64],\n strides=[1, 1, 1, 1, 1],\n manual_normalization=0,\n )\n T370 = fd.ops.squeeze(T327, dims=[3], squeeze_expanded=False)\n T375 = fd.ops.reshape(T328, new_shape=[1, 4096, 2048])\n T380 = fd.ops.reshape(T329, new_shape=[1, 4096, 2048])\n T385 = fd.ops.reshape(T330, new_shape=[1, 4096, 2048])\n T386 = fd.ops.squeeze(T349, dims=[3], squeeze_expanded=False)\n T387 = fd.ops.neg(T350)\n T388 = fd.ops.squeeze(T369, dims=[3], squeeze_expanded=False)\n T389 = fd.ops.neg(T370)\n T390 = fd.ops.cat([T385, T380, T375], dim=2, manual_padding=0)\n T391 = fd.ops.cat([T387, T386], dim=-1, manual_padding=0)\n T392 = fd.ops.cat([T389, T388], dim=-1, manual_padding=0)\n T393 = fd.ops.cast(T390, dtype=DataType.Float)\n T394 = fd.ops.mul(T256, T45)\n T395 = fd.ops.mul(T257, T29)\n T396 = fd.ops.mul(T391, T45)\n T397 = fd.ops.mul(T392, T29)\n S398 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T399 = fd.ops.mul(S398, T393)\n T400 = fd.ops.sum(T394, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T401 = fd.ops.sum(T395, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T402 = fd.ops.sum(T396, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T403 = fd.ops.sum(T397, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T407 = fd.ops.reshape(T399, new_shape=[4096, 6144])\n T413 = fd.ops.broadcast_in_dim(\n T400, shape=[1, 4096, 1, 128], broadcast_dims=[1, 3]\n )\n T419 = fd.ops.broadcast_in_dim(\n T401, shape=[1, 4096, 1, 128], broadcast_dims=[1, 3]\n )\n T425 = fd.ops.broadcast_in_dim(\n T402, shape=[1, 4096, 1, 128], broadcast_dims=[1, 3]\n )\n T431 = fd.ops.broadcast_in_dim(\n T403, shape=[1, 4096, 1, 128], broadcast_dims=[1, 3]\n )\n T432 = fd.ops.permute(T407, dims=[1, 0])\n T436 = fd.ops.reshape(T390, new_shape=[4096, 6144])\n T437 = fd.ops.add(T419, T413)\n T438 = fd.ops.add(T431, T425)\n fd.add_output(T432)\n fd.add_output(T407)\n fd.add_output(T436)\n fd.add_output(T437)\n fd.add_output(T438)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n # input range is revised to [-1, 1] to avoid small validation errors\n # which highly likely caused by the strict tolerance values in\n # ValidationConstants.\n inputs = [\n torch.testing.make_tensor(\n (8388608,), dtype=torch.float16, device=\"cuda:0\", low=-1, high=1\n ).as_strided((1, 16, 4096, 128), (8388608, 128, 2048, 1)),\n torch.testing.make_tensor(\n (1, 4096, 16, 128), dtype=torch.float16, device=\"cuda:0\", low=-1, high=1\n ),\n torch.testing.make_tensor(\n (8388608,), dtype=torch.float16, device=\"cuda:0\", low=-1, high=1\n ).as_strided((1, 16, 4096, 128), (8388608, 128, 2048, 1)),\n torch.testing.make_tensor(\n (524288,), dtype=torch.float32, device=\"cuda:0\", low=-1, high=1\n ).as_strided((1, 4096, 16, 128), (1048576, 128, 0, 1)),\n torch.testing.make_tensor(\n (1, 4096, 6144), dtype=torch.float16, device=\"cuda:0\", low=-1, high=1\n ),\n torch.testing.make_tensor(\n (8388608,), dtype=torch.float16, device=\"cuda:0\", low=-1, high=1\n ).as_strided((1, 16, 4096, 128), (8388608, 128, 2048, 1)),\n torch.testing.make_tensor(\n (524288,), dtype=torch.float32, device=\"cuda:0\", low=-1, high=1\n ).as_strided((1, 4096, 16, 128), (1048576, 128, 0, 1)),\n torch.testing.make_tensor(\n (1, 4096, 16, 128), dtype=torch.float16, device=\"cuda:0\", low=-1, high=1\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization6(nvfuser_direct_test):\n \"\"\"\n Test for scalar input handling in TMA normalization.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including scalar tensor operations, reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[3072],\n contiguity=[True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n T1 = fd.define_tensor(","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_ws_tma_normalization6","uri":"program://Fuser/function/tests.python.direct.test_repro.test_ws_tma_normalization6#L3989-L4126","kind":"function","name":"test_ws_tma_normalization6","path":"tests/python/direct/test_repro.py","language":"python","start_line":3989,"end_line":4126,"context_start_line":3969,"context_end_line":4146,"code":" ).as_strided((1, 16, 4096, 128), (8388608, 128, 2048, 1)),\n torch.testing.make_tensor(\n (524288,), dtype=torch.float32, device=\"cuda:0\", low=-1, high=1\n ).as_strided((1, 4096, 16, 128), (1048576, 128, 0, 1)),\n torch.testing.make_tensor(\n (1, 4096, 6144), dtype=torch.float16, device=\"cuda:0\", low=-1, high=1\n ),\n torch.testing.make_tensor(\n (8388608,), dtype=torch.float16, device=\"cuda:0\", low=-1, high=1\n ).as_strided((1, 16, 4096, 128), (8388608, 128, 2048, 1)),\n torch.testing.make_tensor(\n (524288,), dtype=torch.float32, device=\"cuda:0\", low=-1, high=1\n ).as_strided((1, 4096, 16, 128), (1048576, 128, 0, 1)),\n torch.testing.make_tensor(\n (1, 4096, 16, 128), dtype=torch.float16, device=\"cuda:0\", low=-1, high=1\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_ws_tma_normalization6(nvfuser_direct_test):\n \"\"\"\n Test for scalar input handling in TMA normalization.\n\n This test verifies complex tensor operations with BFloat16 and Float data types,\n including scalar tensor operations, reshape, cast, broadcast, and mathematical operations.\n \"\"\"\n skip_if_global_memory_below_gb(32)\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[3072],\n contiguity=[True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n T1 = fd.define_tensor(\n shape=[1, 4096, 3072],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, 4096, 3072],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 4096, 1],\n contiguity=[None, True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 4096, 3072],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T5 = fd.define_tensor(\n shape=[], contiguity=[], dtype=DataType.Float, is_cpu=False\n )\n T6 = fd.ops.cast(T0, dtype=DataType.Float)\n S7 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T8 = fd.ops.add(S7, T6)\n T9 = fd.ops.cast(T1, dtype=DataType.Float)\n T14 = fd.ops.broadcast_in_dim(T8, shape=[1, 4096, 3072], broadcast_dims=[2])\n T15 = fd.ops.mul(T14, T9)\n T16 = fd.ops.cast(T2, dtype=DataType.Float)\n T17 = fd.ops.mul(T16, T15)\n T18 = fd.ops.sum(T17, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T23 = fd.ops.broadcast_in_dim(T18, shape=[1, 4096, 1], broadcast_dims=[1])\n S24 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T25 = fd.ops.pow(T3, S24)\n S26 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T27 = fd.ops.mul(S26, T23)\n T28 = fd.ops.mul(T27, T25)\n S29 = fd.define_scalar(3072.00, dtype=DataType.Double)\n S30 = fd.ops.reciprocal(S29)\n T31 = fd.ops.mul(T28, S30)\n T32 = fd.ops.sum(T31, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T36 = fd.ops.broadcast_in_dim(T32, shape=[1, 4096], broadcast_dims=[1])\n T41 = fd.ops.broadcast_in_dim(T36, shape=[1, 4096, 1], broadcast_dims=[0, 1])\n T46 = fd.ops.broadcast_in_dim(\n T41, shape=[1, 4096, 3072], broadcast_dims=[0, 1, 2]\n )\n T51 = fd.ops.broadcast_in_dim(\n T3, shape=[1, 4096, 3072], broadcast_dims=[0, 1, 2]\n )\n T52 = fd.ops.mul(T16, T46)\n T53 = fd.ops.mul(T51, T15)\n T54 = fd.ops.add(T53, T52)\n T55 = fd.ops.add(T54, T52)\n T56 = fd.ops.cast(T4, dtype=DataType.Float)\n T57 = fd.ops.mul(T16, T51)\n T58 = fd.ops.add(T56, T55)\n T59 = fd.ops.mul(T57, T9)\n T60 = fd.ops.sum(T59, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T61 = fd.ops.cast(T60, dtype=DataType.BFloat16)\n T62 = fd.ops.mul(T5, T58)\n T63 = fd.ops.cast(T62, dtype=DataType.BFloat16)\n fd.add_output(T61)\n fd.add_output(T63)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.testing.make_tensor(\n (3072,),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 3072),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 3072),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 3072),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_domain_map_hang(nvfuser_direct_test):\n \"\"\"\n Test for issue 4960 - domain map hang in complex tensor operations.\n\n This test verifies complex tensor operations with Float and BFloat16 data types,\n including iota operations, broadcast, mathematical operations, index_select, reshape, cast, slice operations, and concatenation.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[16],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T1 = fd.define_tensor(\n shape=[16],","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_domain_map_hang","uri":"program://Fuser/function/tests.python.direct.test_repro.test_domain_map_hang#L4129-L4454","kind":"function","name":"test_domain_map_hang","path":"tests/python/direct/test_repro.py","language":"python","start_line":4129,"end_line":4454,"context_start_line":4109,"context_end_line":4474,"code":" high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, 4096, 3072),\n dtype=torch.bfloat16,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_domain_map_hang(nvfuser_direct_test):\n \"\"\"\n Test for issue 4960 - domain map hang in complex tensor operations.\n\n This test verifies complex tensor operations with Float and BFloat16 data types,\n including iota operations, broadcast, mathematical operations, index_select, reshape, cast, slice operations, and concatenation.\n \"\"\"\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[16],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T1 = fd.define_tensor(\n shape=[16],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.define_tensor(\n shape=[4096, 4096],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, 4096, 2560],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 4096, 2560],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T5 = fd.define_tensor(\n shape=[1, 4096, 2560],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T6 = fd.define_tensor(\n shape=[1, 4096, 10240],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T7 = fd.define_tensor(\n shape=[1, 4096, 2560],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T8 = fd.define_tensor(\n shape=[1, 4096, 2560],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T9 = fd.define_tensor(\n shape=[1, 4096, 2560],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T10 = fd.define_tensor(\n shape=[1, 4096, 10240],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n S11 = fd.define_scalar(4096, dtype=DataType.Int)\n S12 = fd.define_scalar(0, dtype=DataType.Int)\n S13 = fd.define_scalar(1, dtype=DataType.Int)\n T14 = fd.ops.iota(S11, S12, S13, dtype=DataType.Int)\n T18 = fd.ops.broadcast_in_dim(T14, shape=[1, 4096], broadcast_dims=[1])\n T19 = fd.ops.cast(T14, dtype=DataType.Float)\n T23 = fd.ops.broadcast_in_dim(T19, shape=[4096, 1], broadcast_dims=[0])\n T27 = fd.ops.broadcast_in_dim(T0, shape=[1, 16], broadcast_dims=[1])\n T31 = fd.ops.broadcast_in_dim(T23, shape=[4096, 16], broadcast_dims=[0, 1])\n T35 = fd.ops.broadcast_in_dim(T27, shape=[4096, 16], broadcast_dims=[0, 1])\n T39 = fd.ops.broadcast_in_dim(T1, shape=[1, 16], broadcast_dims=[1])\n T43 = fd.ops.broadcast_in_dim(T39, shape=[4096, 16], broadcast_dims=[0, 1])\n S44 = fd.define_scalar(0, dtype=DataType.Int)\n T45 = fd.ops.lt(T18, S44)\n T46 = fd.ops.mul(T31, T35)\n T47 = fd.ops.mul(T31, T43)\n S48 = fd.define_scalar(4096, dtype=DataType.Int)\n S49 = fd.define_scalar(0, dtype=DataType.Int)\n T50 = fd.ops.where(T45, S48, S49)\n T51 = fd.ops.cast(T50, dtype=DataType.Int)\n T52 = fd.ops.cat([T46, T46], dim=-1, manual_padding=0)\n T53 = fd.ops.cat([T47, T47], dim=-1, manual_padding=0)\n T54 = fd.ops.add(T18, T51)\n T55 = fd.ops.cos(T52)\n T56 = fd.ops.sin(T52)\n T57 = fd.ops.cos(T53)\n T58 = fd.ops.sin(T53)\n T59 = fd.ops.cast(T55, dtype=DataType.BFloat16)\n T60 = fd.ops.cast(T56, dtype=DataType.BFloat16)\n T63 = fd.ops.reshape(T54, new_shape=[4096])\n T64 = fd.ops.cast(T57, dtype=DataType.BFloat16)\n T65 = fd.ops.cast(T58, dtype=DataType.BFloat16)\n T66 = fd.ops.index_select(T59, T63, dim=0)\n T67 = fd.ops.index_select(T60, T63, dim=0)\n T68 = fd.ops.index_select(T64, T63, dim=0)\n T69 = fd.ops.index_select(T65, T63, dim=0)\n T74 = fd.ops.reshape(T66, new_shape=[1, 4096, 32])\n T80 = fd.ops.broadcast_in_dim(\n T74, shape=[1, 1, 4096, 32], broadcast_dims=[0, 2, 3]\n )\n T85 = fd.ops.reshape(T67, new_shape=[1, 4096, 32])\n T91 = fd.ops.broadcast_in_dim(\n T85, shape=[1, 1, 4096, 32], broadcast_dims=[0, 2, 3]\n )\n T97 = fd.ops.broadcast_in_dim(\n T80, shape=[1, 32, 4096, 32], broadcast_dims=[0, 1, 2, 3]\n )\n T98 = fd.ops.cast(T97, dtype=DataType.Float)\n T104 = fd.ops.broadcast_in_dim(\n T91, shape=[1, 32, 4096, 32], broadcast_dims=[0, 1, 2, 3]\n )\n T105 = fd.ops.cast(T104, dtype=DataType.Float)\n T110 = fd.ops.reshape(T68, new_shape=[1, 4096, 32])\n T116 = fd.ops.broadcast_in_dim(\n T110, shape=[1, 1, 4096, 32], broadcast_dims=[0, 2, 3]\n )\n T121 = fd.ops.reshape(T69, new_shape=[1, 4096, 32])\n T127 = fd.ops.broadcast_in_dim(\n T121, shape=[1, 1, 4096, 32], broadcast_dims=[0, 2, 3]\n )\n T133 = fd.ops.broadcast_in_dim(\n T116, shape=[1, 32, 4096, 32], broadcast_dims=[0, 1, 2, 3]\n )\n T134 = fd.ops.cast(T133, dtype=DataType.Float)\n T140 = fd.ops.broadcast_in_dim(\n T127, shape=[1, 32, 4096, 32], broadcast_dims=[0, 1, 2, 3]\n )\n T141 = fd.ops.cast(T140, dtype=DataType.Float)\n T142 = fd.ops.cast(T2, dtype=DataType.BFloat16)\n T143 = fd.ops.cast(T3, dtype=DataType.Float)\n T144 = fd.ops.cast(T4, dtype=DataType.Float)\n T145 = fd.ops.cast(T5, dtype=DataType.Float)\n T146 = fd.ops.cast(T6, dtype=DataType.Float)\n S147 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T148 = fd.ops.mul(T7, S147)\n S149 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T150 = fd.ops.mul(T8, S149)\n S151 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T152 = fd.ops.mul(T9, S151)\n S153 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T154 = fd.ops.mul(T10, S153)\n T155 = fd.ops.add(T143, T148)\n T156 = fd.ops.add(T144, T150)\n T157 = fd.ops.add(T145, T152)\n T158 = fd.ops.add(T146, T154)\n T159 = fd.ops.cast(T155, dtype=DataType.BFloat16)\n T160 = fd.ops.cast(T156, dtype=DataType.BFloat16)\n T161 = fd.ops.cast(T157, dtype=DataType.BFloat16)\n T167 = fd.ops.reshape(T159, new_shape=[1, 4096, 32, 80])\n T173 = fd.ops.reshape(T160, new_shape=[1, 4096, 32, 80])\n T179 = fd.ops.reshape(T161, new_shape=[1, 4096, 32, 80])\n T180 = fd.ops.cast(T158, dtype=DataType.BFloat16)\n T181 = fd.ops.permute(T167, dims=[0, 2, 1, 3])\n T182 = fd.ops.permute(T173, dims=[0, 2, 1, 3])\n T183 = fd.ops.permute(T179, dims=[0, 2, 1, 3])\n S184 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T185 = fd.ops.mul(S184, T158)\n S186 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T187 = fd.ops.pow(T158, S186)\n T203 = fd.ops.slice(\n T181,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 32, 4096, 32],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T219 = fd.ops.slice(\n T181,\n start_indices=[0, 0, 0, 32],\n end_indices=[1, 32, 4096, 80],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T235 = fd.ops.slice(\n T182,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 32, 4096, 32],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T251 = fd.ops.slice(\n T182,\n start_indices=[0, 0, 0, 32],\n end_indices=[1, 32, 4096, 80],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T252 = fd.ops.cast(T203, dtype=DataType.Float)\n T268 = fd.ops.slice(\n T203,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 32, 4096, 16],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T284 = fd.ops.slice(\n T203,\n start_indices=[0, 0, 0, 16],\n end_indices=[1, 32, 4096, 32],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T285 = fd.ops.cast(T284, dtype=DataType.Float)\n T286 = fd.ops.neg(T285)\n T287 = fd.ops.cast(T286, dtype=DataType.BFloat16)\n T288 = fd.ops.cast(T235, dtype=DataType.Float)\n T304 = fd.ops.slice(\n T235,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 32, 4096, 16],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T320 = fd.ops.slice(\n T235,\n start_indices=[0, 0, 0, 16],\n end_indices=[1, 32, 4096, 32],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T321 = fd.ops.cast(T320, dtype=DataType.Float)\n T322 = fd.ops.neg(T321)\n T323 = fd.ops.cast(T322, dtype=DataType.BFloat16)\n T324 = fd.ops.mul(T252, T98)\n T325 = fd.ops.cat([T287, T268], dim=-1, manual_padding=0)\n T326 = fd.ops.mul(T288, T98)\n T327 = fd.ops.cat([T323, T304], dim=-1, manual_padding=0)\n S328 = fd.define_scalar(0.0447150, dtype=DataType.Double)\n T329 = fd.ops.mul(S328, T187)\n T330 = fd.ops.cast(T325, dtype=DataType.Float)\n T331 = fd.ops.cast(T327, dtype=DataType.Float)\n T332 = fd.ops.mul(T330, T105)\n T333 = fd.ops.mul(T331, T105)\n T334 = fd.ops.add(T158, T329)\n T335 = fd.ops.add(T324, T332)\n T336 = fd.ops.add(T326, T333)\n S337 = fd.define_scalar(0.797885, dtype=DataType.Double)\n T338 = fd.ops.mul(S337, T334)\n T339 = fd.ops.cast(T335, dtype=DataType.BFloat16)\n T340 = fd.ops.cast(T336, dtype=DataType.BFloat16)\n T341 = fd.ops.cat([T339, T219], dim=-1, manual_padding=0)\n T342 = fd.ops.cat([T340, T251], dim=-1, manual_padding=0)\n T343 = fd.ops.tanh(T338)\n T344 = fd.ops.cast(T341, dtype=DataType.Float)\n T345 = fd.ops.cast(T342, dtype=DataType.Float)\n T346 = fd.ops.permute(T345, dims=[0, 1, 3, 2])\n S347 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T348 = fd.ops.add(S347, T343)\n T349 = fd.ops.mul(T185, T348)\n T350 = fd.ops.cast(T349, dtype=DataType.BFloat16)\n fd.add_output(T59)\n fd.add_output(T60)\n fd.add_output(T64)\n fd.add_output(T65)\n fd.add_output(T80)\n fd.add_output(T91)\n fd.add_output(T134)\n fd.add_output(T141)\n fd.add_output(T142)\n fd.add_output(T180)\n fd.add_output(T183)\n fd.add_output(T342)\n fd.add_output(T344)\n fd.add_output(T346)\n fd.add_output(T350)\n fd.add_output(T349)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n inputs = [\n torch.testing.make_tensor((16,), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((16,), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((4096, 4096), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 10240), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 10240), dtype=torch.float32, device=\"cuda:0\"\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_shared_memory_usage(nvfuser_direct_test):\n # repro of benchmarks.python.test_dropout_rmsnorm_bwd.test_dropout_rmsnorm_bwd_nvf_benchmark[dtype=torch.bfloat16-size=[16384_24578]]\n # avoid overflow of shared memory usage since previous version didn't consider static smem size\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T2 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Bool, is_cpu=False","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_shared_memory_usage","uri":"program://Fuser/function/tests.python.direct.test_repro.test_shared_memory_usage#L4457-L4544","kind":"function","name":"test_shared_memory_usage","path":"tests/python/direct/test_repro.py","language":"python","start_line":4457,"end_line":4544,"context_start_line":4437,"context_end_line":4564,"code":" ),\n torch.testing.make_tensor(\n (1, 4096, 10240), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 10240), dtype=torch.float32, device=\"cuda:0\"\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_shared_memory_usage(nvfuser_direct_test):\n # repro of benchmarks.python.test_dropout_rmsnorm_bwd.test_dropout_rmsnorm_bwd_nvf_benchmark[dtype=torch.bfloat16-size=[16384_24578]]\n # avoid overflow of shared memory usage since previous version didn't consider static smem size\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T2 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Bool, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n )\n T4 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T5 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.BFloat16, is_cpu=False\n )\n T6 = fd.ops.cast(T1, dtype=DataType.Float)\n T7 = fd.ops.cast(T0, dtype=DataType.Float)\n T8 = fd.ops.cast(T2, dtype=DataType.Float)\n T9 = fd.ops.cast(T4, dtype=DataType.Float)\n T10 = fd.ops.cast(T5, dtype=DataType.Float)\n T11 = fd.ops.mul(T7, T8)\n S12 = fd.define_scalar(1.25000, dtype=DataType.Double)\n T13 = fd.ops.mul(T11, S12)\n T14 = fd.ops.add(T6, T13)\n V15 = fd.ops.shape(T7)\n T16 = fd.ops.broadcast_in_dim(T3, shape=V15, broadcast_dims=[0, 1])\n T17 = fd.ops.reciprocal(T16)\n T18 = fd.ops.mul(T14, T17)\n T19 = fd.ops.broadcast_in_dim(T10, shape=V15, broadcast_dims=[1])\n T20 = fd.ops.mul(T9, T18)\n T21 = fd.ops.mul(T9, T19)\n T22 = fd.ops.sum(T20, dims=[0], keepdim=False, dtype=DataType.Null)\n T23 = fd.ops.mul(T21, T17)\n T24 = fd.ops.neg(T21)\n T25 = fd.ops.mul(T24, T14)\n S26 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T27 = fd.ops.pow(T16, S26)\n T28 = fd.ops.reciprocal(T27)\n T29 = fd.ops.mul(T25, T28)\n T30 = fd.ops.sum(T29, dims=[1], keepdim=False, dtype=DataType.Null)\n S31 = fd.ops.size(T7, dim=0)\n T34 = fd.ops.broadcast_in_dim(T30, shape=[S31, 1], broadcast_dims=[0])\n T35 = fd.ops.mul(S26, T3)\n T36 = fd.ops.reciprocal(T35)\n T37 = fd.ops.mul(T34, T36)\n S38 = fd.ops.size(T7, dim=1)\n S39 = fd.ops.reciprocal(S38)\n T40 = fd.ops.mul(T37, S39)\n T41 = fd.ops.sum(T40, dims=[1], keepdim=False, dtype=DataType.Null)\n T42 = fd.ops.broadcast_in_dim(T41, shape=[S31, 1], broadcast_dims=[0])\n T43 = fd.ops.broadcast_in_dim(T42, shape=V15, broadcast_dims=[0, 1])\n T44 = fd.ops.mul(T43, S26)\n T45 = fd.ops.mul(T44, T14)\n T46 = fd.ops.add(T23, T45)\n T47 = fd.ops.mul(T46, S12)\n T48 = fd.ops.mul(T47, T8)\n T49 = fd.ops.cast(T46, dtype=DataType.BFloat16)\n T50 = fd.ops.cast(T48, dtype=DataType.BFloat16)\n T51 = fd.ops.cast(T22, dtype=DataType.BFloat16)\n fd.add_output(T50)\n fd.add_output(T49)\n fd.add_output(T51)\n\n inputs = [\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bool, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 1), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((24578,), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs, validate_results=True)\n\n\ndef test_ca_map_concrete_loop_id(nvfuser_direct_test):\n def nvfuser_fusion_id10(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[16, 1, 1],\n contiguity=[True, None, None],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, 1, 1024],\n contiguity=[None, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T2 = fd.ops.sub(T0, T0)\n T3 = fd.ops.exp(T2)\n T4 = fd.ops.reciprocal(T3)\n T5 = fd.ops.mul(T3, T4)","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_ca_map_concrete_loop_id","uri":"program://Fuser/function/tests.python.direct.test_repro.test_ca_map_concrete_loop_id#L4547-L4588","kind":"function","name":"test_ca_map_concrete_loop_id","path":"tests/python/direct/test_repro.py","language":"python","start_line":4547,"end_line":4588,"context_start_line":4527,"context_end_line":4608,"code":" T47 = fd.ops.mul(T46, S12)\n T48 = fd.ops.mul(T47, T8)\n T49 = fd.ops.cast(T46, dtype=DataType.BFloat16)\n T50 = fd.ops.cast(T48, dtype=DataType.BFloat16)\n T51 = fd.ops.cast(T22, dtype=DataType.BFloat16)\n fd.add_output(T50)\n fd.add_output(T49)\n fd.add_output(T51)\n\n inputs = [\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bool, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 1), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((24578,), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs, validate_results=True)\n\n\ndef test_ca_map_concrete_loop_id(nvfuser_direct_test):\n def nvfuser_fusion_id10(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[16, 1, 1],\n contiguity=[True, None, None],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, 1, 1024],\n contiguity=[None, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T2 = fd.ops.sub(T0, T0)\n T3 = fd.ops.exp(T2)\n T4 = fd.ops.reciprocal(T3)\n T5 = fd.ops.mul(T3, T4)\n T6 = fd.ops.broadcast(T5, is_broadcast_dim=[False, False, True, False])\n S7 = fd.ops.size(T5, dim=1)\n S8 = fd.define_scalar(16, dtype=DataType.Int)\n S9 = fd.define_scalar(64, dtype=DataType.Int)\n T11 = fd.ops.reshape(T1, new_shape=[S7, S7, S8, S9])\n T12 = fd.ops.permute(T11, dims=[0, 2, 1, 3])\n T13 = fd.ops.squeeze(T12, dims=[0], squeeze_expanded=True)\n T14 = fd.ops.permute(T13, dims=[0, 2, 1])\n T15 = fd.ops.broadcast(T14, is_broadcast_dim=[False, True, False, False])\n T16 = fd.ops.mul(T6, T15)\n T17 = fd.ops.squeeze(T16, dims=[3], squeeze_expanded=True)\n T18 = fd.ops.broadcast(T17, is_broadcast_dim=[True, False, False, False])\n T19 = fd.ops.permute(T18, dims=[0, 2, 1, 3])\n S20 = fd.define_scalar(1024, dtype=DataType.Int)\n T22 = fd.ops.reshape(T19, new_shape=[S7, S7, S20])\n fd.add_output(T5)\n fd.add_output(T13)\n fd.add_output(T22)\n\n inputs = [\n torch.testing.make_tensor((16, 1, 1), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 1, 1024), dtype=torch.float32, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id10, inputs, validate_results=True)\n\n\ndef test_issue5377(nvfuser_direct_test):\n \"\"\"\n Repro for issue 5377, where a traversal for vectorize validation\n failed to find an allocation ID that corresponds to a vectorized\n ID.\n \"\"\"\n\n def nvfuser_fusion(fd: FusionDefinition) -> None:\n tv0 = fd.define_tensor(\n shape=[1, 16],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n tv1 = fd.define_tensor(\n shape=[1, 16],\n contiguity=[None, True],\n dtype=DataType.BFloat16,","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_issue5377","uri":"program://Fuser/function/tests.python.direct.test_repro.test_issue5377#L4591-L4831","kind":"function","name":"test_issue5377","path":"tests/python/direct/test_repro.py","language":"python","start_line":4591,"end_line":4831,"context_start_line":4571,"context_end_line":4831,"code":" T13 = fd.ops.squeeze(T12, dims=[0], squeeze_expanded=True)\n T14 = fd.ops.permute(T13, dims=[0, 2, 1])\n T15 = fd.ops.broadcast(T14, is_broadcast_dim=[False, True, False, False])\n T16 = fd.ops.mul(T6, T15)\n T17 = fd.ops.squeeze(T16, dims=[3], squeeze_expanded=True)\n T18 = fd.ops.broadcast(T17, is_broadcast_dim=[True, False, False, False])\n T19 = fd.ops.permute(T18, dims=[0, 2, 1, 3])\n S20 = fd.define_scalar(1024, dtype=DataType.Int)\n T22 = fd.ops.reshape(T19, new_shape=[S7, S7, S20])\n fd.add_output(T5)\n fd.add_output(T13)\n fd.add_output(T22)\n\n inputs = [\n torch.testing.make_tensor((16, 1, 1), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 1, 1024), dtype=torch.float32, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id10, inputs, validate_results=True)\n\n\ndef test_issue5377(nvfuser_direct_test):\n \"\"\"\n Repro for issue 5377, where a traversal for vectorize validation\n failed to find an allocation ID that corresponds to a vectorized\n ID.\n \"\"\"\n\n def nvfuser_fusion(fd: FusionDefinition) -> None:\n tv0 = fd.define_tensor(\n shape=[1, 16],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n tv1 = fd.define_tensor(\n shape=[1, 16],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n tv2 = fd.define_tensor(\n shape=[1, 5120],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n tv3 = fd.define_tensor(\n shape=[16, 5120, 16384],\n contiguity=[True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n tv4 = fd.define_tensor(\n shape=[16, 8192, 5120],\n contiguity=[True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n tv5 = fd.define_tensor(\n shape=[8192, 5120],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n tv6 = fd.define_tensor(\n shape=[8192, 5120],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n tv7 = fd.define_tensor(\n shape=[5120, 8192],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n tv41 = fd.ops.linear(tv2, tv5)\n tv42 = fd.ops.cast(tv41, dtype=DataType.Float)\n tv43 = fd.ops.neg(tv42)\n tv44 = fd.ops.exp(tv43)\n tv45 = fd.ops.add(1.00000, tv44)\n tv46 = fd.ops.reciprocal(tv45)\n tv47 = fd.ops.mul(tv42, tv46)\n tv48 = fd.ops.linear(tv2, tv6)\n tv49 = fd.ops.cast(tv48, dtype=DataType.Float)\n tv50 = fd.ops.mul(tv47, tv49)\n tv51 = fd.ops.cast(tv50, dtype=DataType.BFloat16)\n tv52 = fd.ops.linear(tv51, tv7)\n tv15 = fd.ops.broadcast(tv2, is_broadcast_dim=[True, False, True, False])\n tv16 = fd.ops.expand(tv15, shape=[16, 1, 1, 5120])\n tv17 = fd.ops.squeeze(tv16, dims=[1, 2])\n tv22 = fd.ops.cast(tv17, dtype=DataType.Float)\n tv8 = fd.ops.cast(tv0, dtype=DataType.BFloat16)\n tv9 = fd.ops.cast(tv8, dtype=DataType.Float)\n tv10 = fd.ops.neg(tv9)\n tv11 = fd.ops.exp(tv10)\n tv12 = fd.ops.add(1.00000, tv11)\n tv13 = fd.ops.reciprocal(tv12)\n tv14 = fd.ops.cast(tv13, dtype=DataType.BFloat16)\n tv18 = fd.ops.squeeze(tv14, dims=[0])\n tv19 = fd.ops.broadcast(tv18, is_broadcast_dim=[False, True])\n tv20 = fd.ops.cast(tv19, dtype=DataType.BFloat16)\n tv21 = fd.ops.expand(tv20, shape=[16, 5120])\n tv23 = fd.ops.cast(tv21, dtype=DataType.Float)\n tv24 = fd.ops.mul(tv22, tv23)\n tv25 = fd.ops.cast(tv24, dtype=DataType.BFloat16)\n tv26 = fd.ops.broadcast(tv25, is_broadcast_dim=[False, True, False])\n tv27 = fd.ops.matmul(tv26, tv3)\n tv29 = fd.ops.slice(\n tv27,\n start_indices=[0, 0, 8192],\n end_indices=[16, 1, 16384],\n strides=[1, 1, 1],\n manual_normalization=True,\n )\n tv36 = fd.ops.cast(tv29, dtype=DataType.Float)\n tv28 = fd.ops.slice(\n tv27,\n start_indices=[0, 0, 0],\n end_indices=[16, 1, 8192],\n strides=[1, 1, 1],\n manual_normalization=True,\n )\n tv30 = fd.ops.cast(tv28, dtype=DataType.Float)\n tv31 = fd.ops.neg(tv30)\n tv32 = fd.ops.exp(tv31)\n tv33 = fd.ops.add(1.00000, tv32)\n tv34 = fd.ops.reciprocal(tv33)\n tv35 = fd.ops.mul(tv30, tv34)\n tv37 = fd.ops.mul(tv36, tv35)\n tv38 = fd.ops.cast(tv37, dtype=DataType.BFloat16)\n tv39 = fd.ops.matmul(tv38, tv4)\n tv40 = fd.ops.squeeze(tv39, dims=[1])\n tv53 = fd.ops.broadcast(tv40, is_broadcast_dim=[False, True, False])\n tv54 = fd.ops.cast(tv53, dtype=DataType.Float)\n tv55 = fd.ops.sum(tv54, dims=[0], dtype=DataType.Float)\n tv56 = fd.ops.cast(tv55, dtype=DataType.BFloat16)\n fd.add_output(tv8, tv1)\n fd.add_output(tv52)\n fd.add_output(tv56)\n\n inputs = [\n torch.testing.make_tensor((1, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 5120), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor(\n (16, 5120, 16384), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (16, 8192, 5120), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor((8192, 5120), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((8192, 5120), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((5120, 8192), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion, inputs, validate_results=True)\n\n # https://github.com/NVIDIA/Fuser/issues/5346\n def test_register_aliasing_bug(nvfuser_direct_test):\n def nvfuser_fusion(fd: FusionDefinition, dim0, dim1) -> None:\n T0 = fd.define_tensor(\n shape=[dim1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T1 = fd.define_tensor(\n shape=[1, dim0, dim1],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, dim0, dim1],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, dim0, 1],\n contiguity=[None, True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T8 = fd.ops.broadcast_in_dim(T0, shape=[1, dim0, dim1], broadcast_dims=[2])\n T9 = fd.ops.mul(T8, T1)\n T10 = fd.ops.mul(T2, T9)\n T11 = fd.ops.sum(T10, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T16 = fd.ops.broadcast_in_dim(T11, shape=[1, dim0, 1], broadcast_dims=[1])\n S17 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T18 = fd.ops.pow(T3, S17)\n S19 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T20 = fd.ops.mul(S19, T16)\n T21 = fd.ops.mul(T20, T18)\n S22 = fd.define_scalar(dim1, dtype=DataType.Double)\n S23 = fd.ops.reciprocal(S22)\n T24 = fd.ops.mul(T21, S23)\n T25 = fd.ops.sum(T24, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T29 = fd.ops.broadcast_in_dim(T25, shape=[1, dim0], broadcast_dims=[1])\n T34 = fd.ops.broadcast_in_dim(\n T29, shape=[1, dim0, 1], broadcast_dims=[0, 1]\n )\n T39 = fd.ops.broadcast_in_dim(\n T3, shape=[1, dim0, dim1], broadcast_dims=[0, 1, 2]\n )\n T44 = fd.ops.broadcast_in_dim(\n T34, shape=[1, dim0, dim1], broadcast_dims=[0, 1, 2]\n )\n T45 = fd.ops.mul(T2, T39)\n T46 = fd.ops.mul(T2, T44)\n T47 = fd.ops.mul(T39, T9)\n T48 = fd.ops.mul(T45, T1)\n T49 = fd.ops.add(T47, T46)\n T50 = fd.ops.add(T49, T46)\n T51 = fd.ops.sum(T48, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T55 = fd.ops.reshape(T50, new_shape=[dim0, dim1])\n fd.add_output(T50)\n fd.add_output(T55)\n fd.add_output(T51)\n\n dim0 = 2048\n dim1 = 32\n with FusionDefinition() as fd:\n nvfuser_fusion(fd, dim0, dim1)\n\n inputs = [\n torch.testing.make_tensor(\n (dim1,),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, dim0, dim1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, dim0, dim1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, dim0, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion, inputs, validate_results=True)","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.fusion_func","uri":"program://Fuser/function/tests.python.direct.test_repro.fusion_func#L82-L104","kind":"function","name":"fusion_func","path":"tests/python/direct/test_repro.py","language":"python","start_line":82,"end_line":104,"context_start_line":62,"context_end_line":124,"code":"def test_issue1246(nvfuser_direct_test):\n \"\"\"\n Test for issue 1246 - tests concatenation with empty tensors and strided tensors.\n\n This test verifies that concatenation operations work correctly with:\n - Strided tensors with non-standard memory layouts\n - Empty tensors (zero-sized dimensions)\n - Both with and without additional operations after concatenation\n \"\"\"\n inputs = [\n torch.randn((8388608,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 32, 2048, 128), (8388608, 262144, 128, 1)\n ),\n torch.randn((0,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (1, 32, 2048, 0), (8388608, 262144, 128, 1)\n ),\n ]\n\n for final_mul in [False, True]:\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, -1, -1, -1],\n contiguity=[None, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, -1, -1, -1],\n contiguity=[None, True, False, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S2 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T3 = fd.ops.mul(T0, S2)\n T4 = fd.ops.cat([T3, T1], dim=-1)\n if final_mul:\n # NOTE: original repro does not have this final op\n S3 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T5 = fd.ops.mul(T4, S3)\n fd.add_output(T5)\n else:\n fd.add_output(T4)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n torch_ref = torch.cat([2.0 * inputs[0], inputs[1]], dim=-1)\n nvfuser_direct_test.assertEqual(nvf_out[0], torch_ref)\n\n\ndef test_issue1270(nvfuser_direct_test):\n \"\"\"\n Test for issue 1270 - tests operations with empty tensors and dead code removal.\n\n This test verifies that operations work correctly with:\n - Empty tensors (zero-sized dimensions)\n - Dead code removal during fusion optimization\n - Complex operations involving casting, multiplication, and reduction\n - Proper handling of empty tensor operations that should not cause problems\n \"\"\"\n inputs = [\n torch.randn(0, device=\"cuda\", dtype=torch.bfloat16).as_strided((5, 0), (1, 0)),\n torch.randn(0, device=\"cuda\", dtype=torch.bfloat16).as_strided((5, 0), (0, 1)),\n ]","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.create_fusion","uri":"program://Fuser/function/tests.python.direct.test_repro.create_fusion#L1304-L1339","kind":"function","name":"create_fusion","path":"tests/python/direct/test_repro.py","language":"python","start_line":1304,"end_line":1339,"context_start_line":1284,"context_end_line":1359,"code":"\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_issue2395(nvfuser_direct_test):\n \"\"\"\n Test for issue 2395 - tests complex operations with strided tensors and multiple data types.\n\n Migrated from `test_issue_2395` in legacy test_pointwise.py\n\n This test verifies that complex operations work correctly with:\n - Large strided tensors with complex memory layouts\n - Multiple data types (Float32 and BFloat16)\n - Complex tensor operations (permute, reshape, slice, sum, mul, neg, add)\n - Broadcasting operations with different shapes\n - Padding operations with scalar values\n - Multiple output tensors from a single fusion\n - Proper handling of tensor contiguity and stride order\n \"\"\"\n\n def create_fusion(fd: FusionDefinition) -> None:\n cond0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, None],\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n values = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n cond1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[1, 0],\n )\n cond1 = fd.ops.broadcast_in_dim(\n cond1, shape=[16, 16, 32], broadcast_dims=[0, 1]\n )\n sliced = fd.ops.slice(\n values,\n start_indices=[0, 0, 16],\n end_indices=[16, 16, 32],\n strides=[1, 1, 1],\n )\n zero = fd.define_scalar(0.00000, dtype=DataType.Double)\n masked = fd.ops.where(cond1, zero, values)\n masked = fd.ops.where(cond0, zero, masked)\n fd.add_output(sliced)\n fd.add_output(masked)\n\n ins = [\n torch.randint(0, 2, (256,), dtype=torch.bool, device=\"cuda:0\").as_strided(\n (16, 16, 32), (16, 1, 0)\n ),\n torch.randn((8192,), dtype=torch.float32, device=\"cuda:0\").as_strided(\n (16, 16, 32), (512, 32, 1)\n ),\n torch.randint(0, 2, (256,), dtype=torch.bool, device=\"cuda:0\").as_strided(\n (16, 16), (16, 1)\n ),\n ]\n outs, _ = nvfuser_direct_test.exec_nvfuser(create_fusion, ins)\n\n nvfuser_direct_test.assertEqual(outs[0], ins[1][:, :, 16:], rtol=0, atol=0)\n nvfuser_direct_test.assertEqual(\n outs[1],\n torch.where(\n torch.logical_or(ins[0] == 1, ins[2].unsqueeze(-1) == 1), 0, ins[1]\n ),","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.nvfuser_fusion_id0","uri":"program://Fuser/function/tests.python.direct.test_repro.nvfuser_fusion_id0#L4460-L4534","kind":"function","name":"nvfuser_fusion_id0","path":"tests/python/direct/test_repro.py","language":"python","start_line":4460,"end_line":4534,"context_start_line":4440,"context_end_line":4554,"code":" ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 2560), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (1, 4096, 10240), dtype=torch.float32, device=\"cuda:0\"\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs, validate_results=True)\n\n\ndef test_shared_memory_usage(nvfuser_direct_test):\n # repro of benchmarks.python.test_dropout_rmsnorm_bwd.test_dropout_rmsnorm_bwd_nvf_benchmark[dtype=torch.bfloat16-size=[16384_24578]]\n # avoid overflow of shared memory usage since previous version didn't consider static smem size\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T2 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Bool, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n )\n T4 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n )\n T5 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.BFloat16, is_cpu=False\n )\n T6 = fd.ops.cast(T1, dtype=DataType.Float)\n T7 = fd.ops.cast(T0, dtype=DataType.Float)\n T8 = fd.ops.cast(T2, dtype=DataType.Float)\n T9 = fd.ops.cast(T4, dtype=DataType.Float)\n T10 = fd.ops.cast(T5, dtype=DataType.Float)\n T11 = fd.ops.mul(T7, T8)\n S12 = fd.define_scalar(1.25000, dtype=DataType.Double)\n T13 = fd.ops.mul(T11, S12)\n T14 = fd.ops.add(T6, T13)\n V15 = fd.ops.shape(T7)\n T16 = fd.ops.broadcast_in_dim(T3, shape=V15, broadcast_dims=[0, 1])\n T17 = fd.ops.reciprocal(T16)\n T18 = fd.ops.mul(T14, T17)\n T19 = fd.ops.broadcast_in_dim(T10, shape=V15, broadcast_dims=[1])\n T20 = fd.ops.mul(T9, T18)\n T21 = fd.ops.mul(T9, T19)\n T22 = fd.ops.sum(T20, dims=[0], keepdim=False, dtype=DataType.Null)\n T23 = fd.ops.mul(T21, T17)\n T24 = fd.ops.neg(T21)\n T25 = fd.ops.mul(T24, T14)\n S26 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T27 = fd.ops.pow(T16, S26)\n T28 = fd.ops.reciprocal(T27)\n T29 = fd.ops.mul(T25, T28)\n T30 = fd.ops.sum(T29, dims=[1], keepdim=False, dtype=DataType.Null)\n S31 = fd.ops.size(T7, dim=0)\n T34 = fd.ops.broadcast_in_dim(T30, shape=[S31, 1], broadcast_dims=[0])\n T35 = fd.ops.mul(S26, T3)\n T36 = fd.ops.reciprocal(T35)\n T37 = fd.ops.mul(T34, T36)\n S38 = fd.ops.size(T7, dim=1)\n S39 = fd.ops.reciprocal(S38)\n T40 = fd.ops.mul(T37, S39)\n T41 = fd.ops.sum(T40, dims=[1], keepdim=False, dtype=DataType.Null)\n T42 = fd.ops.broadcast_in_dim(T41, shape=[S31, 1], broadcast_dims=[0])\n T43 = fd.ops.broadcast_in_dim(T42, shape=V15, broadcast_dims=[0, 1])\n T44 = fd.ops.mul(T43, S26)\n T45 = fd.ops.mul(T44, T14)\n T46 = fd.ops.add(T23, T45)\n T47 = fd.ops.mul(T46, S12)\n T48 = fd.ops.mul(T47, T8)\n T49 = fd.ops.cast(T46, dtype=DataType.BFloat16)\n T50 = fd.ops.cast(T48, dtype=DataType.BFloat16)\n T51 = fd.ops.cast(T22, dtype=DataType.BFloat16)\n fd.add_output(T50)\n fd.add_output(T49)\n fd.add_output(T51)\n\n inputs = [\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bool, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 1), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((24578,), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs, validate_results=True)\n\n\ndef test_ca_map_concrete_loop_id(nvfuser_direct_test):\n def nvfuser_fusion_id10(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[16, 1, 1],\n contiguity=[True, None, None],\n dtype=DataType.Float,\n is_cpu=False,\n )","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.nvfuser_fusion","uri":"program://Fuser/function/tests.python.direct.test_repro.nvfuser_fusion#L4731-L4794","kind":"function","name":"nvfuser_fusion","path":"tests/python/direct/test_repro.py","language":"python","start_line":4731,"end_line":4794,"context_start_line":4711,"context_end_line":4814,"code":"\n inputs = [\n torch.testing.make_tensor((1, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 5120), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor(\n (16, 5120, 16384), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (16, 8192, 5120), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor((8192, 5120), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((8192, 5120), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((5120, 8192), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion, inputs, validate_results=True)\n\n # https://github.com/NVIDIA/Fuser/issues/5346\n def test_register_aliasing_bug(nvfuser_direct_test):\n def nvfuser_fusion(fd: FusionDefinition, dim0, dim1) -> None:\n T0 = fd.define_tensor(\n shape=[dim1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T1 = fd.define_tensor(\n shape=[1, dim0, dim1],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, dim0, dim1],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, dim0, 1],\n contiguity=[None, True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T8 = fd.ops.broadcast_in_dim(T0, shape=[1, dim0, dim1], broadcast_dims=[2])\n T9 = fd.ops.mul(T8, T1)\n T10 = fd.ops.mul(T2, T9)\n T11 = fd.ops.sum(T10, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T16 = fd.ops.broadcast_in_dim(T11, shape=[1, dim0, 1], broadcast_dims=[1])\n S17 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T18 = fd.ops.pow(T3, S17)\n S19 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T20 = fd.ops.mul(S19, T16)\n T21 = fd.ops.mul(T20, T18)\n S22 = fd.define_scalar(dim1, dtype=DataType.Double)\n S23 = fd.ops.reciprocal(S22)\n T24 = fd.ops.mul(T21, S23)\n T25 = fd.ops.sum(T24, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T29 = fd.ops.broadcast_in_dim(T25, shape=[1, dim0], broadcast_dims=[1])\n T34 = fd.ops.broadcast_in_dim(\n T29, shape=[1, dim0, 1], broadcast_dims=[0, 1]\n )\n T39 = fd.ops.broadcast_in_dim(\n T3, shape=[1, dim0, dim1], broadcast_dims=[0, 1, 2]\n )\n T44 = fd.ops.broadcast_in_dim(\n T34, shape=[1, dim0, dim1], broadcast_dims=[0, 1, 2]\n )\n T45 = fd.ops.mul(T2, T39)\n T46 = fd.ops.mul(T2, T44)\n T47 = fd.ops.mul(T39, T9)\n T48 = fd.ops.mul(T45, T1)\n T49 = fd.ops.add(T47, T46)\n T50 = fd.ops.add(T49, T46)\n T51 = fd.ops.sum(T48, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T55 = fd.ops.reshape(T50, new_shape=[dim0, dim1])\n fd.add_output(T50)\n fd.add_output(T55)\n fd.add_output(T51)\n\n dim0 = 2048\n dim1 = 32\n with FusionDefinition() as fd:\n nvfuser_fusion(fd, dim0, dim1)\n\n inputs = [\n torch.testing.make_tensor(\n (dim1,),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, dim0, dim1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.nvfuser_fusion_id28","uri":"program://Fuser/function/tests.python.direct.test_repro.nvfuser_fusion_id28#L1931-L1954","kind":"function","name":"nvfuser_fusion_id28","path":"tests/python/direct/test_repro.py","language":"python","start_line":1931,"end_line":1954,"context_start_line":1911,"context_end_line":1974,"code":" T222 = fd.ops.slice(\n T108,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 7, 5, 0],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T223 = fd.ops.cat([T169, T222], dim=-1, manual_padding=0)\n fd.add_output(T223)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_issue3369(nvfuser_direct_test):\n \"\"\"\n Test for issue 3369 - tests square linear operations.\n\n This test verifies that square linear operations work correctly.\n \"\"\"\n\n def nvfuser_fusion_id28(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[5, 5],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[5, 5],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[5],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T3 = fd.ops.linear(T0, T1, T2)\n fd.add_output(T3)\n\n inputs = [\n torch.testing.make_tensor((5, 5), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((5, 5), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((5,), dtype=torch.float32, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id28, inputs, validate_results=True)\n\n\ndef test_issue4444(nvfuser_direct_test):\n \"\"\"\n Test for issue 4444 - complex tensor operations with multiple slice operations,\n manual normalization, padding, and reshaping operations.\n\n This test validates:\n - Multiple slice operations with manual normalization\n - Complex tensor reshaping and permutation operations\n - Manual padding operations with scalar values\n - Broadcast operations with specific dimensions\n - Cast operations between different data types","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.nvfuser_fusion_id10","uri":"program://Fuser/function/tests.python.direct.test_repro.nvfuser_fusion_id10#L4548-L4582","kind":"function","name":"nvfuser_fusion_id10","path":"tests/python/direct/test_repro.py","language":"python","start_line":4548,"end_line":4582,"context_start_line":4528,"context_end_line":4602,"code":" T48 = fd.ops.mul(T47, T8)\n T49 = fd.ops.cast(T46, dtype=DataType.BFloat16)\n T50 = fd.ops.cast(T48, dtype=DataType.BFloat16)\n T51 = fd.ops.cast(T22, dtype=DataType.BFloat16)\n fd.add_output(T50)\n fd.add_output(T49)\n fd.add_output(T51)\n\n inputs = [\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bool, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 1), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((16, 24578), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((24578,), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id0, inputs, validate_results=True)\n\n\ndef test_ca_map_concrete_loop_id(nvfuser_direct_test):\n def nvfuser_fusion_id10(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[16, 1, 1],\n contiguity=[True, None, None],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, 1, 1024],\n contiguity=[None, None, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T2 = fd.ops.sub(T0, T0)\n T3 = fd.ops.exp(T2)\n T4 = fd.ops.reciprocal(T3)\n T5 = fd.ops.mul(T3, T4)\n T6 = fd.ops.broadcast(T5, is_broadcast_dim=[False, False, True, False])\n S7 = fd.ops.size(T5, dim=1)\n S8 = fd.define_scalar(16, dtype=DataType.Int)\n S9 = fd.define_scalar(64, dtype=DataType.Int)\n T11 = fd.ops.reshape(T1, new_shape=[S7, S7, S8, S9])\n T12 = fd.ops.permute(T11, dims=[0, 2, 1, 3])\n T13 = fd.ops.squeeze(T12, dims=[0], squeeze_expanded=True)\n T14 = fd.ops.permute(T13, dims=[0, 2, 1])\n T15 = fd.ops.broadcast(T14, is_broadcast_dim=[False, True, False, False])\n T16 = fd.ops.mul(T6, T15)\n T17 = fd.ops.squeeze(T16, dims=[3], squeeze_expanded=True)\n T18 = fd.ops.broadcast(T17, is_broadcast_dim=[True, False, False, False])\n T19 = fd.ops.permute(T18, dims=[0, 2, 1, 3])\n S20 = fd.define_scalar(1024, dtype=DataType.Int)\n T22 = fd.ops.reshape(T19, new_shape=[S7, S7, S20])\n fd.add_output(T5)\n fd.add_output(T13)\n fd.add_output(T22)\n\n inputs = [\n torch.testing.make_tensor((16, 1, 1), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 1, 1024), dtype=torch.float32, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id10, inputs, validate_results=True)\n\n\ndef test_issue5377(nvfuser_direct_test):\n \"\"\"\n Repro for issue 5377, where a traversal for vectorize validation\n failed to find an allocation ID that corresponds to a vectorized\n ID.\n \"\"\"\n\n def nvfuser_fusion(fd: FusionDefinition) -> None:\n tv0 = fd.define_tensor(\n shape=[1, 16],\n contiguity=[None, True],\n dtype=DataType.BFloat16,","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_repro.test_register_aliasing_bug","uri":"program://Fuser/function/tests.python.direct.test_repro.test_register_aliasing_bug#L4730-L4831","kind":"function","name":"test_register_aliasing_bug","path":"tests/python/direct/test_repro.py","language":"python","start_line":4730,"end_line":4831,"context_start_line":4710,"context_end_line":4831,"code":" fd.add_output(tv56)\n\n inputs = [\n torch.testing.make_tensor((1, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((1, 5120), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor(\n (16, 5120, 16384), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (16, 8192, 5120), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n torch.testing.make_tensor((8192, 5120), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((8192, 5120), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.testing.make_tensor((5120, 8192), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion, inputs, validate_results=True)\n\n # https://github.com/NVIDIA/Fuser/issues/5346\n def test_register_aliasing_bug(nvfuser_direct_test):\n def nvfuser_fusion(fd: FusionDefinition, dim0, dim1) -> None:\n T0 = fd.define_tensor(\n shape=[dim1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n T1 = fd.define_tensor(\n shape=[1, dim0, dim1],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, dim0, dim1],\n contiguity=[None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T3 = fd.define_tensor(\n shape=[1, dim0, 1],\n contiguity=[None, True, None],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T8 = fd.ops.broadcast_in_dim(T0, shape=[1, dim0, dim1], broadcast_dims=[2])\n T9 = fd.ops.mul(T8, T1)\n T10 = fd.ops.mul(T2, T9)\n T11 = fd.ops.sum(T10, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T16 = fd.ops.broadcast_in_dim(T11, shape=[1, dim0, 1], broadcast_dims=[1])\n S17 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T18 = fd.ops.pow(T3, S17)\n S19 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T20 = fd.ops.mul(S19, T16)\n T21 = fd.ops.mul(T20, T18)\n S22 = fd.define_scalar(dim1, dtype=DataType.Double)\n S23 = fd.ops.reciprocal(S22)\n T24 = fd.ops.mul(T21, S23)\n T25 = fd.ops.sum(T24, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T29 = fd.ops.broadcast_in_dim(T25, shape=[1, dim0], broadcast_dims=[1])\n T34 = fd.ops.broadcast_in_dim(\n T29, shape=[1, dim0, 1], broadcast_dims=[0, 1]\n )\n T39 = fd.ops.broadcast_in_dim(\n T3, shape=[1, dim0, dim1], broadcast_dims=[0, 1, 2]\n )\n T44 = fd.ops.broadcast_in_dim(\n T34, shape=[1, dim0, dim1], broadcast_dims=[0, 1, 2]\n )\n T45 = fd.ops.mul(T2, T39)\n T46 = fd.ops.mul(T2, T44)\n T47 = fd.ops.mul(T39, T9)\n T48 = fd.ops.mul(T45, T1)\n T49 = fd.ops.add(T47, T46)\n T50 = fd.ops.add(T49, T46)\n T51 = fd.ops.sum(T48, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T55 = fd.ops.reshape(T50, new_shape=[dim0, dim1])\n fd.add_output(T50)\n fd.add_output(T55)\n fd.add_output(T51)\n\n dim0 = 2048\n dim1 = 32\n with FusionDefinition() as fd:\n nvfuser_fusion(fd, dim0, dim1)\n\n inputs = [\n torch.testing.make_tensor(\n (dim1,),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, dim0, dim1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, dim0, dim1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n torch.testing.make_tensor(\n (1, dim0, 1),\n dtype=torch.float32,\n device=\"cuda:0\",\n low=LOW_VAL,\n high=HIGH_VAL,\n ),\n ]\n nvfuser_direct_test.exec_nvfuser(nvfuser_fusion, inputs, validate_results=True)","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial","uri":"program://Fuser/module/tests.python.direct.test_tutorial#L1-L2005","kind":"module","name":"tests.python.direct.test_tutorial","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1,"end_line":2005,"context_start_line":1,"context_end_line":2005,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nimport torch.nn.functional as F\nfrom nvfuser_direct import (\n FusionDefinition,\n IdMappingMode,\n ParallelType,\n TensorView,\n Merge,\n Split,\n BroadcastOp,\n SqueezeOp,\n ReshapeOp,\n LoadStoreOpType,\n MemoryType,\n DataType,\n CompileParams,\n KernelExecutor,\n SchedulerType,\n PythonProfiler,\n)\nfrom nvfuser_direct import idm, schedule\n\nfrom python.direct_utils import (\n is_pre_hopper,\n)\n\nverbose_ = True\n\n\n# A helper function to test heuristic schedulers with automatic scheduling\ndef check_auto_schedule(schedule_fn):\n \"\"\"\n A decorator to validate a schedule_fn before applying it to a fusion.\n\n Args:\n schedule_fn: The function to apply the scheduler\n \"\"\"\n # List of all scheduler heuristics for testing\n # NOTE We cannot iterate pybind11 enum directly, so we extract the entries here.\n all_scheduler_heuristics = [\n heuristic\n for heuristic, _ in SchedulerType.__entries.values()\n if not SchedulerType.none\n ]\n\n def inner_fn(fusion, selected_heuristic, inputs):\n \"\"\"\n Helper function to validate a schedule_fn.\n\n Args:\n fusion: The Fusion object to schedule\n selected_heuristic: The SchedulerType expected to work\n inputs: Input tensors for the fusion\n \"\"\"\n available_heuristics = schedule.find_compatible_schedulers(fusion, inputs)\n\n # Assume that only a single heuristic is available for fusion\n assert len(available_heuristics) == 1\n\n # Check that only selected heuristic is available as a scheduler\n assert set(available_heuristics) == set([selected_heuristic])\n\n # Double-check with can_schedule\n status, _ = schedule.can_schedule(fusion, selected_heuristic, inputs)\n assert status\n\n # Check that the other schedulers are not compatible with this fusion\n assert all(\n [\n not schedule.can_schedule(fusion, h, inputs)[0]\n for h in all_scheduler_heuristics\n if h is not selected_heuristic\n ]\n )\n return schedule_fn(fusion, selected_heuristic, inputs)\n\n return inner_fn\n\n\ndef test_tutorial_memcpy():\n # First, we define a fusion. A common pattern is:\n # - Declare a Fusion, which works as a container of expressions using\n # with context manager.\n # - Setup inputs. fd.define_tensor can be used to manually create tensors.\n # fd.from_pytorch will create a TensorView given a pytorch tensor. Fusion\n # registration is automatic.\n # - Define operations with the registered inputs.\n # For supported operations, run:\n # >>> import nvfuser_direct\n # >>> fd = nvfuser_direct.FusionDefinition()\n # >>> help(fd.ops)\n # - Most of operations that take tensors as inputs produce tensors\n # as outputs, which can then be used as inputs to another\n # operations.\n # - Final outputs should be set as fusion outputs with fd.add_output\n\n with FusionDefinition() as fd:\n # Create a 2D tensor of type float. It's \"symbolic\" as we do not\n # assume any specific shape except for that it's 2D.\n tv0 = fd.define_tensor(shape=[-1, -1])\n\n # Just create a copy\n tv1 = fd.ops.set(tv0)\n fd.add_output(tv1)\n\n if verbose_:\n # Here's some common ways to inspect the fusion. These are not\n # necessary for running the fusion but should provide helpful\n # information for understanding how fusions are transformed.\n\n # Print a concise representation of the fusion exprssions\n print(fd.fusion.print_math())\n\n # Generate and print a CUDA kernel. Notice that at this point the\n # genereated code is just a sequential kernel as we have not\n # scheduled the fusion yet, but it should be a valid CUDA kernel\n print(fd.fusion.print_kernel())\n\n # Next, try running the fusion. First, we need to set up a sample\n # input tensor. Here, we create a 32x32 tensor initialized with\n # random float values.\n\n t0 = torch.randn(32, 32, dtype=torch.float, device=\"cuda:0\")\n\n # Next, lower the Fusion to Kernel, generate CUDA kernel source and then\n # compile it with nvrtc. After compilation, KernelExecutor now has a\n # compiled kernel, which can be executed as:\n outputs = fd.manual_execute([t0])\n\n # Note that this run is done using just one thread, which will be\n # corrected below.\n\n # To validate the output, we can just assert that the output is\n # equal to the input as this is just a copy fusion. More commonly,\n # though, fd.validate is used to validate outputs while\n # automatically adjusting thresholds of valid deviations.\n assert outputs[0].equal(t0)\n\n\ndef test_tutorial_memcpy_scheduled():\n # test_tutorial_memcpy_scheduled is a continuation from test_tutorial_memcpy\n\n # Instead of just running the fusion as is, we manually schedule it so that\n # it runs in parallel. In this case, we only have one expression, so we\n # just need to schedule tv1.\n\n # tv1 is a 2D tensor. Let its domain be [i0, i1]. We are going transform\n # this 2D domain to a CUDA Grid and Block. Specifically, a grid consisting\n # of multiple thread blocks, each of which containin multiple threads. A\n # common transformation pattern is to merge all of each axis to get a\n # flattened domain, and then split the domain to factor out axes that are\n # parallelized by threads and thread blocks.\n\n # In python, we can only modify the FusionDefinition inside a with context.\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[-1, -1])\n tv1 = fd.ops.set(tv0)\n fd.add_output(tv1)\n\n # For example, the current domain of tv1 looks like [i0, i1]. We can\n # merge the two axes by:\n tv1.merge(0, 1)\n\n # This creates a single axis that merges i0 and i1. Its extent is a\n # multiplication of the extents of i0 and i1, so we commonly represent\n # it as [i0 * i1]. It can be also examined with:\n if verbose_:\n print(tv1)\n\n # Next, we factor out a subdomain for threads in each thread block.\n tv1.split(0, 256)\n\n # In this case, the flattened domain is now 2D domain with an inner\n # domain of extent 256 and an outer domain of extent i0*i1/256, so the\n # tensor should now look like [i0*i1/256, 256]. Note that in reality we\n # do ceiling division as i0 * i1 may not be divisible by 256.\n if verbose_:\n print(tv1)\n\n # Now that we have two domains, we can parallelize each domain using\n # IterDomain.parallelize(ParallelType). Specifically, to parallelize the\n # inner domain with threads, we can do:\n tv1.axis(1).parallelize(ParallelType.block_x)\n # Similarly, to paralllize the outer domain with thread blocks:\n tv1.axis(0).parallelize(ParallelType.grid_x)\n # This way, the inner and outer axes are divided by blockDim.x threads\n # and gridDim.x blocks, respectively. Each element in each axis is\n # computed by one thread or one block, so this means that the size of\n # each thread block and a grid must match the size of each domain.\n # blockDim.x and gridDim.x must be 256 and i0*i1/256.\n\n # Now that the fusion is parallelized, it can be examined again.\n if verbose_:\n print(fd.fusion.print_math())\n # Notice that the axes of tv1 are now printed with blockIdx.x and\n # threadIdx.x, which shows they are parallelized by the\n # respective parallel types.\n\n # The CUDA kernel should look very differently as there should be no\n # for-loops.\n print(fd.fusion.print_kernel())\n\n # This time, the kernel is launched with multiple threads and thread\n # blocks. Note that the thread block and grid shapes are inferred from the\n # given inputs. To see how many threads are used, run this test\n # with NVFUSER_DUMP=launch_param\n t0 = torch.randn(32, 32, dtype=torch.float, device=\"cuda:0\")\n outputs = fd.manual_execute([t0])\n assert outputs[0].equal(t0)\n\n\ndef test_tutorial_reduction():\n def fusion_func(fd: FusionDefinition) -> TensorView:\n # Create a 2D tensor\n tv0 = fd.define_tensor(shape=[-1, -1])\n\n # Reduce the second dimension\n tv1 = fd.ops.sum(tv0, dims=[1])\n fd.add_output(tv1)\n\n return tv1\n\n with FusionDefinition() as fd0:\n ref_tv = fusion_func(fd0)\n\n # At this point, nothing is parallelized. The reduction is done by\n # a single thread sequentially.\n\n if verbose_:\n print(fd0.fusion.print_math())\n print(fd0.fusion.print_kernel())\n\n # Block-parallel reduction\n ref_tv.axis(1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd0.fusion.print_math())\n print(fd0.fusion.print_kernel())\n\n t0 = torch.randn(10, 1024, dtype=torch.float, device=\"cuda:0\")\n ref = t0.sum(dim=1)\n\n fd0.manual_validate([t0], [ref])\n\n # Create another FusionDefinition with same math but different schedule.\n with FusionDefinition() as fd1:\n ref_tv = fusion_func(fd1)\n\n # Next, use the same fusion but parallelize the reduction with\n # thread blocks\n ref_tv.axis(1).parallelize(ParallelType.grid_x)\n\n if verbose_:\n print(fd1.fusion.print_math())\n print(fd1.fusion.print_kernel())\n\n fd1.manual_validate([t0], [ref])\n\n # Create another FusionDefinition with same math but different schedule.\n with FusionDefinition() as fd2:\n ref_tv = fusion_func(fd2)\n\n # We can also parallelize the first axis as well. For example,\n # here's how threadIdx.x is used for the reduction and threadIdx.y\n # is used for the outer non-reduction domain\n ref_tv.axis(0).parallelize(ParallelType.block_y)\n ref_tv.axis(1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd2.fusion.print_math())\n print(fd2.fusion.print_kernel())\n\n # Running this fusion, however, should fail as it would require thread\n # blocks of shape 1024x10, i.e., the same shape as the input tensor, which\n # is too large in CUDA.\n with pytest.raises(RuntimeError):\n fd2.manual_validate([t0], [ref])\n\n # Try again with a smaller input. This should launch a kernel\n # with thread blocks of shape 32x10\n t1 = torch.randn(10, 32, dtype=torch.float, device=\"cuda:0\")\n fd2.manual_validate([t1], [t1.sum(dim=1)])\n\n # Create another FusionDefinition with same math but different schedule.\n with FusionDefinition() as fd3:\n ref_tv = fusion_func(fd3)\n\n # We can of course mix BIDx and TIDx.\n ref_tv.axis(0).parallelize(ParallelType.grid_x)\n ref_tv.axis(1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd3.fusion.print_math())\n print(fd3.fusion.print_kernel())\n\n # The original input should not fail in this case. The kernel will be\n # launched with 10 thread blocks, each of which has 1024 threads. Try\n # running this test with NVFUSER_DUMP=launch_param to see the launch\n # configuration of each kernel lauch\n fd3.manual_validate([t0], [ref])\n\n\ndef test_tutorial_reduction_rfactor():\n # Just a very simple reduction of 1D tensor\n def fusion_func(fd: FusionDefinition) -> TensorView:\n tv0 = fd.define_tensor(shape=[-1])\n tv1 = fd.ops.sum(tv0, dims=[0])\n fd.add_output(tv1)\n return tv1\n\n # Create separate fusions because of multiple schedules\n with FusionDefinition() as fd0:\n tv1 = fusion_func(fd0)\n\n # A common pattern of reductions in CUDA involves multiple steps of\n # reductions, where the first step is a per-thread local reduction,\n # followed by a block reduction of the per-thread partial results,\n # and also potentially followed by a grid reduction of the\n # per-block partial results. Here's an example with a two-step\n # reduction:\n #\n # // Step 1: Per-thread reduction\n # float partial_result = 0;\n # for (int i = threadIdx.x; i += blockDim.x; i < N) {\n # partial_result += input[i];\n # }\n #\n # // Step 2: Accumulation within each thread block\n # __shared__ float shared_buf[blockDim.x];\n # shared_buf[threadIdx.x] = partial_result;\n # __syncthreads();\n # float final_result = 0;\n # // Accumulation of the partila result in a naive sequntial way.\n # if (threadIdx.x == 0) {\n # for (int i = 0; i < blockDim.x; ++i) {\n # final_result += shared_buf[i];\n # }\n # }\n\n # To reproduce the multi-step reduction pattern in nvFuser, a fusion\n # transformation called reduction rfactor is used. The basic idea is to\n # split a reduction domain such that each of the output domains of the\n # split is separately reduced. For example, tv1 can be transformed from\n # a 2D tensor to a 3D tensor as follows:\n\n # tv0: [i0]\n # tv1: [r1]\n tv1.split(0, 1024)\n # tv1: [r1/1024, r1024]\n\n # Both of the two inner domains are reduction domains, and we first\n # want to reduce the second domain, i.e., r1/1024, by each thread\n # independently, and then reduce the other reduction domain by a\n # block reduction. This can be done as follows:\n tv2 = tv1.rfactor([0])\n\n # The fusion math should now look like:\n # tv0: root = logical = [i{i0}]\n # tv2 = reduction(tv0): root = [r{i0}], logical = [r{i0/1024}, i{1024}]\n # tv1 = reduction(tv2): root = logical = [r{1024}]\n if verbose_:\n print(fd0.fusion.print_math())\n\n # Notice that the reduction operation is now split into two operations,\n # where the first one takes care of the first domain, and the second one\n # finishes up the remaining domain. The final values of tv1 is not\n # altered, but its computation is changed. (More strictly, since\n # floating-point addition is not associative, the final result will not\n # be exactly the same due to rounding errors)\n\n # To realize the parallelization as we sketched above, we can\n # use TIDx for both of tv1 and tv2 as follows:\n tv1.axis(0).parallelize(ParallelType.block_x)\n tv2.axis(1).parallelize(ParallelType.block_x)\n\n # At this point, tv2 is a TIDx-parallelized operation of multiple\n # independent reductions. There will be 1024 threads, each of which\n # reduces the first axis of size r1/1024. tv1 is also parallelized by\n # TIDx, but unlike tv2 the reduction domain is parallelized, so it\n # becomes a block-reduction operation.\n if verbose_:\n print(fd0.fusion.print_math())\n print(fd0.fusion.print_kernel())\n\n # Let's run the scheduled fusion\n t0 = torch.randn(10000, dtype=torch.float, device=\"cuda:0\")\n ref = t0.sum(dim=0)\n fd0.manual_validate([t0], [ref])\n\n # We can further increase the parallelism by splitting the reduction domain\n # into three\n with FusionDefinition() as fd1:\n tv1 = fusion_func(fd1)\n\n # First, split for TIDx of 1024 threads\n tv1.split(0, 1024)\n # Next, split for BIDx of 100 thread blocks\n tv1.split(0, 100)\n # tv1: [r0/1024/100, r100, r1024]\n\n # Factoring out per-thread reduction\n tv2 = tv1.rfactor([1])\n # tv2: [i0/1024/100, r100, i1024]\n # tv1: [r0/1024/100, r1024]\n\n # Factoring out block reduction\n tv3 = tv1.rfactor([1])\n # tv2: [i0/1024/100, r100, i1024]\n # tv3: [i0/1024/100, r1024]\n # tv1: [r0/1024/100]\n\n # Parallelize each operation as follows\n # tv2: [bidx(i0/1024/100), r100, tidx(i1024)]\n # tv3: [bidx(i0/1024/100), tidx(r1024)]\n # tv1: [bidx(r0/1024/100)]\n tv2.axis(0).parallelize(ParallelType.grid_x)\n tv3.axis(0).parallelize(ParallelType.grid_x)\n tv1.axis(0).parallelize(ParallelType.grid_x)\n tv2.axis(2).parallelize(ParallelType.block_x)\n tv3.axis(1).parallelize(ParallelType.block_x)\n # Note that this could be also done more easily using\n # scheduler_utils::parallelizeAllLike.\n\n if verbose_:\n print(fd1.fusion.print_math())\n print(fd1.fusion.print_kernel())\n\n t1 = torch.randn(10000000, dtype=torch.float, device=\"cuda:0\")\n ref1 = t1.sum(dim=0)\n fd1.manual_validate([t1], [ref1])\n\n\ndef test_tutorial_reshape():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[4, 8])\n\n # Shape of tv0 is assumed to be [4, 8], which is then reshaped to [32]\n tv1 = fd.ops.reshape(tv0, [32])\n fd.add_output(tv1)\n\n if verbose_:\n # Notice that tv1 has root and logical domains. The root domain has two\n # IterDomains, whereas the logical domain consists of a single\n # IterDomain that is an output of a merge operation of the two root\n # IterDomains.\n print(fd.fusion.print_math())\n\n # Check if the tv1 domains are generated as expected\n assert tv1.has_root()\n assert len(tv1.get_logical_domain()) == 1\n # In python, use type() function to check an object's class.\n # In CPP, use isA template function.\n tv1_merge = tv1.get_logical_domain()[0].definition()\n assert type(tv1_merge) is Merge\n assert tv1_merge.inner() == tv1.get_root_domain()[1]\n assert tv1_merge.outer() == tv1.get_root_domain()[0]\n\n # Reshape example with broadcast domains\n with FusionDefinition() as fd1:\n # Create a 3D tensor with a broadcast domain\n tv0 = fd1.define_tensor(shape=[1, 2, 3])\n\n # tv0 is first squeezed and then reshaped and unsqueezed\n tv1 = fd1.ops.reshape(tv0, [3, 2, 1])\n fd1.add_output(tv1)\n\n if verbose_:\n print(fd1.fusion.print_math())\n\n # The fusion should look like:\n #\n # tv1 = unsqueeze(reshape(squeeze(tv0)));\n assert type(tv1.definition()) is BroadcastOp\n reshape_output = tv1.definition().input(0)\n assert type(reshape_output.definition()) is ReshapeOp\n squeeze_output = reshape_output.definition().input(0)\n assert type(squeeze_output.definition()) is SqueezeOp\n\n assert reshape_output.has_root()\n assert len(reshape_output.get_logical_domain()) == 2\n assert type(reshape_output.get_logical_domain()[0].definition()) is Split\n reshape_output_split = reshape_output.get_logical_domain()[0].definition()\n assert reshape_output_split.outer() == reshape_output.get_logical_domain()[0]\n assert reshape_output_split.inner() == reshape_output.get_logical_domain()[1]\n assert type(reshape_output_split.input(0).definition()) is Merge\n reshape_output_merge = reshape_output_split.input(0).definition()\n assert reshape_output_merge.outer() == reshape_output.get_root_domain()[0]\n assert reshape_output_merge.inner() == reshape_output.get_root_domain()[1]\n\n # So far, the fusion has transformations as part of its definition. It can\n # be further extended with scheduling transformations.\n reshape_output.merge(0, 1)\n reshape_output.split(0, 128)\n\n assert type(reshape_output.get_loop_domain()[0].definition()) is Split\n assert (\n reshape_output.get_loop_domain()[0].definition().inner()\n == reshape_output.get_loop_domain()[1]\n )\n assert (\n type(reshape_output.get_loop_domain()[0].definition().input(0).definition())\n == Merge\n )\n assert (\n reshape_output.get_loop\n# ... truncated ...","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.check_auto_schedule","uri":"program://Fuser/function/tests.python.direct.test_tutorial.check_auto_schedule#L37-L83","kind":"function","name":"check_auto_schedule","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":37,"end_line":83,"context_start_line":17,"context_end_line":103,"code":" SqueezeOp,\n ReshapeOp,\n LoadStoreOpType,\n MemoryType,\n DataType,\n CompileParams,\n KernelExecutor,\n SchedulerType,\n PythonProfiler,\n)\nfrom nvfuser_direct import idm, schedule\n\nfrom python.direct_utils import (\n is_pre_hopper,\n)\n\nverbose_ = True\n\n\n# A helper function to test heuristic schedulers with automatic scheduling\ndef check_auto_schedule(schedule_fn):\n \"\"\"\n A decorator to validate a schedule_fn before applying it to a fusion.\n\n Args:\n schedule_fn: The function to apply the scheduler\n \"\"\"\n # List of all scheduler heuristics for testing\n # NOTE We cannot iterate pybind11 enum directly, so we extract the entries here.\n all_scheduler_heuristics = [\n heuristic\n for heuristic, _ in SchedulerType.__entries.values()\n if not SchedulerType.none\n ]\n\n def inner_fn(fusion, selected_heuristic, inputs):\n \"\"\"\n Helper function to validate a schedule_fn.\n\n Args:\n fusion: The Fusion object to schedule\n selected_heuristic: The SchedulerType expected to work\n inputs: Input tensors for the fusion\n \"\"\"\n available_heuristics = schedule.find_compatible_schedulers(fusion, inputs)\n\n # Assume that only a single heuristic is available for fusion\n assert len(available_heuristics) == 1\n\n # Check that only selected heuristic is available as a scheduler\n assert set(available_heuristics) == set([selected_heuristic])\n\n # Double-check with can_schedule\n status, _ = schedule.can_schedule(fusion, selected_heuristic, inputs)\n assert status\n\n # Check that the other schedulers are not compatible with this fusion\n assert all(\n [\n not schedule.can_schedule(fusion, h, inputs)[0]\n for h in all_scheduler_heuristics\n if h is not selected_heuristic\n ]\n )\n return schedule_fn(fusion, selected_heuristic, inputs)\n\n return inner_fn\n\n\ndef test_tutorial_memcpy():\n # First, we define a fusion. A common pattern is:\n # - Declare a Fusion, which works as a container of expressions using\n # with context manager.\n # - Setup inputs. fd.define_tensor can be used to manually create tensors.\n # fd.from_pytorch will create a TensorView given a pytorch tensor. Fusion\n # registration is automatic.\n # - Define operations with the registered inputs.\n # For supported operations, run:\n # >>> import nvfuser_direct\n # >>> fd = nvfuser_direct.FusionDefinition()\n # >>> help(fd.ops)\n # - Most of operations that take tensors as inputs produce tensors\n # as outputs, which can then be used as inputs to another\n # operations.\n # - Final outputs should be set as fusion outputs with fd.add_output\n\n with FusionDefinition() as fd:","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_memcpy","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_memcpy#L86-L143","kind":"function","name":"test_tutorial_memcpy","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":86,"end_line":143,"context_start_line":66,"context_end_line":163,"code":" # Check that only selected heuristic is available as a scheduler\n assert set(available_heuristics) == set([selected_heuristic])\n\n # Double-check with can_schedule\n status, _ = schedule.can_schedule(fusion, selected_heuristic, inputs)\n assert status\n\n # Check that the other schedulers are not compatible with this fusion\n assert all(\n [\n not schedule.can_schedule(fusion, h, inputs)[0]\n for h in all_scheduler_heuristics\n if h is not selected_heuristic\n ]\n )\n return schedule_fn(fusion, selected_heuristic, inputs)\n\n return inner_fn\n\n\ndef test_tutorial_memcpy():\n # First, we define a fusion. A common pattern is:\n # - Declare a Fusion, which works as a container of expressions using\n # with context manager.\n # - Setup inputs. fd.define_tensor can be used to manually create tensors.\n # fd.from_pytorch will create a TensorView given a pytorch tensor. Fusion\n # registration is automatic.\n # - Define operations with the registered inputs.\n # For supported operations, run:\n # >>> import nvfuser_direct\n # >>> fd = nvfuser_direct.FusionDefinition()\n # >>> help(fd.ops)\n # - Most of operations that take tensors as inputs produce tensors\n # as outputs, which can then be used as inputs to another\n # operations.\n # - Final outputs should be set as fusion outputs with fd.add_output\n\n with FusionDefinition() as fd:\n # Create a 2D tensor of type float. It's \"symbolic\" as we do not\n # assume any specific shape except for that it's 2D.\n tv0 = fd.define_tensor(shape=[-1, -1])\n\n # Just create a copy\n tv1 = fd.ops.set(tv0)\n fd.add_output(tv1)\n\n if verbose_:\n # Here's some common ways to inspect the fusion. These are not\n # necessary for running the fusion but should provide helpful\n # information for understanding how fusions are transformed.\n\n # Print a concise representation of the fusion exprssions\n print(fd.fusion.print_math())\n\n # Generate and print a CUDA kernel. Notice that at this point the\n # genereated code is just a sequential kernel as we have not\n # scheduled the fusion yet, but it should be a valid CUDA kernel\n print(fd.fusion.print_kernel())\n\n # Next, try running the fusion. First, we need to set up a sample\n # input tensor. Here, we create a 32x32 tensor initialized with\n # random float values.\n\n t0 = torch.randn(32, 32, dtype=torch.float, device=\"cuda:0\")\n\n # Next, lower the Fusion to Kernel, generate CUDA kernel source and then\n # compile it with nvrtc. After compilation, KernelExecutor now has a\n # compiled kernel, which can be executed as:\n outputs = fd.manual_execute([t0])\n\n # Note that this run is done using just one thread, which will be\n # corrected below.\n\n # To validate the output, we can just assert that the output is\n # equal to the input as this is just a copy fusion. More commonly,\n # though, fd.validate is used to validate outputs while\n # automatically adjusting thresholds of valid deviations.\n assert outputs[0].equal(t0)\n\n\ndef test_tutorial_memcpy_scheduled():\n # test_tutorial_memcpy_scheduled is a continuation from test_tutorial_memcpy\n\n # Instead of just running the fusion as is, we manually schedule it so that\n # it runs in parallel. In this case, we only have one expression, so we\n # just need to schedule tv1.\n\n # tv1 is a 2D tensor. Let its domain be [i0, i1]. We are going transform\n # this 2D domain to a CUDA Grid and Block. Specifically, a grid consisting\n # of multiple thread blocks, each of which containin multiple threads. A\n # common transformation pattern is to merge all of each axis to get a\n # flattened domain, and then split the domain to factor out axes that are\n # parallelized by threads and thread blocks.\n\n # In python, we can only modify the FusionDefinition inside a with context.\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[-1, -1])\n tv1 = fd.ops.set(tv0)","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_memcpy_scheduled","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_memcpy_scheduled#L146-L215","kind":"function","name":"test_tutorial_memcpy_scheduled","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":146,"end_line":215,"context_start_line":126,"context_end_line":235,"code":" # input tensor. Here, we create a 32x32 tensor initialized with\n # random float values.\n\n t0 = torch.randn(32, 32, dtype=torch.float, device=\"cuda:0\")\n\n # Next, lower the Fusion to Kernel, generate CUDA kernel source and then\n # compile it with nvrtc. After compilation, KernelExecutor now has a\n # compiled kernel, which can be executed as:\n outputs = fd.manual_execute([t0])\n\n # Note that this run is done using just one thread, which will be\n # corrected below.\n\n # To validate the output, we can just assert that the output is\n # equal to the input as this is just a copy fusion. More commonly,\n # though, fd.validate is used to validate outputs while\n # automatically adjusting thresholds of valid deviations.\n assert outputs[0].equal(t0)\n\n\ndef test_tutorial_memcpy_scheduled():\n # test_tutorial_memcpy_scheduled is a continuation from test_tutorial_memcpy\n\n # Instead of just running the fusion as is, we manually schedule it so that\n # it runs in parallel. In this case, we only have one expression, so we\n # just need to schedule tv1.\n\n # tv1 is a 2D tensor. Let its domain be [i0, i1]. We are going transform\n # this 2D domain to a CUDA Grid and Block. Specifically, a grid consisting\n # of multiple thread blocks, each of which containin multiple threads. A\n # common transformation pattern is to merge all of each axis to get a\n # flattened domain, and then split the domain to factor out axes that are\n # parallelized by threads and thread blocks.\n\n # In python, we can only modify the FusionDefinition inside a with context.\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[-1, -1])\n tv1 = fd.ops.set(tv0)\n fd.add_output(tv1)\n\n # For example, the current domain of tv1 looks like [i0, i1]. We can\n # merge the two axes by:\n tv1.merge(0, 1)\n\n # This creates a single axis that merges i0 and i1. Its extent is a\n # multiplication of the extents of i0 and i1, so we commonly represent\n # it as [i0 * i1]. It can be also examined with:\n if verbose_:\n print(tv1)\n\n # Next, we factor out a subdomain for threads in each thread block.\n tv1.split(0, 256)\n\n # In this case, the flattened domain is now 2D domain with an inner\n # domain of extent 256 and an outer domain of extent i0*i1/256, so the\n # tensor should now look like [i0*i1/256, 256]. Note that in reality we\n # do ceiling division as i0 * i1 may not be divisible by 256.\n if verbose_:\n print(tv1)\n\n # Now that we have two domains, we can parallelize each domain using\n # IterDomain.parallelize(ParallelType). Specifically, to parallelize the\n # inner domain with threads, we can do:\n tv1.axis(1).parallelize(ParallelType.block_x)\n # Similarly, to paralllize the outer domain with thread blocks:\n tv1.axis(0).parallelize(ParallelType.grid_x)\n # This way, the inner and outer axes are divided by blockDim.x threads\n # and gridDim.x blocks, respectively. Each element in each axis is\n # computed by one thread or one block, so this means that the size of\n # each thread block and a grid must match the size of each domain.\n # blockDim.x and gridDim.x must be 256 and i0*i1/256.\n\n # Now that the fusion is parallelized, it can be examined again.\n if verbose_:\n print(fd.fusion.print_math())\n # Notice that the axes of tv1 are now printed with blockIdx.x and\n # threadIdx.x, which shows they are parallelized by the\n # respective parallel types.\n\n # The CUDA kernel should look very differently as there should be no\n # for-loops.\n print(fd.fusion.print_kernel())\n\n # This time, the kernel is launched with multiple threads and thread\n # blocks. Note that the thread block and grid shapes are inferred from the\n # given inputs. To see how many threads are used, run this test\n # with NVFUSER_DUMP=launch_param\n t0 = torch.randn(32, 32, dtype=torch.float, device=\"cuda:0\")\n outputs = fd.manual_execute([t0])\n assert outputs[0].equal(t0)\n\n\ndef test_tutorial_reduction():\n def fusion_func(fd: FusionDefinition) -> TensorView:\n # Create a 2D tensor\n tv0 = fd.define_tensor(shape=[-1, -1])\n\n # Reduce the second dimension\n tv1 = fd.ops.sum(tv0, dims=[1])\n fd.add_output(tv1)\n\n return tv1\n\n with FusionDefinition() as fd0:\n ref_tv = fusion_func(fd0)\n\n # At this point, nothing is parallelized. The reduction is done by\n # a single thread sequentially.\n\n if verbose_:","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_reduction","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_reduction#L218-L306","kind":"function","name":"test_tutorial_reduction","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":218,"end_line":306,"context_start_line":198,"context_end_line":326,"code":" # Now that the fusion is parallelized, it can be examined again.\n if verbose_:\n print(fd.fusion.print_math())\n # Notice that the axes of tv1 are now printed with blockIdx.x and\n # threadIdx.x, which shows they are parallelized by the\n # respective parallel types.\n\n # The CUDA kernel should look very differently as there should be no\n # for-loops.\n print(fd.fusion.print_kernel())\n\n # This time, the kernel is launched with multiple threads and thread\n # blocks. Note that the thread block and grid shapes are inferred from the\n # given inputs. To see how many threads are used, run this test\n # with NVFUSER_DUMP=launch_param\n t0 = torch.randn(32, 32, dtype=torch.float, device=\"cuda:0\")\n outputs = fd.manual_execute([t0])\n assert outputs[0].equal(t0)\n\n\ndef test_tutorial_reduction():\n def fusion_func(fd: FusionDefinition) -> TensorView:\n # Create a 2D tensor\n tv0 = fd.define_tensor(shape=[-1, -1])\n\n # Reduce the second dimension\n tv1 = fd.ops.sum(tv0, dims=[1])\n fd.add_output(tv1)\n\n return tv1\n\n with FusionDefinition() as fd0:\n ref_tv = fusion_func(fd0)\n\n # At this point, nothing is parallelized. The reduction is done by\n # a single thread sequentially.\n\n if verbose_:\n print(fd0.fusion.print_math())\n print(fd0.fusion.print_kernel())\n\n # Block-parallel reduction\n ref_tv.axis(1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd0.fusion.print_math())\n print(fd0.fusion.print_kernel())\n\n t0 = torch.randn(10, 1024, dtype=torch.float, device=\"cuda:0\")\n ref = t0.sum(dim=1)\n\n fd0.manual_validate([t0], [ref])\n\n # Create another FusionDefinition with same math but different schedule.\n with FusionDefinition() as fd1:\n ref_tv = fusion_func(fd1)\n\n # Next, use the same fusion but parallelize the reduction with\n # thread blocks\n ref_tv.axis(1).parallelize(ParallelType.grid_x)\n\n if verbose_:\n print(fd1.fusion.print_math())\n print(fd1.fusion.print_kernel())\n\n fd1.manual_validate([t0], [ref])\n\n # Create another FusionDefinition with same math but different schedule.\n with FusionDefinition() as fd2:\n ref_tv = fusion_func(fd2)\n\n # We can also parallelize the first axis as well. For example,\n # here's how threadIdx.x is used for the reduction and threadIdx.y\n # is used for the outer non-reduction domain\n ref_tv.axis(0).parallelize(ParallelType.block_y)\n ref_tv.axis(1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd2.fusion.print_math())\n print(fd2.fusion.print_kernel())\n\n # Running this fusion, however, should fail as it would require thread\n # blocks of shape 1024x10, i.e., the same shape as the input tensor, which\n # is too large in CUDA.\n with pytest.raises(RuntimeError):\n fd2.manual_validate([t0], [ref])\n\n # Try again with a smaller input. This should launch a kernel\n # with thread blocks of shape 32x10\n t1 = torch.randn(10, 32, dtype=torch.float, device=\"cuda:0\")\n fd2.manual_validate([t1], [t1.sum(dim=1)])\n\n # Create another FusionDefinition with same math but different schedule.\n with FusionDefinition() as fd3:\n ref_tv = fusion_func(fd3)\n\n # We can of course mix BIDx and TIDx.\n ref_tv.axis(0).parallelize(ParallelType.grid_x)\n ref_tv.axis(1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd3.fusion.print_math())\n print(fd3.fusion.print_kernel())\n\n # The original input should not fail in this case. The kernel will be\n # launched with 10 thread blocks, each of which has 1024 threads. Try\n # running this test with NVFUSER_DUMP=launch_param to see the launch\n # configuration of each kernel lauch\n fd3.manual_validate([t0], [ref])\n\n\ndef test_tutorial_reduction_rfactor():\n # Just a very simple reduction of 1D tensor\n def fusion_func(fd: FusionDefinition) -> TensorView:\n tv0 = fd.define_tensor(shape=[-1])\n tv1 = fd.ops.sum(tv0, dims=[0])\n fd.add_output(tv1)\n return tv1\n\n # Create separate fusions because of multiple schedules\n with FusionDefinition() as fd0:\n tv1 = fusion_func(fd0)\n\n # A common pattern of reductions in CUDA involves multiple steps of\n # reductions, where the first step is a per-thread local reduction,\n # followed by a block reduction of the per-thread partial results,\n # and also potentially followed by a grid reduction of the\n # per-block partial results. Here's an example with a two-step\n # reduction:","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_reduction_rfactor","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_reduction_rfactor#L309-L436","kind":"function","name":"test_tutorial_reduction_rfactor","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":309,"end_line":436,"context_start_line":289,"context_end_line":456,"code":"\n # Create another FusionDefinition with same math but different schedule.\n with FusionDefinition() as fd3:\n ref_tv = fusion_func(fd3)\n\n # We can of course mix BIDx and TIDx.\n ref_tv.axis(0).parallelize(ParallelType.grid_x)\n ref_tv.axis(1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd3.fusion.print_math())\n print(fd3.fusion.print_kernel())\n\n # The original input should not fail in this case. The kernel will be\n # launched with 10 thread blocks, each of which has 1024 threads. Try\n # running this test with NVFUSER_DUMP=launch_param to see the launch\n # configuration of each kernel lauch\n fd3.manual_validate([t0], [ref])\n\n\ndef test_tutorial_reduction_rfactor():\n # Just a very simple reduction of 1D tensor\n def fusion_func(fd: FusionDefinition) -> TensorView:\n tv0 = fd.define_tensor(shape=[-1])\n tv1 = fd.ops.sum(tv0, dims=[0])\n fd.add_output(tv1)\n return tv1\n\n # Create separate fusions because of multiple schedules\n with FusionDefinition() as fd0:\n tv1 = fusion_func(fd0)\n\n # A common pattern of reductions in CUDA involves multiple steps of\n # reductions, where the first step is a per-thread local reduction,\n # followed by a block reduction of the per-thread partial results,\n # and also potentially followed by a grid reduction of the\n # per-block partial results. Here's an example with a two-step\n # reduction:\n #\n # // Step 1: Per-thread reduction\n # float partial_result = 0;\n # for (int i = threadIdx.x; i += blockDim.x; i < N) {\n # partial_result += input[i];\n # }\n #\n # // Step 2: Accumulation within each thread block\n # __shared__ float shared_buf[blockDim.x];\n # shared_buf[threadIdx.x] = partial_result;\n # __syncthreads();\n # float final_result = 0;\n # // Accumulation of the partila result in a naive sequntial way.\n # if (threadIdx.x == 0) {\n # for (int i = 0; i < blockDim.x; ++i) {\n # final_result += shared_buf[i];\n # }\n # }\n\n # To reproduce the multi-step reduction pattern in nvFuser, a fusion\n # transformation called reduction rfactor is used. The basic idea is to\n # split a reduction domain such that each of the output domains of the\n # split is separately reduced. For example, tv1 can be transformed from\n # a 2D tensor to a 3D tensor as follows:\n\n # tv0: [i0]\n # tv1: [r1]\n tv1.split(0, 1024)\n # tv1: [r1/1024, r1024]\n\n # Both of the two inner domains are reduction domains, and we first\n # want to reduce the second domain, i.e., r1/1024, by each thread\n # independently, and then reduce the other reduction domain by a\n # block reduction. This can be done as follows:\n tv2 = tv1.rfactor([0])\n\n # The fusion math should now look like:\n # tv0: root = logical = [i{i0}]\n # tv2 = reduction(tv0): root = [r{i0}], logical = [r{i0/1024}, i{1024}]\n # tv1 = reduction(tv2): root = logical = [r{1024}]\n if verbose_:\n print(fd0.fusion.print_math())\n\n # Notice that the reduction operation is now split into two operations,\n # where the first one takes care of the first domain, and the second one\n # finishes up the remaining domain. The final values of tv1 is not\n # altered, but its computation is changed. (More strictly, since\n # floating-point addition is not associative, the final result will not\n # be exactly the same due to rounding errors)\n\n # To realize the parallelization as we sketched above, we can\n # use TIDx for both of tv1 and tv2 as follows:\n tv1.axis(0).parallelize(ParallelType.block_x)\n tv2.axis(1).parallelize(ParallelType.block_x)\n\n # At this point, tv2 is a TIDx-parallelized operation of multiple\n # independent reductions. There will be 1024 threads, each of which\n # reduces the first axis of size r1/1024. tv1 is also parallelized by\n # TIDx, but unlike tv2 the reduction domain is parallelized, so it\n # becomes a block-reduction operation.\n if verbose_:\n print(fd0.fusion.print_math())\n print(fd0.fusion.print_kernel())\n\n # Let's run the scheduled fusion\n t0 = torch.randn(10000, dtype=torch.float, device=\"cuda:0\")\n ref = t0.sum(dim=0)\n fd0.manual_validate([t0], [ref])\n\n # We can further increase the parallelism by splitting the reduction domain\n # into three\n with FusionDefinition() as fd1:\n tv1 = fusion_func(fd1)\n\n # First, split for TIDx of 1024 threads\n tv1.split(0, 1024)\n # Next, split for BIDx of 100 thread blocks\n tv1.split(0, 100)\n # tv1: [r0/1024/100, r100, r1024]\n\n # Factoring out per-thread reduction\n tv2 = tv1.rfactor([1])\n # tv2: [i0/1024/100, r100, i1024]\n # tv1: [r0/1024/100, r1024]\n\n # Factoring out block reduction\n tv3 = tv1.rfactor([1])\n # tv2: [i0/1024/100, r100, i1024]\n # tv3: [i0/1024/100, r1024]\n # tv1: [r0/1024/100]\n\n # Parallelize each operation as follows\n # tv2: [bidx(i0/1024/100), r100, tidx(i1024)]\n # tv3: [bidx(i0/1024/100), tidx(r1024)]\n # tv1: [bidx(r0/1024/100)]\n tv2.axis(0).parallelize(ParallelType.grid_x)\n tv3.axis(0).parallelize(ParallelType.grid_x)\n tv1.axis(0).parallelize(ParallelType.grid_x)\n tv2.axis(2).parallelize(ParallelType.block_x)\n tv3.axis(1).parallelize(ParallelType.block_x)\n # Note that this could be also done more easily using\n # scheduler_utils::parallelizeAllLike.\n\n if verbose_:\n print(fd1.fusion.print_math())\n print(fd1.fusion.print_kernel())\n\n t1 = torch.randn(10000000, dtype=torch.float, device=\"cuda:0\")\n ref1 = t1.sum(dim=0)\n fd1.manual_validate([t1], [ref1])\n\n\ndef test_tutorial_reshape():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[4, 8])\n\n # Shape of tv0 is assumed to be [4, 8], which is then reshaped to [32]\n tv1 = fd.ops.reshape(tv0, [32])\n fd.add_output(tv1)\n\n if verbose_:\n # Notice that tv1 has root and logical domains. The root domain has two\n # IterDomains, whereas the logical domain consists of a single\n # IterDomain that is an output of a merge operation of the two root\n # IterDomains.\n print(fd.fusion.print_math())\n\n # Check if the tv1 domains are generated as expected\n assert tv1.has_root()\n assert len(tv1.get_logical_domain()) == 1","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_reshape","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_reshape#L439-L574","kind":"function","name":"test_tutorial_reshape","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":439,"end_line":574,"context_start_line":419,"context_end_line":594,"code":" # tv2: [bidx(i0/1024/100), r100, tidx(i1024)]\n # tv3: [bidx(i0/1024/100), tidx(r1024)]\n # tv1: [bidx(r0/1024/100)]\n tv2.axis(0).parallelize(ParallelType.grid_x)\n tv3.axis(0).parallelize(ParallelType.grid_x)\n tv1.axis(0).parallelize(ParallelType.grid_x)\n tv2.axis(2).parallelize(ParallelType.block_x)\n tv3.axis(1).parallelize(ParallelType.block_x)\n # Note that this could be also done more easily using\n # scheduler_utils::parallelizeAllLike.\n\n if verbose_:\n print(fd1.fusion.print_math())\n print(fd1.fusion.print_kernel())\n\n t1 = torch.randn(10000000, dtype=torch.float, device=\"cuda:0\")\n ref1 = t1.sum(dim=0)\n fd1.manual_validate([t1], [ref1])\n\n\ndef test_tutorial_reshape():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[4, 8])\n\n # Shape of tv0 is assumed to be [4, 8], which is then reshaped to [32]\n tv1 = fd.ops.reshape(tv0, [32])\n fd.add_output(tv1)\n\n if verbose_:\n # Notice that tv1 has root and logical domains. The root domain has two\n # IterDomains, whereas the logical domain consists of a single\n # IterDomain that is an output of a merge operation of the two root\n # IterDomains.\n print(fd.fusion.print_math())\n\n # Check if the tv1 domains are generated as expected\n assert tv1.has_root()\n assert len(tv1.get_logical_domain()) == 1\n # In python, use type() function to check an object's class.\n # In CPP, use isA template function.\n tv1_merge = tv1.get_logical_domain()[0].definition()\n assert type(tv1_merge) is Merge\n assert tv1_merge.inner() == tv1.get_root_domain()[1]\n assert tv1_merge.outer() == tv1.get_root_domain()[0]\n\n # Reshape example with broadcast domains\n with FusionDefinition() as fd1:\n # Create a 3D tensor with a broadcast domain\n tv0 = fd1.define_tensor(shape=[1, 2, 3])\n\n # tv0 is first squeezed and then reshaped and unsqueezed\n tv1 = fd1.ops.reshape(tv0, [3, 2, 1])\n fd1.add_output(tv1)\n\n if verbose_:\n print(fd1.fusion.print_math())\n\n # The fusion should look like:\n #\n # tv1 = unsqueeze(reshape(squeeze(tv0)));\n assert type(tv1.definition()) is BroadcastOp\n reshape_output = tv1.definition().input(0)\n assert type(reshape_output.definition()) is ReshapeOp\n squeeze_output = reshape_output.definition().input(0)\n assert type(squeeze_output.definition()) is SqueezeOp\n\n assert reshape_output.has_root()\n assert len(reshape_output.get_logical_domain()) == 2\n assert type(reshape_output.get_logical_domain()[0].definition()) is Split\n reshape_output_split = reshape_output.get_logical_domain()[0].definition()\n assert reshape_output_split.outer() == reshape_output.get_logical_domain()[0]\n assert reshape_output_split.inner() == reshape_output.get_logical_domain()[1]\n assert type(reshape_output_split.input(0).definition()) is Merge\n reshape_output_merge = reshape_output_split.input(0).definition()\n assert reshape_output_merge.outer() == reshape_output.get_root_domain()[0]\n assert reshape_output_merge.inner() == reshape_output.get_root_domain()[1]\n\n # So far, the fusion has transformations as part of its definition. It can\n # be further extended with scheduling transformations.\n reshape_output.merge(0, 1)\n reshape_output.split(0, 128)\n\n assert type(reshape_output.get_loop_domain()[0].definition()) is Split\n assert (\n reshape_output.get_loop_domain()[0].definition().inner()\n == reshape_output.get_loop_domain()[1]\n )\n assert (\n type(reshape_output.get_loop_domain()[0].definition().input(0).definition())\n == Merge\n )\n assert (\n reshape_output.get_loop_domain()[0]\n .definition()\n .input(0)\n .definition()\n .outer()\n == reshape_output.get_logical_domain()[0]\n )\n assert (\n reshape_output.get_loop_domain()[0]\n .definition()\n .input(0)\n .definition()\n .inner()\n == reshape_output.get_logical_domain()[1]\n )\n\n # Here's how we propagate the transformations of reshape_output to all\n # other tensors in the fusion\n fd.sched.transform_like(reshape_output)\n\n # Now, all tensors, including those before the reshape op, should be\n # transformed to 2D tensors with an inner domain of extent 128.\n if verbose_:\n print(fd.fusion.print_math())\n\n # Notice that all transformations of the reshape tensor, including both the\n # reshape and scheduling transformations, are propagated. For example,\n # squeeze_output should have the merge and split for the reshape, followed\n # by another merge and split for scheduling. Specifically:\n #\n # Root domain: [b0, i1, i2]\n # merge(1, 2) -> [b0, i1*i2]\n # outer split(1, 3) -> [b0, 3, i1*i2/3]\n # merge(1, 2) -> [b0, 3*i1*i2/3]\n # split(1, 128) -> [b0, 3*i1*i2/3/128, 128]\n assert type(squeeze_output.get_loop_domain()[0].definition()) is Split\n squeeze_output_second_split = squeeze_output.get_loop_domain()[0].definition()\n assert (\n squeeze_output_second_split.outer() == squeeze_output.get_loop_domain()[0]\n )\n assert (\n squeeze_output_second_split.inner() == squeeze_output.get_loop_domain()[1]\n )\n\n assert type(squeeze_output_second_split.input(0).definition()) is Merge\n squeeze_output_second_merge = squeeze_output_second_split.input(0).definition()\n\n assert type(squeeze_output_second_merge.outer().definition()) is Split\n squeeze_output_first_split = squeeze_output_second_merge.outer().definition()\n assert squeeze_output_first_split.outer() == squeeze_output_second_merge.outer()\n assert squeeze_output_first_split.inner() == squeeze_output_second_merge.inner()\n\n assert type(squeeze_output_first_split.input(0).definition()) is Merge\n squeeze_output_first_merge = squeeze_output_first_split.input(0).definition()\n assert (\n squeeze_output_first_merge.outer() == squeeze_output.get_logical_domain()[0]\n )\n assert (\n squeeze_output_first_merge.inner() == squeeze_output.get_logical_domain()[1]\n )\n\n # Note that all the transformations of squeeze_output are scheduling\n # transformations, thus it should not have a root domain\n assert not squeeze_output.has_root()\n\n\ndef test_tutorial_id_model_reshape_analysis():\n \"\"\"\n Demonstration of using IdModel for analyzing equivalence of reshape ops\n \"\"\"\n with FusionDefinition() as fd:\n # Use the static reshape to avoid reshape concretization.\n tv0 = fd.define_tensor(shape=[10, 20])\n tv1 = fd.define_tensor(shape=[10, 20])\n\n # While the reshape operations are equivalent, we do not know if the two\n # inputs are the same. There is not an operation allowing us to infer\n # equivalence. e.g., tv0 + tv1.\n tv2 = fd.ops.reshape(tv0, [20, 10])\n tv3 = fd.ops.reshape(tv1, [20, 10])\n fd.add_output(tv2)\n fd.add_output(tv3)\n\n id_model = idm.IdModel(fd.fusion)","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_id_model_reshape_analysis","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_id_model_reshape_analysis#L577-L636","kind":"function","name":"test_tutorial_id_model_reshape_analysis","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":577,"end_line":636,"context_start_line":557,"context_end_line":656,"code":"\n assert type(squeeze_output_second_merge.outer().definition()) is Split\n squeeze_output_first_split = squeeze_output_second_merge.outer().definition()\n assert squeeze_output_first_split.outer() == squeeze_output_second_merge.outer()\n assert squeeze_output_first_split.inner() == squeeze_output_second_merge.inner()\n\n assert type(squeeze_output_first_split.input(0).definition()) is Merge\n squeeze_output_first_merge = squeeze_output_first_split.input(0).definition()\n assert (\n squeeze_output_first_merge.outer() == squeeze_output.get_logical_domain()[0]\n )\n assert (\n squeeze_output_first_merge.inner() == squeeze_output.get_logical_domain()[1]\n )\n\n # Note that all the transformations of squeeze_output are scheduling\n # transformations, thus it should not have a root domain\n assert not squeeze_output.has_root()\n\n\ndef test_tutorial_id_model_reshape_analysis():\n \"\"\"\n Demonstration of using IdModel for analyzing equivalence of reshape ops\n \"\"\"\n with FusionDefinition() as fd:\n # Use the static reshape to avoid reshape concretization.\n tv0 = fd.define_tensor(shape=[10, 20])\n tv1 = fd.define_tensor(shape=[10, 20])\n\n # While the reshape operations are equivalent, we do not know if the two\n # inputs are the same. There is not an operation allowing us to infer\n # equivalence. e.g., tv0 + tv1.\n tv2 = fd.ops.reshape(tv0, [20, 10])\n tv3 = fd.ops.reshape(tv1, [20, 10])\n fd.add_output(tv2)\n fd.add_output(tv3)\n\n id_model = idm.IdModel(fd.fusion)\n exact_graph = id_model.maybe_build_graph(IdMappingMode.exact)\n\n if verbose_:\n print(id_model)\n print(exact_graph)\n print(exact_graph.disjoint_val_sets())\n\n # As mentioned above, we do not know any relationship between tv0 and tv1.\n # They should not be mapped in exact graph.\n assert len(tv0.get_logical_domain()) == len(tv1.get_logical_domain())\n for tv0_id, tv1_id in zip(tv0.get_logical_domain(), tv1.get_logical_domain()):\n assert not exact_graph.disjoint_val_sets().strict_are_mapped(tv0_id, tv1_id)\n\n # Thus, the outputs of the reshape ops are not mapped either\n assert len(tv2.get_loop_domain()) == len(tv3.get_loop_domain())\n for tv2_id, tv3_id in zip(tv2.get_loop_domain(), tv3.get_loop_domain()):\n assert not exact_graph.disjoint_val_sets().strict_are_mapped(tv2_id, tv3_id)\n\n # Now, suppose we can say the inputs are exactly mapped. We can manually\n # add mappings:\n for tv0_id, tv1_id in zip(tv0.get_logical_domain(), tv1.get_logical_domain()):\n exact_graph.map_vals(tv0_id, tv1_id)\n\n # Now, tv2 and tv3 should be fully mapped, including their root,\n # intermediate and loop domains.\n\n # Check the root domains.\n assert len(tv2.get_root_domain()) == len(tv3.get_root_domain())\n for tv2_id, tv3_id in zip(tv2.get_root_domain(), tv3.get_root_domain()):\n assert exact_graph.disjoint_val_sets().strict_are_mapped(tv2_id, tv3_id)\n\n # The reshape consists of a merge and split. The output of the merge should\n # be mapped as well\n assert exact_graph.disjoint_val_sets().strict_are_mapped(\n tv2.get_root_domain()[0].uses()[0].output(0),\n tv3.get_root_domain()[0].uses()[0].output(0),\n )\n\n # The next operation is split. Its outputs, which are the loop domains,\n # should be mapped too.\n for tv2_id, tv3_id in zip(tv2.get_loop_domain(), tv3.get_loop_domain()):\n assert exact_graph.disjoint_val_sets().strict_are_mapped(tv2_id, tv3_id)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example1(nvfuser_direct_test):\n \"\"\"\n This tutorial uses copy kernels to demonstrate how to schedule TMA.\n Please note that this is not a guide on how to use TMA to achieve SOL.\n Instead, it is a demonstration on the degree of freedoms we have in a\n TMA schedule and how a schedule is translated into generated code in the\n kernel. I also want the readers to focus on the schedule of TMA. The\n other parts of the kernel that is scheduled is not important here.\n Indeed, I picked a random, valid schedule. For the example about TMA\n load, please focus on the schedule of the shared memory tensor. For the\n example about TMA store, please focus on the allocation domain of the\n shared memory tensor and the fusion output.\n \"\"\"\n\n # In this example, we treat the fusion as 1D, which is similar to how we","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_basic_tma_example1","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_basic_tma_example1#L642-L725","kind":"function","name":"test_tutorial_basic_tma_example1","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":642,"end_line":725,"context_start_line":622,"context_end_line":745,"code":" assert len(tv2.get_root_domain()) == len(tv3.get_root_domain())\n for tv2_id, tv3_id in zip(tv2.get_root_domain(), tv3.get_root_domain()):\n assert exact_graph.disjoint_val_sets().strict_are_mapped(tv2_id, tv3_id)\n\n # The reshape consists of a merge and split. The output of the merge should\n # be mapped as well\n assert exact_graph.disjoint_val_sets().strict_are_mapped(\n tv2.get_root_domain()[0].uses()[0].output(0),\n tv3.get_root_domain()[0].uses()[0].output(0),\n )\n\n # The next operation is split. Its outputs, which are the loop domains,\n # should be mapped too.\n for tv2_id, tv3_id in zip(tv2.get_loop_domain(), tv3.get_loop_domain()):\n assert exact_graph.disjoint_val_sets().strict_are_mapped(tv2_id, tv3_id)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example1(nvfuser_direct_test):\n \"\"\"\n This tutorial uses copy kernels to demonstrate how to schedule TMA.\n Please note that this is not a guide on how to use TMA to achieve SOL.\n Instead, it is a demonstration on the degree of freedoms we have in a\n TMA schedule and how a schedule is translated into generated code in the\n kernel. I also want the readers to focus on the schedule of TMA. The\n other parts of the kernel that is scheduled is not important here.\n Indeed, I picked a random, valid schedule. For the example about TMA\n load, please focus on the schedule of the shared memory tensor. For the\n example about TMA store, please focus on the allocation domain of the\n shared memory tensor and the fusion output.\n \"\"\"\n\n # In this example, we treat the fusion as 1D, which is similar to how we\n # generally schedule pointwise fusions. We use a single 1D TMA instruction to\n # load the entire CTA tile to shared memory.\n # CTA tile size = TMA tile size = 256\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = input.cache_after(LoadStoreOpType.tma)\n smem_cache.set_memory_type(MemoryType.shared)\n\n # For TMA load, both the shared memory layout and the loop nest and\n # parallelization of TMA are specified by the consumer: smem_cache\n\n # Step 1: define TMA domain\n # We want to treat the entire tensor as 1D so define the TMA domain as\n # [I0*I1*I2]\n smem_cache.merge(0, 1)\n smem_cache.merge(0, 1)\n # Note that the TMA domain only exists in people's mind, there is no need to\n # set anything here.\n\n # Step 2: define box\n smem_cache.split(0, 256)\n # [I0*I1*I2/256, 256]\n # partitioned IterDomain: I0*I1*I2\n # coordinate IterDomain: I0*I1*I2/256\n # box IterDomain: 256\n\n # Step 3: define tile\n # We use dense tile here, so tile == box. Nothing to do here.\n\n # Step 4: schedule the shared memory tensor\n # By default, the allocation domain is the logical domain, which is already\n # in good shape for this case.\n\n # Step 5: schedule the consumer tensor\n smem_cache.axis(0).parallelize(ParallelType.grid_x)\n smem_cache.axis(1).parallelize(ParallelType.tma)\n # [BIDx, TMA]\n\n # Schedule the smem->gmem part\n output.merge(0, 1)\n output.merge(0, 1)\n output.split(0, 256)\n output.axis(0).parallelize(ParallelType.grid_x)\n output.axis(1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n # TMA will be generated like:\n # Note that the coordinate is in number of items, smem address is in\n # bytes\n #\n # if (threadIdx.x == 0) {\n # Hopper::cpAsyncBulkTensorTileG2S(\n # coordinate = {256 * blockIdx.x},\n # smem_addr = toSmem(T2));\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example2(nvfuser_direct_test):\n \"\"\"\n Example 2:\n Similar to example 1, we treat the fusion as 1D and uses 1D TMA to load\n data to shared memory. But this time, instead of using 1 TMA instruction\n to load the entire CTA tile, we use 4 TMA instructions. We use a for loop\n to launch these 4 instructions\n CTA tile size = 4 * TMA tile size = 1024\n \"\"\"\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = input.cache_after(LoadStoreOpType.tma)","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_basic_tma_example2","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_basic_tma_example2#L731-L810","kind":"function","name":"test_tutorial_basic_tma_example2","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":731,"end_line":810,"context_start_line":711,"context_end_line":830,"code":" #\n # if (threadIdx.x == 0) {\n # Hopper::cpAsyncBulkTensorTileG2S(\n # coordinate = {256 * blockIdx.x},\n # smem_addr = toSmem(T2));\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example2(nvfuser_direct_test):\n \"\"\"\n Example 2:\n Similar to example 1, we treat the fusion as 1D and uses 1D TMA to load\n data to shared memory. But this time, instead of using 1 TMA instruction\n to load the entire CTA tile, we use 4 TMA instructions. We use a for loop\n to launch these 4 instructions\n CTA tile size = 4 * TMA tile size = 1024\n \"\"\"\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = input.cache_after(LoadStoreOpType.tma)\n smem_cache.set_memory_type(MemoryType.shared)\n\n # For TMA load, both the shared memory layout and the loop nest and\n # parallelization of TMA are specified by the consumer: smem_cache\n\n # Step 1: define TMA domain\n # We want to treat the entire tensor as 1D, so define the TMA domain as\n # [I0*I1*I2]\n smem_cache.merge(0, 1)\n smem_cache.merge(0, 1)\n # Note that the TMA domain only exist in people's mind, there is no need to\n # set anything here.\n\n # Step 2: define box\n smem_cache.split(0, 256)\n # [I0*I1*I2/256, 256]\n # partitioned IterDomain: I0*I1*I2\n # coordinate IterDomain: I0*I1*I2/256\n # box IterDomain: 256\n\n # Step 3: define tile\n # We use dense tile here, so tile == box. Nothing to do here.\n\n # Step 4: schedule the shared memory tensor\n # By default, the allocation domain is the logical domain, which is already\n # in good shape for this case.\n\n # Step 5: schedule the consumer tensor\n smem_cache.split(0, 4)\n # [I0*I1*I2/256/4, 4, 256]\n smem_cache.axis(0).parallelize(ParallelType.grid_x)\n smem_cache.axis(2).parallelize(ParallelType.tma)\n # [BIDx, Serial, TMA]\n\n # Schedule the smem->gmem part\n output.merge(0, 1)\n output.merge(0, 1)\n output.split(0, 256)\n output.split(0, 4)\n output.axis(0).parallelize(ParallelType.grid_x)\n output.axis(2).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n # TMA will be generated like:\n # Note that the coordinate is in number of items, smem address is in\n # bytes\n #\n # for (nvfuser_index_t i8 = 0; i8 < 4; ++i8) {\n # if (threadIdx.x == 0) {\n # Hopper::cpAsyncBulkTensorTileG2S(\n # coordinate = {1024 * blockIdx.x + 256 * i8},\n # smem_addr = (toSmem(T2) + 1024 * i8));\n # }\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example3(nvfuser_direct_test):\n \"\"\"\n Example 3:\n Similar to example 2, we treat the fusion as 1D and use 1D TMA to load data\n to shared memory. 4 TMA instructions are used to load the entire CTA tile.\n However, instead of using a for loop to launch these 4 instructions, we\n parallelize these 4 instructions to TIDx.\n CTA tile size = 4 * TMA tile size = 1024\n \"\"\"\n\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_basic_tma_example3","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_basic_tma_example3#L816-L895","kind":"function","name":"test_tutorial_basic_tma_example3","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":816,"end_line":895,"context_start_line":796,"context_end_line":915,"code":" # if (threadIdx.x == 0) {\n # Hopper::cpAsyncBulkTensorTileG2S(\n # coordinate = {1024 * blockIdx.x + 256 * i8},\n # smem_addr = (toSmem(T2) + 1024 * i8));\n # }\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example3(nvfuser_direct_test):\n \"\"\"\n Example 3:\n Similar to example 2, we treat the fusion as 1D and use 1D TMA to load data\n to shared memory. 4 TMA instructions are used to load the entire CTA tile.\n However, instead of using a for loop to launch these 4 instructions, we\n parallelize these 4 instructions to TIDx.\n CTA tile size = 4 * TMA tile size = 1024\n \"\"\"\n\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = input.cache_after(LoadStoreOpType.tma)\n smem_cache.set_memory_type(MemoryType.shared)\n\n # For TMA load, both the shared memory layout and the loop nest and\n # parallelization of TMA are specified by the consumer: smem_cache\n\n # Step 1: define TMA domain\n # Because we want to treat the entire tensor as 1D, we define the TMA\n # domain as [I0*I1*I2]\n smem_cache.merge(0, 1)\n smem_cache.merge(0, 1)\n # Note that the TMA domain only exist in people's mind, there is no need to\n # set anything here.\n\n # Step 2: define box\n smem_cache.split(0, 256)\n # [I0*I1*I2/256, 256]\n # partitioned IterDomain: I0*I1*I2\n # coordinate IterDomain: I0*I1*I2/256\n # box IterDomain: 256\n\n # Step 3: define tile\n # We use dense tile here, so tile == box. Nothing to do here.\n\n # Step 4: schedule the shared memory tensor\n # By default, the allocation domain is the logical domain, which is already\n # in good shape for this case.\n\n # Step 5: schedule the consumer tensor\n smem_cache.split(0, 4)\n # [I0*I1*I2/256/4, 4, 256]\n smem_cache.axis(0).parallelize(ParallelType.grid_x)\n smem_cache.axis(1).parallelize(ParallelType.block_x)\n smem_cache.axis(2).parallelize(ParallelType.tma)\n # [BIDx, TIDx, TMA]\n\n # Schedule the smem->gmem part\n output.merge(0, 1)\n output.merge(0, 1)\n output.split(0, 256)\n output.split(0, 4)\n output.axis(0).parallelize(ParallelType.grid_x)\n output.axis(2).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n # TMA will be generated like:\n # Note that the coordinate is in number of items, smem address is in\n # bytes\n #\n # if (threadIdx.x < 4) {\n # Hopper::cpAsyncBulkTensorTileG2S(\n # coordinate = {1024 * blockIdx.x + 256 * threadIdx.x},\n # smem_addr = (toSmem(T2) + 1024 * threadIdx.x));\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example4(nvfuser_direct_test):\n \"\"\"\n Example 4: Similar to example 3, except that we are using TMA for store\n instead of load.\n \"\"\"\n\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = output.cache_before(LoadStoreOpType.tma)\n smem_cache.set_memory_type(MemoryType.shared)\n\n # For TMA store, the loop nest and parallelization is specified in the","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_basic_tma_example4","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_basic_tma_example4#L901-L977","kind":"function","name":"test_tutorial_basic_tma_example4","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":901,"end_line":977,"context_start_line":881,"context_end_line":997,"code":" #\n # if (threadIdx.x < 4) {\n # Hopper::cpAsyncBulkTensorTileG2S(\n # coordinate = {1024 * blockIdx.x + 256 * threadIdx.x},\n # smem_addr = (toSmem(T2) + 1024 * threadIdx.x));\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example4(nvfuser_direct_test):\n \"\"\"\n Example 4: Similar to example 3, except that we are using TMA for store\n instead of load.\n \"\"\"\n\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = output.cache_before(LoadStoreOpType.tma)\n smem_cache.set_memory_type(MemoryType.shared)\n\n # For TMA store, the loop nest and parallelization is specified in the\n # consumer `output`, and the shared memory layout is specified in the\n # allocation dimain of `smem_cache`.\n\n # Step 1: define TMA domain\n # Because we want to treat the entire tensor as 1D, we define the TMA\n # domain as [I0*I1*I2]\n output.merge(0, 1)\n output.merge(0, 1)\n # Note that the TMA domain only exist in people's mind, there is no need to\n # set anything here.\n\n # Step 2: define box\n output.split(0, 256)\n # [I0*I1*I2/256, 256]\n # partitioned IterDomain: I0*I1*I2\n # coordinate IterDomain: I0*I1*I2/256\n # box IterDomain: 256\n\n # Step 3: define tile\n # We use dense tile here, so tile == box. Nothing to do here.\n\n # Step 4: schedule the shared memory tensor\n # By default, the allocation domain is the logical domain, which is already\n # in good shape for this case.\n\n # Step 5: schedule the consumer tensor\n output.split(0, 4)\n # [I0*I1*I2/256/4, 4, 256]\n output.axis(0).parallelize(ParallelType.grid_x)\n output.axis(1).parallelize(ParallelType.block_x)\n output.axis(2).parallelize(ParallelType.tma)\n # [BIDx, TIDx, TMA]\n\n # Schedule the gmem->smem part\n smem_cache.merge(0, 1)\n smem_cache.merge(0, 1)\n smem_cache.split(0, 256)\n smem_cache.split(0, 4)\n smem_cache.axis(0).parallelize(ParallelType.grid_x)\n smem_cache.axis(2).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n # TMA will be generated like:\n # Note that the coordinate is in number of items, smem address is in\n # bytes\n #\n # if (threadIdx.x < 4) {\n # Hopper::cpAsyncBulkTensorTileS2G(\n # coordinate = {1024 * blockIdx.x + 256 * threadIdx.x},\n # smem_addr = (toSmem(T2) + 1024 * threadIdx.x));\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example5(nvfuser_direct_test):\n \"\"\"\n Example 5: Still the same copy kernel of 3D tensor, but this time, we\n want to do tiling on the inner two dimensions. The first dimension is\n treated as a \"batch\" dimension. We use CTA tile (64, 64), and TMA tile\n (32, 32), so we need 4 TMA instructions to load the entire CTA tile.\n We want to use two threads, and each thread issue two TMA instructions.\n \"\"\"\n\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = input.cache_after(LoadStoreOpType.tma)","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_basic_tma_example5","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_basic_tma_example5#L983-L1086","kind":"function","name":"test_tutorial_basic_tma_example5","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":983,"end_line":1086,"context_start_line":963,"context_end_line":1106,"code":" #\n # if (threadIdx.x < 4) {\n # Hopper::cpAsyncBulkTensorTileS2G(\n # coordinate = {1024 * blockIdx.x + 256 * threadIdx.x},\n # smem_addr = (toSmem(T2) + 1024 * threadIdx.x));\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example5(nvfuser_direct_test):\n \"\"\"\n Example 5: Still the same copy kernel of 3D tensor, but this time, we\n want to do tiling on the inner two dimensions. The first dimension is\n treated as a \"batch\" dimension. We use CTA tile (64, 64), and TMA tile\n (32, 32), so we need 4 TMA instructions to load the entire CTA tile.\n We want to use two threads, and each thread issue two TMA instructions.\n \"\"\"\n\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = input.cache_after(LoadStoreOpType.tma)\n smem_cache.set_memory_type(MemoryType.shared)\n\n # For TMA load, both the shared memory layout and the loop nest and\n # parallelization of TMA are specified by the consumer: smem_cache\n\n # Step 1: define TMA domain\n # For this case, we want to treat all three dimensions separately.\n # TMA domain: [I0, I1, I2]\n # Note that the TMA domain only exist in people's mind, there is no need to\n # set anything here.\n\n # Step 2: define box\n smem_cache.split(2, 32)\n smem_cache.split(1, 32)\n # [I0, I1/32, 32, I2/32', 32']\n # Box dimensions defined by partitioning: I1 and I2\n # partitioned IterDomain: I1, I2\n # coordinate IterDomain: I1/32, I2/32'\n # box IterDomain: 32, 32'\n # Box dimension defined by compositing: I0\n # coordinate IterDomain: I0\n # box IterDomain: no box IterDomain, so implicit size 1\n\n # Step 3: define tile\n # We use dense tile here, so tile == box. Nothing to do here.\n\n # Step 4: schedule the shared memory tensor\n # By default, the allocation domain is the logical domain. The default\n # value does not work for this case, because the tile will not be\n # contiguous in shared memory.\n # [I0, I1/32, 32, I2/32', 32']\n smem_cache.split(3, 2)\n smem_cache.split(1, 2)\n # [I0, I1/32/2, 2, 32, I2/32'/2', 2', 32']\n smem_cache.reorder({3: -2, 2: -4})\n # [I0, I1/32/2, I2/32'/2', 2, 2', 32, 32']\n smem_cache.set_allocation_domain(\n smem_cache.get_loop_domain(), new_contiguity=True\n )\n\n # Step 5: schedule the consumer tensor\n # [I0, I1/32/2, I2/32'/2', 2, 2', 32, 32']\n smem_cache.axis(0).parallelize(ParallelType.grid_x)\n smem_cache.axis(1).parallelize(ParallelType.grid_y)\n smem_cache.axis(2).parallelize(ParallelType.grid_z)\n smem_cache.axis(3).parallelize(ParallelType.block_x)\n smem_cache.axis(5).parallelize(ParallelType.tma)\n smem_cache.axis(6).parallelize(ParallelType.tma)\n # [BIDx, BIDy, BIDz, TIDx, Serial, TMA, TMA]\n\n # Schedule the smem->gmem part\n output.split(2, 32)\n output.split(1, 32)\n output.split(3, 2)\n output.split(1, 2)\n output.reorder({3: -2, 2: -4})\n output.axis(0).parallelize(ParallelType.grid_x)\n output.axis(1).parallelize(ParallelType.grid_y)\n output.axis(2).parallelize(ParallelType.grid_z)\n output.merge(3, 4)\n output.axis(3).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n # TMA will be generated like:\n # Note that the coordinate is in number of items, smem address is in\n # bytes. Also note that coordinate is in column major, so inner dims\n # goes first\n #\n # for (nvfuser_index_t i13 = 0; i13 < 2; ++i13) {\n # if (threadIdx.x < 2) {\n # Hopper::cpAsyncBulkTensorTileG2S(\n # coordinate =\n # {64 * blockIdx.z + 32 * i13,\n # 64 * blockIdx.y + 32 * threadIdx.x,\n # blockIdx.x},\n # smem_addr = toSmem(T2) + 8192 * threadIdx.x + 4096 * i13);\n # }\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example6(nvfuser_direct_test):\n \"\"\"\n Example 6: Similar to example 5, but we are using TMA for store instead\n of load.\n \"\"\"\n\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = output.cache_before(LoadStoreOpType.tma)\n smem_cache.set_memory_type(MemoryType.shared)\n\n # For TMA store, the loop nest and parallelization is specified in the","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_basic_tma_example6","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_basic_tma_example6#L1092-L1196","kind":"function","name":"test_tutorial_basic_tma_example6","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1092,"end_line":1196,"context_start_line":1072,"context_end_line":1216,"code":" # {64 * blockIdx.z + 32 * i13,\n # 64 * blockIdx.y + 32 * threadIdx.x,\n # blockIdx.x},\n # smem_addr = toSmem(T2) + 8192 * threadIdx.x + 4096 * i13);\n # }\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_basic_tma_example6(nvfuser_direct_test):\n \"\"\"\n Example 6: Similar to example 5, but we are using TMA for store instead\n of load.\n \"\"\"\n\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n output = fd.ops.set(input)\n fd.add_output(output)\n\n smem_cache = output.cache_before(LoadStoreOpType.tma)\n smem_cache.set_memory_type(MemoryType.shared)\n\n # For TMA store, the loop nest and parallelization is specified in the\n # consumer `output`, and the shared memory layout is specified in the\n # allocation dimain of `smem_cache`.\n\n # Step 1: define TMA domain\n # For this case, we want to treat all three dimensions separately.\n # TMA domain: [I0, I1, I2]\n # Note that the TMA domain only exist in people's mind, there is no need to\n # set anything here.\n\n # Step 2: define box\n output.split(2, 32)\n output.split(1, 32)\n # [I0, I1/32, 32, I2/32', 32']\n # Box dimensions defined by partitioning: I1 and I2\n # partitioned IterDomain: I1, I2\n # coordinate IterDomain: I1/32, I2/32'\n # box IterDomain: 32, 32'\n # Box dimension defined by compositing: I0\n # coordinate IterDomain: I0\n # box IterDomain: no box IterDomain, so implicit size 1\n\n # Step 3: define tile\n # We use dense tile here, so tile == box. Nothing to do here.\n\n # Step 4: schedule the shared memory tensor\n # By default, the allocation domain is the logical domain. The default\n # value does not work for this case, because th tile will not be\n # contiguous in shared memory.\n # [I0, I1, I2]\n smem_cache.split(2, 32)\n smem_cache.split(1, 32)\n # [I0, I1/32, 32, I2/32', 32']\n smem_cache.split(3, 2)\n smem_cache.split(1, 2)\n # [I0, I1/32/2, 2, 32, I2/32'/2', 2', 32']\n smem_cache.reorder({3: -2, 2: -4})\n # [I0, I1/32/2, I2/32'/2', 2, 2', 32, 32']\n smem_cache.set_allocation_domain(\n smem_cache.get_loop_domain(), new_contiguity=True\n )\n\n # Step 5: schedule the consumer tensor\n # Because we are not inlining anything in this example, we do not care\n # about the order of IterDomains.\n # [I0, I1/32, 32, I2/32', 32']\n output.split(3, 2)\n output.split(1, 2)\n # [I0, I1/32/2, 2, 32, I2/32'/2', 2', 32']\n output.axis(0).parallelize(ParallelType.grid_x)\n output.axis(1).parallelize(ParallelType.grid_y)\n output.axis(2).parallelize(ParallelType.block_x)\n output.axis(3).parallelize(ParallelType.tma)\n output.axis(4).parallelize(ParallelType.grid_z)\n output.axis(6).parallelize(ParallelType.tma)\n # [BIDx, BIDy, TIDx, TMA, BIDz, Serial, TMA]\n\n # Schedule the gmem->smem part\n smem_cache.merge(-2, -1)\n smem_cache.axis(0).parallelize(ParallelType.grid_x)\n smem_cache.axis(1).parallelize(ParallelType.grid_y)\n smem_cache.axis(2).parallelize(ParallelType.grid_z)\n smem_cache.axis(-1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n # TMA will be generated like:\n # Note that the coordinate is in number of items, smem address is in\n # bytes.Also note that coordinate is in column major, so inner dims\n # goes first\n #\n # for (nvfuser_index_t i19 = 0; i19 < 2; ++i19) {\n # if (threadIdx.x < 2) {\n # Hopper::cpAsyncBulkTensorTileS2G(\n # coordinate =\n # {64 * blockIdx.z + 32 * i19,\n # 64 * blockIdx.y + 32 * threadIdx.x,\n # blockIdx.x},\n # smem_addr = toSmem(T2) + 8192 * threadIdx.x + 4096 * i19);\n # }\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_vectorize_store_pointwise_tma(nvfuser_direct_test):\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n tv1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Create cache_tvs\n tv0a = tv0.cache_after(LoadStoreOpType.tma)\n tv1a = tv1.cache_after(LoadStoreOpType.tma)\n tv2b = tv2.cache_before()\n\n tv0a.set_memory_type(MemoryType.shared)\n tv1a.set_memory_type(MemoryType.shared)\n","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_vectorize_store_pointwise_tma","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_vectorize_store_pointwise_tma#L1202-L1290","kind":"function","name":"test_tutorial_vectorize_store_pointwise_tma","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1202,"end_line":1290,"context_start_line":1182,"context_end_line":1310,"code":" # {64 * blockIdx.z + 32 * i19,\n # 64 * blockIdx.y + 32 * threadIdx.x,\n # blockIdx.x},\n # smem_addr = toSmem(T2) + 8192 * threadIdx.x + 4096 * i19);\n # }\n # }\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(5, 3, 300, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_vectorize_store_pointwise_tma(nvfuser_direct_test):\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n tv1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Create cache_tvs\n tv0a = tv0.cache_after(LoadStoreOpType.tma)\n tv1a = tv1.cache_after(LoadStoreOpType.tma)\n tv2b = tv2.cache_before()\n\n tv0a.set_memory_type(MemoryType.shared)\n tv1a.set_memory_type(MemoryType.shared)\n\n reference_tv = tv2\n\n # Step 1: Create tma domain\n # Use the root domain as TMA domain\n # root domain: [I0, I1]\n\n num_threads = 128\n vectorization = 2\n tma_tile = num_threads * vectorization\n num_stages = 4\n num_ctas_for_hopper = 132\n\n # Step 2: Create Box\n # After TMA domain creation\n # split: [I0, I3, 256]\n reference_tv.split(-1, tma_tile)\n # split: [I2, 4, I3, 256]\n reference_tv.split(0, num_stages)\n\n # Step 3: Create Tile\n # Do nothing here because box == tile\n\n # Step 4: Schedule Shared Memory Tensor\n # split: [I2, 4, I3, 128, 2]\n reference_tv.split(-1, vectorization)\n # split: [I4, 132, 4, I3, 128, 2]\n reference_tv.split(0, num_ctas_for_hopper)\n # reorder: [I4, 132, I3, 4, 128, 2]\n reference_tv.reorder({3: 2, 2: 3})\n\n # Transform Operations between cache operations and output reference\n fd.sched.transform_like(reference_tv)\n\n # Propagate common parallel dimensions\n reference_tv.axis(1).parallelize(ParallelType.grid_x)\n fd.sched.parallelize_like(reference_tv)\n\n tv2b.axis(-2).parallelize(ParallelType.block_x)\n\n # Vectorization for writing results to gmem\n reference_tv.axis(-3).parallelize(ParallelType.unroll)\n reference_tv.axis(-2).parallelize(ParallelType.block_x)\n reference_tv.axis(-1).parallelize(ParallelType.vectorize)\n\n # Apply bulk type to TMA tensors\n tv0a.axis(-1).parallelize(ParallelType.tma)\n tv0a.axis(-2).parallelize(ParallelType.tma)\n tv0a.axis(-3).parallelize(ParallelType.tma)\n\n tv1a.axis(-1).parallelize(ParallelType.tma)\n tv1a.axis(-2).parallelize(ParallelType.tma)\n tv1a.axis(-3).parallelize(ParallelType.tma)\n\n # ComputeAt\n fd.sched.inline_most()\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n\n dim0 = 16384\n dim1 = 16384\n\n # Compile with KernelExecutor directly to avoid scheduling\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(dim0, dim1, dtype=torch.float, device=\"cuda:0\")\n t1 = torch.randn(dim0, dim1, dtype=torch.float, device=\"cuda:0\")\n t2 = t0 + t1\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0, t1], compile_params=index32bit)\n outputs = ke.run([t0, t1])\n assert outputs[0].equal(t2)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_pointwise_broadcast_tma(nvfuser_direct_test):\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n tv1 = fd.define_tensor(\n shape=[-1, -1, -1, -1], contiguity=[True, False, True, True]\n )\n tv2 = fd.ops.broadcast(tv0, [True, False, False, False])\n tv3 = fd.ops.add(tv2, tv1)\n fd.add_output(tv3)\n\n # Create cache_tvs\n tv0a = tv0.cache_after(LoadStoreOpType.tma)\n tv1a = tv1.cache_after(LoadStoreOpType.tma)\n tv3b = tv3.cache_before(LoadStoreOpType.tma)\n","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_pointwise_broadcast_tma","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_pointwise_broadcast_tma#L1296-L1385","kind":"function","name":"test_tutorial_pointwise_broadcast_tma","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1296,"end_line":1385,"context_start_line":1276,"context_end_line":1405,"code":"\n dim0 = 16384\n dim1 = 16384\n\n # Compile with KernelExecutor directly to avoid scheduling\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(dim0, dim1, dtype=torch.float, device=\"cuda:0\")\n t1 = torch.randn(dim0, dim1, dtype=torch.float, device=\"cuda:0\")\n t2 = t0 + t1\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0, t1], compile_params=index32bit)\n outputs = ke.run([t0, t1])\n assert outputs[0].equal(t2)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_pointwise_broadcast_tma(nvfuser_direct_test):\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n tv1 = fd.define_tensor(\n shape=[-1, -1, -1, -1], contiguity=[True, False, True, True]\n )\n tv2 = fd.ops.broadcast(tv0, [True, False, False, False])\n tv3 = fd.ops.add(tv2, tv1)\n fd.add_output(tv3)\n\n # Create cache_tvs\n tv0a = tv0.cache_after(LoadStoreOpType.tma)\n tv1a = tv1.cache_after(LoadStoreOpType.tma)\n tv3b = tv3.cache_before(LoadStoreOpType.tma)\n\n tv0a.set_memory_type(MemoryType.shared)\n tv1a.set_memory_type(MemoryType.shared)\n tv3b.set_memory_type(MemoryType.shared)\n\n reference_tv = tv3\n\n # Step 1: Create tma domain\n # root domain: [I0, I1, I2, I3]\n # TMA domain: [I0, I1, I4]\n reference_tv.merge(-2, -1)\n\n # Step 2: Define TMA Box\n # split: [I0, I1, I5, 256]\n reference_tv.split(-1, 256)\n\n # Step 3: Define Tile\n # Do nothing here because tile == box.\n\n # Step 4: Schedule Shared Memory Tensor\n # merge: [I10, I5, 256]\n reference_tv.merge(0, 1)\n # split: [I10, I7, 4, 256]\n reference_tv.split(-2, 4)\n # merge: [I11, 4, 256]\n reference_tv.merge(0, 1)\n\n # Transform Operations between cache operations and output reference\n fd.sched.transform_like(reference_tv)\n\n # Define Parallelization Schema\n # Intermediate Tensors\n tv3b.axis(0).parallelize(ParallelType.grid_x)\n tv3b.axis(1).parallelize(ParallelType.unroll)\n tv3b.axis(2).parallelize(ParallelType.block_x)\n\n tv2.axis(0).parallelize(ParallelType.grid_x)\n tv2.axis(1).parallelize(ParallelType.unroll)\n tv2.axis(2).parallelize(ParallelType.block_x)\n\n # TMA Tensors\n tv1a.axis(0).parallelize(ParallelType.grid_x)\n tv1a.axis(1).parallelize(ParallelType.block_x)\n tv1a.axis(2).parallelize(ParallelType.tma)\n\n tv0a.axis(0).parallelize(ParallelType.grid_x)\n tv0a.axis(1).parallelize(ParallelType.block_x)\n tv0a.axis(2).parallelize(ParallelType.tma)\n\n tv3.axis(0).parallelize(ParallelType.grid_x)\n tv3.axis(1).parallelize(ParallelType.block_x)\n tv3.axis(2).parallelize(ParallelType.tma)\n\n # ComputeAt\n fd.sched.inline_most()\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n\n dim0 = 32\n dim1 = 2\n dim2 = 4\n dim3 = 256\n\n # Compile with KernelExecutor directly to avoid scheduling\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(dim1, dim2, dim3, dtype=torch.float, device=\"cuda:0\")\n t1 = torch.randn(dim0, dim1, dim2, dim3, dtype=torch.float, device=\"cuda:0\")\n t2 = t0 + t1\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0, t1], compile_params=index32bit)\n outputs = ke.run([t0, t1])\n assert outputs[0].equal(t2)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_tma_bank_conflict_free_transpose(nvfuser_direct_test):\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n output = fd.ops.permute(input, [1, 0])\n fd.add_output(output)\n\n # Change the fusion to input->smem->register->smem->output where the\n # smem->register part does the transpose\n input_smem_cache = input.cache_after(LoadStoreOpType.tma)\n input_smem_cache.set_memory_type(MemoryType.shared)\n\n output_smem_cache = output.cache_before(LoadStoreOpType.tma)\n output_smem_cache.set_memory_type(MemoryType.shared)\n\n output_reg_cache = output_smem_cache.cache_before()","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_tma_bank_conflict_free_transpose","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_tma_bank_conflict_free_transpose#L1391-L1489","kind":"function","name":"test_tutorial_tma_bank_conflict_free_transpose","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1391,"end_line":1489,"context_start_line":1371,"context_end_line":1509,"code":" dim1 = 2\n dim2 = 4\n dim3 = 256\n\n # Compile with KernelExecutor directly to avoid scheduling\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(dim1, dim2, dim3, dtype=torch.float, device=\"cuda:0\")\n t1 = torch.randn(dim0, dim1, dim2, dim3, dtype=torch.float, device=\"cuda:0\")\n t2 = t0 + t1\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0, t1], compile_params=index32bit)\n outputs = ke.run([t0, t1])\n assert outputs[0].equal(t2)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_tutorial_tma_bank_conflict_free_transpose(nvfuser_direct_test):\n with FusionDefinition() as fd:\n input = fd.define_tensor(shape=[-1, -1], contiguity=[True, True])\n output = fd.ops.permute(input, [1, 0])\n fd.add_output(output)\n\n # Change the fusion to input->smem->register->smem->output where the\n # smem->register part does the transpose\n input_smem_cache = input.cache_after(LoadStoreOpType.tma)\n input_smem_cache.set_memory_type(MemoryType.shared)\n\n output_smem_cache = output.cache_before(LoadStoreOpType.tma)\n output_smem_cache.set_memory_type(MemoryType.shared)\n\n output_reg_cache = output_smem_cache.cache_before()\n\n # Create 32x32 tile. Each CTA has one tile, and the entire tile will be\n # loaded to shared memory by TMA, and stored back to global memory by TMA.\n\n # [I1, I0]\n output.split(1, 32)\n output.split(0, 32)\n # [I1, 32', I0, 32]\n output.reorder({0: 1, 1: 2, 2: 0})\n output.merge(0, 1)\n # [I0/32 * I1/32', 32', 32]\n output.axis(0).parallelize(ParallelType.grid_x)\n # [BIDx, 32', 32]\n\n fd.sched.bounded_transform_backward(\n output, -1, [input], propagate_parallel_type=True\n )\n\n # For fusion output, we just use TMA to store the entire tile back to global\n # memory. There is no need to further schedule the output tensor.\n output.axis(1).parallelize(ParallelType.tma)\n output.axis(2).parallelize(ParallelType.tma)\n # [BIDx, Bulk, Bulk]\n\n # output_smem_cache and output_reg_cache are scheduled in the same way.\n # We use each warp to load one column of input_smem_cache. We vectorize\n # the load to 16 bytes, and use 8 warps to load all these 8 columns. Then,\n # when we write to output_smem_cache, we unroll the write. Each warp writes\n # one row in output_smem_cache in each iteration, so there is no bank\n # conflict.\n\n # [BIDx, 32', 32]\n output_smem_cache.set_allocation_domain(\n output_smem_cache.get_loop_domain(), new_contiguity=True\n )\n output_smem_cache.split(1, 4)\n # [BIDx, 8', 4', 32]\n\n fd.sched.bounded_transform_backward(output_smem_cache, -1, [input])\n\n output_smem_cache.merge(1, 3)\n # [BIDx, 256, 4']\n output_smem_cache.axis(1).parallelize(ParallelType.block_x)\n\n fd.sched.bounded_transform_backward(\n output_smem_cache, -1, [input_smem_cache], propagate_parallel_type=True\n )\n\n output_smem_cache.axis(2).parallelize(ParallelType.unroll)\n output_reg_cache.axis(2).parallelize(ParallelType.vectorize)\n output_reg_cache.set_allocation_domain(\n output_reg_cache.get_loop_domain(), new_contiguity=True\n )\n\n # Schedule the memory format for 128 byte swizzle\n # [BIDx, 8', 4', 32]\n input_smem_cache.reorder({3: 1, 1: 2, 2: 3})\n # [BIDx, 32, 8', 4']\n input_smem_cache.split(1, 8)\n # [BIDx, 4, 8, 8', 4']\n input_smem_cache.swizzle(2, 3)\n # [BIDx, 4, 8, 8', 4']\n input_smem_cache.set_allocation_domain(\n input_smem_cache.get_loop_domain(), new_contiguity=True\n )\n\n input_smem_cache.axis(1).parallelize(ParallelType.tma)\n input_smem_cache.axis(2).parallelize(ParallelType.tma)\n input_smem_cache.axis(3).parallelize(ParallelType.tma)\n input_smem_cache.axis(4).parallelize(ParallelType.tma)\n # [BIDx, Bulk, Bulk, Bulk, Bulk]\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(10000, 10000, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0.t())\n\n\ndef test_tutorial_compute_heuristics_and_schedule():\n \"\"\"\n Demonstrate explicit scheduling: compute_heuristics, modify, then schedule.\n This shows how to customize automatically computed heuristics.\n \"\"\"\n inputs = [\n torch.randn(4, 4, device=\"cuda\"),\n torch.randn(4, 4, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.exp(t2)\n fd.add_output(t3)\n\n # Step 1: Compute heuristics for pointwise scheduler","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_compute_heuristics_and_schedule","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_compute_heuristics_and_schedule#L1492-L1568","kind":"function","name":"test_tutorial_compute_heuristics_and_schedule","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1492,"end_line":1568,"context_start_line":1472,"context_end_line":1588,"code":" input_smem_cache.axis(1).parallelize(ParallelType.tma)\n input_smem_cache.axis(2).parallelize(ParallelType.tma)\n input_smem_cache.axis(3).parallelize(ParallelType.tma)\n input_smem_cache.axis(4).parallelize(ParallelType.tma)\n # [BIDx, Bulk, Bulk, Bulk, Bulk]\n\n if verbose_:\n print(fd.fusion.print_math())\n print(fd.fusion.print_kernel())\n\n index32bit = CompileParams(\n index_type=DataType.Int32, maxrregcount=255, enable_magic_zero=False\n )\n t0 = torch.randn(10000, 10000, dtype=torch.float, device=\"cuda:0\")\n ke = KernelExecutor()\n ke.compile(fd.fusion, [t0], compile_params=index32bit)\n outputs = ke.run([t0])\n assert outputs[0].equal(t0.t())\n\n\ndef test_tutorial_compute_heuristics_and_schedule():\n \"\"\"\n Demonstrate explicit scheduling: compute_heuristics, modify, then schedule.\n This shows how to customize automatically computed heuristics.\n \"\"\"\n inputs = [\n torch.randn(4, 4, device=\"cuda\"),\n torch.randn(4, 4, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.exp(t2)\n fd.add_output(t3)\n\n # Step 1: Compute heuristics for pointwise scheduler\n heuristic_params = schedule.compute_heuristics(\n fd.fusion, SchedulerType.pointwise, inputs\n )\n\n before_modification = \"\"\"\n===== Pointwise Parameters ========\nTag: Pointwise heuristics Pointwise Characteristics:\n Gridx: 1 BlckY: 1 BlckX: 128\nvectorization_factor: 1\nunroll_factor_outer: 1\nunroll_factor_inner: 1\n====================================\n\"\"\"\n assert str(heuristic_params) == before_modification\n\n # Step 2: Modify the computed heuristics\n # Example: Adjust vectorization and unroll factors\n heuristic_params.vectorization_factor = 1\n heuristic_params.unroll_factor_inner = 2\n\n after_modification = \"\"\"\n===== Pointwise Parameters ========\nTag: Pointwise heuristics Pointwise Characteristics:\n Gridx: 1 BlckY: 1 BlckX: 128\nvectorization_factor: 1\nunroll_factor_outer: 1\nunroll_factor_inner: 2\n====================================\n\"\"\"\n assert str(heuristic_params) == after_modification\n\n # Step 3: Apply the schedule using modified heuristics\n schedule.schedule(fd.fusion, SchedulerType.pointwise, heuristic_params)\n\n schedule_fusion_math = \"\"\"Inputs:\n T0_g_float[iS61{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iS62{1}, iS60{2}, iS58{128}]\n T1_g_float[iS47{( ceilDiv(( ceilDiv(( i3 * i4 ), 128) ), 2) )}, iS48{1}, iS46{2}, iS44{128}]\nOutputs:\n T3_g_float[iblockIdx.x19{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS20{1}, iS18{2}, ithreadIdx.x16{128}] ca_pos( 2 ) produce_pos( 4 )\n\n%kernel_math {\nT4_l_float[iblockIdx.x54{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS55{1}, iS53{2}, ithreadIdx.x51{128}] ca_pos( 2 )\n = Set( T0_g_float[iS61{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iS62{1}, iS60{2}, iS58{128}], cache_op=Streaming )\nT5_l_float[iblockIdx.x40{( ceilDiv(( ceilDiv(( i3 * i4 ), 128) ), 2) )}, iUS41{1}, iS39{2}, ithreadIdx.x37{128}] ca_pos( 2 )\n = Set( T1_g_float[iS47{( ceilDiv(( ceilDiv(( i3 * i4 ), 128) ), 2) )}, iS48{1}, iS46{2}, iS44{128}], cache_op=Streaming )\nT2_l_float[iblockIdx.x33{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS34{1}, iS32{2}, ithreadIdx.x30{128}] ca_pos( 4 ) produce_pos( 2 )\n = T4_l_float[iblockIdx.x54{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS55{1}, iS53{2}, ithreadIdx.x51{128}] ca_pos( 2 )\n + T5_l_float[iblockIdx.x40{( ceilDiv(( ceilDiv(( i3 * i4 ), 128) ), 2) )}, iUS41{1}, iS39{2}, ithreadIdx.x37{128}] ca_pos( 2 );\nT6_l_float[iblockIdx.x26{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS27{1}, iS25{2}, ithreadIdx.x23{128}] ca_pos( 4 ) produce_pos( 4 )\n = expf(T2_l_float[iblockIdx.x33{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS34{1}, iS32{2}, ithreadIdx.x30{128}] ca_pos( 4 ) produce_pos( 2 ));\nT3_g_float[iblockIdx.x19{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS20{1}, iS18{2}, ithreadIdx.x16{128}] ca_pos( 2 ) produce_pos( 4 )\n = Set( T6_l_float[iblockIdx.x26{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS27{1}, iS25{2}, ithreadIdx.x23{128}] ca_pos( 4 ) produce_pos( 4 ), cache_op=Streaming )\n} // %kernel_math \\n\\n\"\"\"\n assert fd.fusion.print_math() == schedule_fusion_math\n\n # Execute with the modified heuristic params\n nvf_out = fd.manual_execute(inputs, heuristic_params)\n eager_out = torch.exp(inputs[0] + inputs[1])\n torch.testing.assert_close(eager_out, nvf_out[0])\n\n\ndef test_tutorial_pointwise_auto_scheduler():\n \"\"\"\n Implement a simple pointwise kernel with automatic scheduling.\n Uses nvfuser's PointwiseScheduler.\n \"\"\"\n inputs = [\n torch.randn(4, 4, device=\"cuda\"),\n torch.randn(4, 4, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.exp(t2)\n fd.add_output(t3)\n\n # Apply selected scheduler","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_pointwise_auto_scheduler","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_pointwise_auto_scheduler#L1571-L1595","kind":"function","name":"test_tutorial_pointwise_auto_scheduler","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1571,"end_line":1595,"context_start_line":1551,"context_end_line":1615,"code":"T4_l_float[iblockIdx.x54{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS55{1}, iS53{2}, ithreadIdx.x51{128}] ca_pos( 2 )\n = Set( T0_g_float[iS61{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iS62{1}, iS60{2}, iS58{128}], cache_op=Streaming )\nT5_l_float[iblockIdx.x40{( ceilDiv(( ceilDiv(( i3 * i4 ), 128) ), 2) )}, iUS41{1}, iS39{2}, ithreadIdx.x37{128}] ca_pos( 2 )\n = Set( T1_g_float[iS47{( ceilDiv(( ceilDiv(( i3 * i4 ), 128) ), 2) )}, iS48{1}, iS46{2}, iS44{128}], cache_op=Streaming )\nT2_l_float[iblockIdx.x33{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS34{1}, iS32{2}, ithreadIdx.x30{128}] ca_pos( 4 ) produce_pos( 2 )\n = T4_l_float[iblockIdx.x54{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS55{1}, iS53{2}, ithreadIdx.x51{128}] ca_pos( 2 )\n + T5_l_float[iblockIdx.x40{( ceilDiv(( ceilDiv(( i3 * i4 ), 128) ), 2) )}, iUS41{1}, iS39{2}, ithreadIdx.x37{128}] ca_pos( 2 );\nT6_l_float[iblockIdx.x26{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS27{1}, iS25{2}, ithreadIdx.x23{128}] ca_pos( 4 ) produce_pos( 4 )\n = expf(T2_l_float[iblockIdx.x33{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS34{1}, iS32{2}, ithreadIdx.x30{128}] ca_pos( 4 ) produce_pos( 2 ));\nT3_g_float[iblockIdx.x19{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS20{1}, iS18{2}, ithreadIdx.x16{128}] ca_pos( 2 ) produce_pos( 4 )\n = Set( T6_l_float[iblockIdx.x26{( ceilDiv(( ceilDiv(( i0 * i1 ), 128) ), 2) )}, iUS27{1}, iS25{2}, ithreadIdx.x23{128}] ca_pos( 4 ) produce_pos( 4 ), cache_op=Streaming )\n} // %kernel_math \\n\\n\"\"\"\n assert fd.fusion.print_math() == schedule_fusion_math\n\n # Execute with the modified heuristic params\n nvf_out = fd.manual_execute(inputs, heuristic_params)\n eager_out = torch.exp(inputs[0] + inputs[1])\n torch.testing.assert_close(eager_out, nvf_out[0])\n\n\ndef test_tutorial_pointwise_auto_scheduler():\n \"\"\"\n Implement a simple pointwise kernel with automatic scheduling.\n Uses nvfuser's PointwiseScheduler.\n \"\"\"\n inputs = [\n torch.randn(4, 4, device=\"cuda\"),\n torch.randn(4, 4, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.exp(t2)\n fd.add_output(t3)\n\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.pointwise, inputs\n )\n\n nvf_out = fd.manual_execute(inputs, heuristic_params)\n eager_out = torch.exp(inputs[0] + inputs[1])\n torch.testing.assert_close(eager_out, nvf_out[0])\n\n\ndef test_tutorial_reduction_auto_scheduler():\n \"\"\"\n Implement a simple reduction kernel with automatic scheduling.\n - Expects failure with PointwiseScheduler\n - Uses nvfuser's ReductionScheduler\n \"\"\"\n inputs = [\n torch.randn(4, 4, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.sum(t0, dims=[1])\n t2 = fd.ops.exp(t1)\n fd.add_output(t2)\n\n # Test error msg for can_schedule\n pointwise_status, error_msg = schedule.can_schedule(","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_reduction_auto_scheduler","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_reduction_auto_scheduler#L1598-L1631","kind":"function","name":"test_tutorial_reduction_auto_scheduler","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1598,"end_line":1631,"context_start_line":1578,"context_end_line":1651,"code":" torch.randn(4, 4, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.exp(t2)\n fd.add_output(t3)\n\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.pointwise, inputs\n )\n\n nvf_out = fd.manual_execute(inputs, heuristic_params)\n eager_out = torch.exp(inputs[0] + inputs[1])\n torch.testing.assert_close(eager_out, nvf_out[0])\n\n\ndef test_tutorial_reduction_auto_scheduler():\n \"\"\"\n Implement a simple reduction kernel with automatic scheduling.\n - Expects failure with PointwiseScheduler\n - Uses nvfuser's ReductionScheduler\n \"\"\"\n inputs = [\n torch.randn(4, 4, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.sum(t0, dims=[1])\n t2 = fd.ops.exp(t1)\n fd.add_output(t2)\n\n # Test error msg for can_schedule\n pointwise_status, error_msg = schedule.can_schedule(\n fd.fusion, SchedulerType.pointwise, inputs\n )\n assert not pointwise_status\n assert (\n error_msg.strip()\n == \"Scheduler _pointwise_ ***rejected*** because : cannot find reference tensor\"\n )\n\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.reduction, inputs\n )\n\n nvf_out = fd.manual_execute(inputs, heuristic_params)\n eager_out = torch.exp(inputs[0].sum(1))\n torch.testing.assert_close(eager_out, nvf_out[0])\n\n\ndef test_tutorial_inner_persistent_auto_scheduler():\n \"\"\"\n Implement a simple normalization kernel with automatic scheduling.\n Uses nvfuser's InnerPersistentScheduler.\n \"\"\"\n tensor_size = 4\n inputs = [torch.randn(tensor_size, tensor_size, device=\"cuda\")]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n s0 = fd.define_scalar(1e-6, dtype=DataType.Double)\n norm_const = fd.define_scalar(tensor_size, dtype=DataType.Int)\n\n bcast_sum0 = fd.ops.sum(t0, dims=[-1], keepdim=True)\n mean = fd.ops.div(bcast_sum0, norm_const)\n\n diff = fd.ops.sub(t0, mean)\n diff_sq = fd.ops.mul(diff, diff)","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_inner_persistent_auto_scheduler","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_inner_persistent_auto_scheduler#L1634-L1668","kind":"function","name":"test_tutorial_inner_persistent_auto_scheduler","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1634,"end_line":1668,"context_start_line":1614,"context_end_line":1688,"code":" # Test error msg for can_schedule\n pointwise_status, error_msg = schedule.can_schedule(\n fd.fusion, SchedulerType.pointwise, inputs\n )\n assert not pointwise_status\n assert (\n error_msg.strip()\n == \"Scheduler _pointwise_ ***rejected*** because : cannot find reference tensor\"\n )\n\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.reduction, inputs\n )\n\n nvf_out = fd.manual_execute(inputs, heuristic_params)\n eager_out = torch.exp(inputs[0].sum(1))\n torch.testing.assert_close(eager_out, nvf_out[0])\n\n\ndef test_tutorial_inner_persistent_auto_scheduler():\n \"\"\"\n Implement a simple normalization kernel with automatic scheduling.\n Uses nvfuser's InnerPersistentScheduler.\n \"\"\"\n tensor_size = 4\n inputs = [torch.randn(tensor_size, tensor_size, device=\"cuda\")]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n s0 = fd.define_scalar(1e-6, dtype=DataType.Double)\n norm_const = fd.define_scalar(tensor_size, dtype=DataType.Int)\n\n bcast_sum0 = fd.ops.sum(t0, dims=[-1], keepdim=True)\n mean = fd.ops.div(bcast_sum0, norm_const)\n\n diff = fd.ops.sub(t0, mean)\n diff_sq = fd.ops.mul(diff, diff)\n bcast_sum1 = fd.ops.sum(diff_sq, dims=[-1], keepdim=True)\n var = fd.ops.div(bcast_sum1, norm_const)\n\n t0_diff = fd.ops.sub(t0, mean)\n var_eps = fd.ops.sqrt(fd.ops.add(var, s0))\n t0_norm = fd.ops.div(t0_diff, var_eps)\n fd.add_output(t0_norm)\n\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.inner_persistent, inputs\n )\n\n nvf_out = fd.manual_execute(inputs, heuristic_params)\n var, mean = torch.var_mean(inputs[0], dim=-1, correction=0, keepdim=True)\n eager_out = (inputs[0] - mean) / torch.sqrt(var + 1e-6)\n torch.testing.assert_close(eager_out, nvf_out[0])\n\n\ndef test_tutorial_scheduling_layer_norm_with_profiling():\n \"\"\"Test and profile layer norm fusion with manual scheduling.\"\"\"\n\n def _definition_func(fd: FusionDefinition, inputs, tensor_size):\n \"\"\"Define the layer norm fusion operations.\"\"\"\n t0 = fd.from_pytorch(inputs[0])\n s0 = fd.define_scalar(1e-6, dtype=DataType.Double)\n norm_const = fd.define_scalar(tensor_size, dtype=DataType.Int)\n\n mean_cast = fd.ops.cast(t0, dtype=DataType.Float)\n bcast_sum0 = fd.ops.sum(mean_cast, dims=[-1], keepdim=True)\n mean = fd.ops.div(bcast_sum0, norm_const)\n\n var_cast = fd.ops.cast(t0, dtype=DataType.Float)\n diff = fd.ops.sub(var_cast, mean)\n diff_sq = fd.ops.mul(diff, diff)\n bcast_sum1 = fd.ops.sum(diff_sq, dims=[-1], keepdim=True)\n var = fd.ops.div(bcast_sum1, norm_const)","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_tutorial_scheduling_layer_norm_with_profiling","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_tutorial_scheduling_layer_norm_with_profiling#L1671-L1800","kind":"function","name":"test_tutorial_scheduling_layer_norm_with_profiling","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1671,"end_line":1800,"context_start_line":1651,"context_end_line":1820,"code":" diff_sq = fd.ops.mul(diff, diff)\n bcast_sum1 = fd.ops.sum(diff_sq, dims=[-1], keepdim=True)\n var = fd.ops.div(bcast_sum1, norm_const)\n\n t0_diff = fd.ops.sub(t0, mean)\n var_eps = fd.ops.sqrt(fd.ops.add(var, s0))\n t0_norm = fd.ops.div(t0_diff, var_eps)\n fd.add_output(t0_norm)\n\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.inner_persistent, inputs\n )\n\n nvf_out = fd.manual_execute(inputs, heuristic_params)\n var, mean = torch.var_mean(inputs[0], dim=-1, correction=0, keepdim=True)\n eager_out = (inputs[0] - mean) / torch.sqrt(var + 1e-6)\n torch.testing.assert_close(eager_out, nvf_out[0])\n\n\ndef test_tutorial_scheduling_layer_norm_with_profiling():\n \"\"\"Test and profile layer norm fusion with manual scheduling.\"\"\"\n\n def _definition_func(fd: FusionDefinition, inputs, tensor_size):\n \"\"\"Define the layer norm fusion operations.\"\"\"\n t0 = fd.from_pytorch(inputs[0])\n s0 = fd.define_scalar(1e-6, dtype=DataType.Double)\n norm_const = fd.define_scalar(tensor_size, dtype=DataType.Int)\n\n mean_cast = fd.ops.cast(t0, dtype=DataType.Float)\n bcast_sum0 = fd.ops.sum(mean_cast, dims=[-1], keepdim=True)\n mean = fd.ops.div(bcast_sum0, norm_const)\n\n var_cast = fd.ops.cast(t0, dtype=DataType.Float)\n diff = fd.ops.sub(var_cast, mean)\n diff_sq = fd.ops.mul(diff, diff)\n bcast_sum1 = fd.ops.sum(diff_sq, dims=[-1], keepdim=True)\n var = fd.ops.div(bcast_sum1, norm_const)\n\n t0_cast = fd.ops.cast(t0, dtype=DataType.Float)\n t0_diff = fd.ops.sub(t0_cast, mean)\n var_eps = fd.ops.sqrt(fd.ops.add(var, s0))\n t0_norm = fd.ops.div(t0_diff, var_eps)\n\n t0_norm_cast = fd.ops.cast(t0_norm, dtype=DataType.BFloat16)\n fd.add_output(t0_norm_cast)\n\n def _schedule_func(fd: FusionDefinition):\n \"\"\"Schedule the layer norm fusion.\"\"\"\n tv_inputs = list(filter(lambda v: v.is_tensor(), fd.fusion.inputs()))\n assert len(tv_inputs) == 1\n\n tv_outputs = list(filter(lambda v: v.is_tensor(), fd.fusion.outputs()))\n assert len(tv_outputs) == 1\n\n # create cache tensors\n cache_after_t0 = tv_inputs[0].cache_after()\n cache_after_t0.set_memory_type(MemoryType.shared)\n\n cache_before_t0_norm = tv_outputs[0].cache_before()\n cache_tvs = [cache_after_t0, cache_before_t0_norm]\n if verbose_:\n print(\"cache input:\\t\", cache_after_t0)\n print(\"cache output:\\t\", cache_before_t0_norm)\n\n # Schedule Reference Tensor\n reference_tv = tv_outputs[0]\n reference_tv.split(-1, 256 * 4)\n reference_tv.split(-1, 4)\n fd.sched.transform_like(reference_tv)\n if verbose_:\n print(\"scheduled reference tensor:\\n\", reference_tv)\n\n # Add rfactor TensorViews\n all_tvs = filter(lambda v: v.is_tensor(), fd.fusion.vals())\n reduction_tvs = list(\n filter(\n lambda tv: any(id.is_reduction() for id in tv.get_logical_domain()),\n all_tvs,\n )\n )\n assert len(reduction_tvs) == 2\n rfactor_tvs = [tv.rfactor([-1]) for tv in reduction_tvs]\n\n # Add common parallelization\n reference_tv.axis(0).parallelize(ParallelType.grid_x)\n reference_tv.axis(-2).parallelize(ParallelType.block_x)\n fd.sched.parallelize_like(reference_tv)\n if verbose_:\n print(\"parallelized reference tensor:\\n\", reference_tv)\n\n # Vectorize input load and output store\n cache_after_t0.axis(-1).parallelize(ParallelType.vectorize)\n tv_outputs[0].axis(-1).parallelize(ParallelType.vectorize)\n if verbose_:\n print(\"vectorized input load:\\n\", cache_after_t0)\n print(\"vectorized output store:\\n\", tv_outputs[0])\n\n # Add computeAt; inline_most automatically skips vectorized iterDomains\n fd.sched.inline_most()\n\n batch_size = 1024\n tensor_size = 4096\n inputs = [\n torch.randn(batch_size, tensor_size, dtype=torch.bfloat16, device=\"cuda\"),\n ]\n\n print(\"\\n\\n===================== Schedule Layer Norm =========================\")\n\n with FusionDefinition() as fd:\n _definition_func(fd, inputs, tensor_size)\n _schedule_func(fd)\n\n with PythonProfiler(auto_scheduled=False) as prof:\n nvf_out = fd.manual_execute(inputs)\n\n torch_out = torch.nn.functional.layer_norm(\n inputs[0], normalized_shape=inputs[0].shape[1:]\n )\n print(\"==================================================================\")\n\n # Change rtol and atol for fp16 dtype\n results_match = torch.allclose(nvf_out[0], torch_out, rtol=1e-2, atol=1e-2)\n assert results_match, \"Nvfuser and PyTorch results do not match!\"\n\n print(\"====================== Profile Kernel =============================\")\n assert len(prof.profile.kernel_profiles) == 1\n kp = prof.profile.kernel_profiles[0]\n\n basic_information = f\"Name: {kp.name}, Schedule: {kp.scheduler}, \\\n Segment id: {kp.segment_id}, Device: {kp.device}, Stream: {kp.stream}\"\n print(basic_information)\n\n kernel_information = f\"Compile time: {kp.compile_time_ms:.2f} ms, \\\n Grid: {kp.grid_str}, Block: {kp.block_str}, Registers: {kp.registers}\"\n print(kernel_information)\n\n runtime_information = f\"Input size: {kp.input_bytes} bytes, \\\n Output size: {kp.output_bytes} bytes, Time: {kp.time_ms:2f} ms\"\n print(runtime_information)\n\n bandwidth_information = f\"Effective Bandwidth: {kp.effective_bandwidth_gbs:.2f} GB/s, \\\n Peak Bandwidth: {kp.percentage_peak_bandwidth:2f}%\"\n print(bandwidth_information)\n print(\"===================================================================\")\n\n # Validate profiler captured kernel info\n assert prof.profile.fusion_id >= 0\n assert len(prof.profile.kernel_profiles) > 0\n assert prof.profile.kernel_profiles[0].scheduler == \"user\"\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_warp_specialized_circular_buffering_pointwise():\n # NOTE: Only a functional test, so high performance is not expected.\n def _definition_func(fd: FusionDefinition, inputs):\n tv0 = fd.from_pytorch(inputs[0])\n tv1 = fd.from_pytorch(inputs[1])\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n def _schedule_func(fd: FusionDefinition):\n # Parameters\n number_of_stages = 4\n prefetch_distance = 1\n bulk_inner_dim = 128\n\n tv_inputs = list(filter(lambda v: v.is_tensor(), fd.fusion.inputs()))","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_warp_specialized_circular_buffering_pointwise","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_warp_specialized_circular_buffering_pointwise#L1806-L1887","kind":"function","name":"test_warp_specialized_circular_buffering_pointwise","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1806,"end_line":1887,"context_start_line":1786,"context_end_line":1907,"code":" print(kernel_information)\n\n runtime_information = f\"Input size: {kp.input_bytes} bytes, \\\n Output size: {kp.output_bytes} bytes, Time: {kp.time_ms:2f} ms\"\n print(runtime_information)\n\n bandwidth_information = f\"Effective Bandwidth: {kp.effective_bandwidth_gbs:.2f} GB/s, \\\n Peak Bandwidth: {kp.percentage_peak_bandwidth:2f}%\"\n print(bandwidth_information)\n print(\"===================================================================\")\n\n # Validate profiler captured kernel info\n assert prof.profile.fusion_id >= 0\n assert len(prof.profile.kernel_profiles) > 0\n assert prof.profile.kernel_profiles[0].scheduler == \"user\"\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_warp_specialized_circular_buffering_pointwise():\n # NOTE: Only a functional test, so high performance is not expected.\n def _definition_func(fd: FusionDefinition, inputs):\n tv0 = fd.from_pytorch(inputs[0])\n tv1 = fd.from_pytorch(inputs[1])\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n def _schedule_func(fd: FusionDefinition):\n # Parameters\n number_of_stages = 4\n prefetch_distance = 1\n bulk_inner_dim = 128\n\n tv_inputs = list(filter(lambda v: v.is_tensor(), fd.fusion.inputs()))\n assert len(tv_inputs) == 2\n tv0, tv1 = tv_inputs\n\n # Use TMA to load TV0 into shared memory\n tv3 = tv0.cache_after(LoadStoreOpType.tma)\n tv3.set_memory_type(MemoryType.shared)\n\n tv4 = tv1.cache_after(LoadStoreOpType.tma)\n tv4.set_memory_type(MemoryType.shared)\n\n tv_outputs = list(filter(lambda v: v.is_tensor(), fd.fusion.outputs()))\n assert len(tv_outputs) == 1\n reference = tv_outputs[0]\n\n # [M, N] -> [M, N/bid, bid]\n reference.split(-1, bulk_inner_dim)\n fd.sched.transform_like(reference)\n\n tv3.axis(0).parallelize(ParallelType.grid_x)\n tv4.axis(0).parallelize(ParallelType.grid_x)\n\n # Set computeAt position for circular buffering pipelining\n # The circular buffer axis is the first serial iterDomain to the left\n # of computeAt position. The domain is [M [BIDx], N/bid, bid], so the\n # circular buffer iterDomain is N/bid for computeAt position 2.\n fd.sched.inline_at(reference, pos=2)\n\n # Circular Buffer with TMA loads\n tv3.axis(2).parallelize(ParallelType.tma)\n tv4.axis(2).parallelize(ParallelType.tma)\n fd.sched.warp_specialize(\n tv3, number_of_stages, prefetch_distance, ParallelType.block_y\n )\n fd.sched.warp_specialize(\n tv4, number_of_stages, prefetch_distance, ParallelType.block_y\n )\n\n # Split reference to parallelize TMA tile\n reference.split(-1, bulk_inner_dim)\n reference.axis(0).parallelize(ParallelType.grid_x)\n reference.axis(-1).parallelize(ParallelType.block_x)\n\n # Inputs\n tensor_outer_dim = 128\n tensor_inner_dim = 1024\n t0 = torch.randn(\n tensor_outer_dim,\n tensor_inner_dim,\n dtype=torch.float,\n device=torch.device(\"cuda:0\"),\n )\n t1 = torch.randn(\n tensor_outer_dim,\n tensor_inner_dim,\n dtype=torch.float,\n device=torch.device(\"cuda:0\"),\n )\n inputs = [t0, t1]\n\n with FusionDefinition() as fd:\n _definition_func(fd, inputs)\n _schedule_func(fd)\n\n outputs = fd.manual_execute(inputs)\n warp_specialization_if_stmt = \"if ((((nvfuser_index_t)threadIdx.y) >= 1LL)) {\"\n assert warp_specialization_if_stmt in fd.fusion.print_kernel()\n assert torch.allclose(outputs[0], t0 + t1)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_pdl():\n def nvf_fused_add_rmsnorm(fd: FusionDefinition, input_shape, weight_shape, eps):\n \"\"\"\n Fused add root mean square normalization.\n * a [num_tokens, hidden_size]\n * residual [num_tokens, hidden_size]\n * weight [hidden_size]\n return rmsnorm(a + residual)\n \"\"\"\n normalization_axis = -1\n keepdim = True\n a = fd.define_tensor(\n shape=input_shape,\n contiguity=[None, True],\n dtype=DataType.BFloat16,","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.test_pdl","uri":"program://Fuser/function/tests.python.direct.test_tutorial.test_pdl#L1893-L2005","kind":"function","name":"test_pdl","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1893,"end_line":2005,"context_start_line":1873,"context_end_line":2005,"code":" tensor_outer_dim,\n tensor_inner_dim,\n dtype=torch.float,\n device=torch.device(\"cuda:0\"),\n )\n inputs = [t0, t1]\n\n with FusionDefinition() as fd:\n _definition_func(fd, inputs)\n _schedule_func(fd)\n\n outputs = fd.manual_execute(inputs)\n warp_specialization_if_stmt = \"if ((((nvfuser_index_t)threadIdx.y) >= 1LL)) {\"\n assert warp_specialization_if_stmt in fd.fusion.print_kernel()\n assert torch.allclose(outputs[0], t0 + t1)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_pdl():\n def nvf_fused_add_rmsnorm(fd: FusionDefinition, input_shape, weight_shape, eps):\n \"\"\"\n Fused add root mean square normalization.\n * a [num_tokens, hidden_size]\n * residual [num_tokens, hidden_size]\n * weight [hidden_size]\n return rmsnorm(a + residual)\n \"\"\"\n normalization_axis = -1\n keepdim = True\n a = fd.define_tensor(\n shape=input_shape,\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n )\n residual = fd.define_tensor(\n shape=input_shape,\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n )\n weights = fd.define_tensor(\n shape=weight_shape,\n contiguity=[True],\n dtype=DataType.BFloat16,\n )\n norm_const = fd.define_scalar(input_shape[normalization_axis])\n eps_const = fd.define_scalar(eps)\n\n rmsnorm_input = fd.ops.add(a, residual)\n rmsnorm_input_sq = fd.ops.mul(rmsnorm_input, rmsnorm_input)\n sum0 = fd.ops.sum(rmsnorm_input_sq, dims=[normalization_axis], keepdim=keepdim)\n var = fd.ops.div(sum0, norm_const)\n var_eps = fd.ops.add(var, eps_const)\n invstd = fd.ops.rsqrt(var_eps)\n pre_scale = fd.ops.mul(rmsnorm_input, invstd)\n weights_bcast = fd.ops.broadcast_in_dim(\n weights, shape=input_shape, broadcast_dims=[1]\n )\n out = fd.ops.mul(pre_scale, weights_bcast)\n out_bf16 = fd.ops.cast(out, dtype=DataType.BFloat16)\n # NOTE alias_input does not check if output and alias_input have the same type\n fd.add_output(out_bf16, alias_input=a)\n\n def fused_add_rmsnorm(hidden_states, residual, weight, eps):\n inputs = [hidden_states, residual, weight]\n with FusionDefinition() as fd:\n nvf_fused_add_rmsnorm(\n fd,\n input_shape=hidden_states.shape,\n weight_shape=weight.shape,\n eps=eps,\n )\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.inner_persistent, inputs\n )\n fd.manual_execute(inputs, heuristic_params)\n assert fd.ke.is_programmatic_dependent_launch_enabled()\n\n def nvfuser(hidden_states, residual, layer, eps):\n fused_add_rmsnorm(hidden_states, residual, layer[\"post_attn_norm\"], eps)\n router_logits = F.linear(\n hidden_states, layer[\"router_weight\"], layer[\"router_bias\"]\n )\n return hidden_states\n\n def baseline(hidden_states, residual, layer, eps, use_pdl):\n hidden_states += residual\n hidden_states = F.rms_norm(\n hidden_states, [hidden_states.shape[-1]], layer[\"post_attn_norm\"], eps\n )\n router_logits = F.linear(\n hidden_states, layer[\"router_weight\"], layer[\"router_bias\"]\n )\n return hidden_states\n\n device = \"cuda\"\n dtype = torch.bfloat16\n num_tokens = 1 # decode phase: 1 token per sequence\n hidden_size = 2880\n num_experts = 32\n eps = 1e-6 # rms_norm_eps\n\n layer = {\n \"post_attn_norm\": torch.randn(\n hidden_size, dtype=dtype, device=device\n ).contiguous(),\n \"router_weight\": torch.randn(\n num_experts, hidden_size, dtype=dtype, device=device\n ).contiguous(),\n \"router_bias\": torch.randn(\n num_experts, dtype=dtype, device=device\n ).contiguous(),\n }\n\n # ========== Static tensors for CUDA graph capture ==========\n static_hidden_states = torch.randn(\n num_tokens, hidden_size, dtype=dtype, device=device\n ).contiguous()\n static_residual = torch.randn(\n num_tokens, hidden_size, dtype=dtype, device=device\n ).contiguous()\n\n baseline_result = baseline(\n static_hidden_states.clone().detach(),\n static_residual.clone().detach(),\n layer,\n eps,\n use_pdl=True,\n )\n nvf_result = nvfuser(static_hidden_states, static_residual, layer, eps)\n assert torch.allclose(nvf_result, baseline_result, rtol=1e-2, atol=1e-2)","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.inner_fn","uri":"program://Fuser/function/tests.python.direct.test_tutorial.inner_fn#L52-L81","kind":"function","name":"inner_fn","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":52,"end_line":81,"context_start_line":32,"context_end_line":101,"code":"\nverbose_ = True\n\n\n# A helper function to test heuristic schedulers with automatic scheduling\ndef check_auto_schedule(schedule_fn):\n \"\"\"\n A decorator to validate a schedule_fn before applying it to a fusion.\n\n Args:\n schedule_fn: The function to apply the scheduler\n \"\"\"\n # List of all scheduler heuristics for testing\n # NOTE We cannot iterate pybind11 enum directly, so we extract the entries here.\n all_scheduler_heuristics = [\n heuristic\n for heuristic, _ in SchedulerType.__entries.values()\n if not SchedulerType.none\n ]\n\n def inner_fn(fusion, selected_heuristic, inputs):\n \"\"\"\n Helper function to validate a schedule_fn.\n\n Args:\n fusion: The Fusion object to schedule\n selected_heuristic: The SchedulerType expected to work\n inputs: Input tensors for the fusion\n \"\"\"\n available_heuristics = schedule.find_compatible_schedulers(fusion, inputs)\n\n # Assume that only a single heuristic is available for fusion\n assert len(available_heuristics) == 1\n\n # Check that only selected heuristic is available as a scheduler\n assert set(available_heuristics) == set([selected_heuristic])\n\n # Double-check with can_schedule\n status, _ = schedule.can_schedule(fusion, selected_heuristic, inputs)\n assert status\n\n # Check that the other schedulers are not compatible with this fusion\n assert all(\n [\n not schedule.can_schedule(fusion, h, inputs)[0]\n for h in all_scheduler_heuristics\n if h is not selected_heuristic\n ]\n )\n return schedule_fn(fusion, selected_heuristic, inputs)\n\n return inner_fn\n\n\ndef test_tutorial_memcpy():\n # First, we define a fusion. A common pattern is:\n # - Declare a Fusion, which works as a container of expressions using\n # with context manager.\n # - Setup inputs. fd.define_tensor can be used to manually create tensors.\n # fd.from_pytorch will create a TensorView given a pytorch tensor. Fusion\n # registration is automatic.\n # - Define operations with the registered inputs.\n # For supported operations, run:\n # >>> import nvfuser_direct\n # >>> fd = nvfuser_direct.FusionDefinition()\n # >>> help(fd.ops)\n # - Most of operations that take tensors as inputs produce tensors\n # as outputs, which can then be used as inputs to another\n # operations.\n # - Final outputs should be set as fusion outputs with fd.add_output","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.fusion_func","uri":"program://Fuser/function/tests.python.direct.test_tutorial.fusion_func#L311-L315","kind":"function","name":"fusion_func","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":311,"end_line":315,"context_start_line":291,"context_end_line":335,"code":" with FusionDefinition() as fd3:\n ref_tv = fusion_func(fd3)\n\n # We can of course mix BIDx and TIDx.\n ref_tv.axis(0).parallelize(ParallelType.grid_x)\n ref_tv.axis(1).parallelize(ParallelType.block_x)\n\n if verbose_:\n print(fd3.fusion.print_math())\n print(fd3.fusion.print_kernel())\n\n # The original input should not fail in this case. The kernel will be\n # launched with 10 thread blocks, each of which has 1024 threads. Try\n # running this test with NVFUSER_DUMP=launch_param to see the launch\n # configuration of each kernel lauch\n fd3.manual_validate([t0], [ref])\n\n\ndef test_tutorial_reduction_rfactor():\n # Just a very simple reduction of 1D tensor\n def fusion_func(fd: FusionDefinition) -> TensorView:\n tv0 = fd.define_tensor(shape=[-1])\n tv1 = fd.ops.sum(tv0, dims=[0])\n fd.add_output(tv1)\n return tv1\n\n # Create separate fusions because of multiple schedules\n with FusionDefinition() as fd0:\n tv1 = fusion_func(fd0)\n\n # A common pattern of reductions in CUDA involves multiple steps of\n # reductions, where the first step is a per-thread local reduction,\n # followed by a block reduction of the per-thread partial results,\n # and also potentially followed by a grid reduction of the\n # per-block partial results. Here's an example with a two-step\n # reduction:\n #\n # // Step 1: Per-thread reduction\n # float partial_result = 0;\n # for (int i = threadIdx.x; i += blockDim.x; i < N) {\n # partial_result += input[i];\n # }\n #\n # // Step 2: Accumulation within each thread block\n # __shared__ float shared_buf[blockDim.x];","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial._definition_func","uri":"program://Fuser/function/tests.python.direct.test_tutorial._definition_func#L1808-L1812","kind":"function","name":"_definition_func","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1808,"end_line":1812,"context_start_line":1788,"context_end_line":1832,"code":" runtime_information = f\"Input size: {kp.input_bytes} bytes, \\\n Output size: {kp.output_bytes} bytes, Time: {kp.time_ms:2f} ms\"\n print(runtime_information)\n\n bandwidth_information = f\"Effective Bandwidth: {kp.effective_bandwidth_gbs:.2f} GB/s, \\\n Peak Bandwidth: {kp.percentage_peak_bandwidth:2f}%\"\n print(bandwidth_information)\n print(\"===================================================================\")\n\n # Validate profiler captured kernel info\n assert prof.profile.fusion_id >= 0\n assert len(prof.profile.kernel_profiles) > 0\n assert prof.profile.kernel_profiles[0].scheduler == \"user\"\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_warp_specialized_circular_buffering_pointwise():\n # NOTE: Only a functional test, so high performance is not expected.\n def _definition_func(fd: FusionDefinition, inputs):\n tv0 = fd.from_pytorch(inputs[0])\n tv1 = fd.from_pytorch(inputs[1])\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n def _schedule_func(fd: FusionDefinition):\n # Parameters\n number_of_stages = 4\n prefetch_distance = 1\n bulk_inner_dim = 128\n\n tv_inputs = list(filter(lambda v: v.is_tensor(), fd.fusion.inputs()))\n assert len(tv_inputs) == 2\n tv0, tv1 = tv_inputs\n\n # Use TMA to load TV0 into shared memory\n tv3 = tv0.cache_after(LoadStoreOpType.tma)\n tv3.set_memory_type(MemoryType.shared)\n\n tv4 = tv1.cache_after(LoadStoreOpType.tma)\n tv4.set_memory_type(MemoryType.shared)\n\n tv_outputs = list(filter(lambda v: v.is_tensor(), fd.fusion.outputs()))\n assert len(tv_outputs) == 1","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial._schedule_func","uri":"program://Fuser/function/tests.python.direct.test_tutorial._schedule_func#L1814-L1861","kind":"function","name":"_schedule_func","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1814,"end_line":1861,"context_start_line":1794,"context_end_line":1881,"code":" print(bandwidth_information)\n print(\"===================================================================\")\n\n # Validate profiler captured kernel info\n assert prof.profile.fusion_id >= 0\n assert len(prof.profile.kernel_profiles) > 0\n assert prof.profile.kernel_profiles[0].scheduler == \"user\"\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_warp_specialized_circular_buffering_pointwise():\n # NOTE: Only a functional test, so high performance is not expected.\n def _definition_func(fd: FusionDefinition, inputs):\n tv0 = fd.from_pytorch(inputs[0])\n tv1 = fd.from_pytorch(inputs[1])\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n def _schedule_func(fd: FusionDefinition):\n # Parameters\n number_of_stages = 4\n prefetch_distance = 1\n bulk_inner_dim = 128\n\n tv_inputs = list(filter(lambda v: v.is_tensor(), fd.fusion.inputs()))\n assert len(tv_inputs) == 2\n tv0, tv1 = tv_inputs\n\n # Use TMA to load TV0 into shared memory\n tv3 = tv0.cache_after(LoadStoreOpType.tma)\n tv3.set_memory_type(MemoryType.shared)\n\n tv4 = tv1.cache_after(LoadStoreOpType.tma)\n tv4.set_memory_type(MemoryType.shared)\n\n tv_outputs = list(filter(lambda v: v.is_tensor(), fd.fusion.outputs()))\n assert len(tv_outputs) == 1\n reference = tv_outputs[0]\n\n # [M, N] -> [M, N/bid, bid]\n reference.split(-1, bulk_inner_dim)\n fd.sched.transform_like(reference)\n\n tv3.axis(0).parallelize(ParallelType.grid_x)\n tv4.axis(0).parallelize(ParallelType.grid_x)\n\n # Set computeAt position for circular buffering pipelining\n # The circular buffer axis is the first serial iterDomain to the left\n # of computeAt position. The domain is [M [BIDx], N/bid, bid], so the\n # circular buffer iterDomain is N/bid for computeAt position 2.\n fd.sched.inline_at(reference, pos=2)\n\n # Circular Buffer with TMA loads\n tv3.axis(2).parallelize(ParallelType.tma)\n tv4.axis(2).parallelize(ParallelType.tma)\n fd.sched.warp_specialize(\n tv3, number_of_stages, prefetch_distance, ParallelType.block_y\n )\n fd.sched.warp_specialize(\n tv4, number_of_stages, prefetch_distance, ParallelType.block_y\n )\n\n # Split reference to parallelize TMA tile\n reference.split(-1, bulk_inner_dim)\n reference.axis(0).parallelize(ParallelType.grid_x)\n reference.axis(-1).parallelize(ParallelType.block_x)\n\n # Inputs\n tensor_outer_dim = 128\n tensor_inner_dim = 1024\n t0 = torch.randn(\n tensor_outer_dim,\n tensor_inner_dim,\n dtype=torch.float,\n device=torch.device(\"cuda:0\"),\n )\n t1 = torch.randn(\n tensor_outer_dim,\n tensor_inner_dim,\n dtype=torch.float,\n device=torch.device(\"cuda:0\"),\n )\n inputs = [t0, t1]\n\n with FusionDefinition() as fd:\n _definition_func(fd, inputs)","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.nvf_fused_add_rmsnorm","uri":"program://Fuser/function/tests.python.direct.test_tutorial.nvf_fused_add_rmsnorm#L1894-L1935","kind":"function","name":"nvf_fused_add_rmsnorm","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1894,"end_line":1935,"context_start_line":1874,"context_end_line":1955,"code":" tensor_inner_dim,\n dtype=torch.float,\n device=torch.device(\"cuda:0\"),\n )\n inputs = [t0, t1]\n\n with FusionDefinition() as fd:\n _definition_func(fd, inputs)\n _schedule_func(fd)\n\n outputs = fd.manual_execute(inputs)\n warp_specialization_if_stmt = \"if ((((nvfuser_index_t)threadIdx.y) >= 1LL)) {\"\n assert warp_specialization_if_stmt in fd.fusion.print_kernel()\n assert torch.allclose(outputs[0], t0 + t1)\n\n\n@pytest.mark.skipif(\n is_pre_hopper(), reason=\"Only supported on Hopper and newer devices.\"\n)\ndef test_pdl():\n def nvf_fused_add_rmsnorm(fd: FusionDefinition, input_shape, weight_shape, eps):\n \"\"\"\n Fused add root mean square normalization.\n * a [num_tokens, hidden_size]\n * residual [num_tokens, hidden_size]\n * weight [hidden_size]\n return rmsnorm(a + residual)\n \"\"\"\n normalization_axis = -1\n keepdim = True\n a = fd.define_tensor(\n shape=input_shape,\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n )\n residual = fd.define_tensor(\n shape=input_shape,\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n )\n weights = fd.define_tensor(\n shape=weight_shape,\n contiguity=[True],\n dtype=DataType.BFloat16,\n )\n norm_const = fd.define_scalar(input_shape[normalization_axis])\n eps_const = fd.define_scalar(eps)\n\n rmsnorm_input = fd.ops.add(a, residual)\n rmsnorm_input_sq = fd.ops.mul(rmsnorm_input, rmsnorm_input)\n sum0 = fd.ops.sum(rmsnorm_input_sq, dims=[normalization_axis], keepdim=keepdim)\n var = fd.ops.div(sum0, norm_const)\n var_eps = fd.ops.add(var, eps_const)\n invstd = fd.ops.rsqrt(var_eps)\n pre_scale = fd.ops.mul(rmsnorm_input, invstd)\n weights_bcast = fd.ops.broadcast_in_dim(\n weights, shape=input_shape, broadcast_dims=[1]\n )\n out = fd.ops.mul(pre_scale, weights_bcast)\n out_bf16 = fd.ops.cast(out, dtype=DataType.BFloat16)\n # NOTE alias_input does not check if output and alias_input have the same type\n fd.add_output(out_bf16, alias_input=a)\n\n def fused_add_rmsnorm(hidden_states, residual, weight, eps):\n inputs = [hidden_states, residual, weight]\n with FusionDefinition() as fd:\n nvf_fused_add_rmsnorm(\n fd,\n input_shape=hidden_states.shape,\n weight_shape=weight.shape,\n eps=eps,\n )\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.inner_persistent, inputs\n )\n fd.manual_execute(inputs, heuristic_params)\n assert fd.ke.is_programmatic_dependent_launch_enabled()\n\n def nvfuser(hidden_states, residual, layer, eps):\n fused_add_rmsnorm(hidden_states, residual, layer[\"post_attn_norm\"], eps)\n router_logits = F.linear(","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.fused_add_rmsnorm","uri":"program://Fuser/function/tests.python.direct.test_tutorial.fused_add_rmsnorm#L1937-L1951","kind":"function","name":"fused_add_rmsnorm","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1937,"end_line":1951,"context_start_line":1917,"context_end_line":1971,"code":" dtype=DataType.BFloat16,\n )\n norm_const = fd.define_scalar(input_shape[normalization_axis])\n eps_const = fd.define_scalar(eps)\n\n rmsnorm_input = fd.ops.add(a, residual)\n rmsnorm_input_sq = fd.ops.mul(rmsnorm_input, rmsnorm_input)\n sum0 = fd.ops.sum(rmsnorm_input_sq, dims=[normalization_axis], keepdim=keepdim)\n var = fd.ops.div(sum0, norm_const)\n var_eps = fd.ops.add(var, eps_const)\n invstd = fd.ops.rsqrt(var_eps)\n pre_scale = fd.ops.mul(rmsnorm_input, invstd)\n weights_bcast = fd.ops.broadcast_in_dim(\n weights, shape=input_shape, broadcast_dims=[1]\n )\n out = fd.ops.mul(pre_scale, weights_bcast)\n out_bf16 = fd.ops.cast(out, dtype=DataType.BFloat16)\n # NOTE alias_input does not check if output and alias_input have the same type\n fd.add_output(out_bf16, alias_input=a)\n\n def fused_add_rmsnorm(hidden_states, residual, weight, eps):\n inputs = [hidden_states, residual, weight]\n with FusionDefinition() as fd:\n nvf_fused_add_rmsnorm(\n fd,\n input_shape=hidden_states.shape,\n weight_shape=weight.shape,\n eps=eps,\n )\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.inner_persistent, inputs\n )\n fd.manual_execute(inputs, heuristic_params)\n assert fd.ke.is_programmatic_dependent_launch_enabled()\n\n def nvfuser(hidden_states, residual, layer, eps):\n fused_add_rmsnorm(hidden_states, residual, layer[\"post_attn_norm\"], eps)\n router_logits = F.linear(\n hidden_states, layer[\"router_weight\"], layer[\"router_bias\"]\n )\n return hidden_states\n\n def baseline(hidden_states, residual, layer, eps, use_pdl):\n hidden_states += residual\n hidden_states = F.rms_norm(\n hidden_states, [hidden_states.shape[-1]], layer[\"post_attn_norm\"], eps\n )\n router_logits = F.linear(\n hidden_states, layer[\"router_weight\"], layer[\"router_bias\"]\n )\n return hidden_states\n\n device = \"cuda\"\n dtype = torch.bfloat16","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.nvfuser","uri":"program://Fuser/function/tests.python.direct.test_tutorial.nvfuser#L1953-L1958","kind":"function","name":"nvfuser","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1953,"end_line":1958,"context_start_line":1933,"context_end_line":1978,"code":" out_bf16 = fd.ops.cast(out, dtype=DataType.BFloat16)\n # NOTE alias_input does not check if output and alias_input have the same type\n fd.add_output(out_bf16, alias_input=a)\n\n def fused_add_rmsnorm(hidden_states, residual, weight, eps):\n inputs = [hidden_states, residual, weight]\n with FusionDefinition() as fd:\n nvf_fused_add_rmsnorm(\n fd,\n input_shape=hidden_states.shape,\n weight_shape=weight.shape,\n eps=eps,\n )\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.inner_persistent, inputs\n )\n fd.manual_execute(inputs, heuristic_params)\n assert fd.ke.is_programmatic_dependent_launch_enabled()\n\n def nvfuser(hidden_states, residual, layer, eps):\n fused_add_rmsnorm(hidden_states, residual, layer[\"post_attn_norm\"], eps)\n router_logits = F.linear(\n hidden_states, layer[\"router_weight\"], layer[\"router_bias\"]\n )\n return hidden_states\n\n def baseline(hidden_states, residual, layer, eps, use_pdl):\n hidden_states += residual\n hidden_states = F.rms_norm(\n hidden_states, [hidden_states.shape[-1]], layer[\"post_attn_norm\"], eps\n )\n router_logits = F.linear(\n hidden_states, layer[\"router_weight\"], layer[\"router_bias\"]\n )\n return hidden_states\n\n device = \"cuda\"\n dtype = torch.bfloat16\n num_tokens = 1 # decode phase: 1 token per sequence\n hidden_size = 2880\n num_experts = 32\n eps = 1e-6 # rms_norm_eps\n\n layer = {\n \"post_attn_norm\": torch.randn(","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_tutorial.baseline","uri":"program://Fuser/function/tests.python.direct.test_tutorial.baseline#L1960-L1968","kind":"function","name":"baseline","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1960,"end_line":1968,"context_start_line":1940,"context_end_line":1988,"code":" nvf_fused_add_rmsnorm(\n fd,\n input_shape=hidden_states.shape,\n weight_shape=weight.shape,\n eps=eps,\n )\n # Apply selected scheduler\n heuristic_params = check_auto_schedule(schedule.schedule)(\n fd.fusion, SchedulerType.inner_persistent, inputs\n )\n fd.manual_execute(inputs, heuristic_params)\n assert fd.ke.is_programmatic_dependent_launch_enabled()\n\n def nvfuser(hidden_states, residual, layer, eps):\n fused_add_rmsnorm(hidden_states, residual, layer[\"post_attn_norm\"], eps)\n router_logits = F.linear(\n hidden_states, layer[\"router_weight\"], layer[\"router_bias\"]\n )\n return hidden_states\n\n def baseline(hidden_states, residual, layer, eps, use_pdl):\n hidden_states += residual\n hidden_states = F.rms_norm(\n hidden_states, [hidden_states.shape[-1]], layer[\"post_attn_norm\"], eps\n )\n router_logits = F.linear(\n hidden_states, layer[\"router_weight\"], layer[\"router_bias\"]\n )\n return hidden_states\n\n device = \"cuda\"\n dtype = torch.bfloat16\n num_tokens = 1 # decode phase: 1 token per sequence\n hidden_size = 2880\n num_experts = 32\n eps = 1e-6 # rms_norm_eps\n\n layer = {\n \"post_attn_norm\": torch.randn(\n hidden_size, dtype=dtype, device=device\n ).contiguous(),\n \"router_weight\": torch.randn(\n num_experts, hidden_size, dtype=dtype, device=device\n ).contiguous(),\n \"router_bias\": torch.randn(\n num_experts, dtype=dtype, device=device\n ).contiguous(),\n }\n","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_nvfp4_gemm","uri":"program://Fuser/module/tests.python.direct.test_cutlass_nvfp4_gemm#L1-L281","kind":"module","name":"tests.python.direct.test_cutlass_nvfp4_gemm","path":"tests/python/direct/test_cutlass_nvfp4_gemm.py","language":"python","start_line":1,"end_line":281,"context_start_line":1,"context_end_line":281,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom nvfuser_direct import nvf_cutlass\nfrom python.direct_utils import microarchitecture_is\n\nif not microarchitecture_is(10, 0):\n pytest.skip(\n reason=\"Nvfp4 Requires compute capability 10.0, other arches are not tested.\",\n allow_module_level=True,\n )\n\nfrom python.direct_utils import (\n FLOAT4_E2M1_MAX,\n FLOAT8_E4M3_MAX,\n dequantize_to_dtype,\n linear_to_swizzled_128_4,\n pytorch_nvfp4_quantize,\n round_up,\n activation_scale_to_nvfp4,\n fp4_to_fp32,\n unpack_fp4,\n)\n\n\ndef get_ref_results(\n a_fp4,\n b_fp4,\n a_sf,\n b_sf,\n a_global_scale,\n b_global_scale,\n m,\n n,\n dtype,\n block_size,\n device,\n):\n _, m_k = a_fp4.shape\n _, n_k = b_fp4.shape\n assert m_k == n_k\n a_in_dtype = dequantize_to_dtype(\n a_fp4, a_sf, a_global_scale, dtype=dtype, device=device, block_size=block_size\n )\n b_in_dtype = dequantize_to_dtype(\n b_fp4, b_sf, b_global_scale, dtype=dtype, device=device, block_size=block_size\n )\n return torch.matmul(a_in_dtype, b_in_dtype.t())\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(\n \"shape\", [(128, 128, 64), (128, 128, 128), (256, 128, 64), (128, 256, 128)]\n)\n@torch.inference_mode()\ndef test_nvfp4_gemm(\n dtype: torch.dtype,\n shape: tuple[int, int, int],\n) -> None:\n m, n, packed_k = shape\n k = packed_k * 2\n block_size = 16\n a_dtype = torch.randn((m, k), dtype=dtype, device=\"cuda\")\n b_dtype = torch.randn((n, k), dtype=dtype, device=\"cuda\")\n\n a_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(a_dtype.flatten(), dim=-1)\n ).to(torch.float32)\n b_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(b_dtype.flatten(), dim=-1)\n ).to(torch.float32)\n alpha = 1.0 / (a_global_scale * b_global_scale)\n\n a_fp4, a_scale_linear = pytorch_nvfp4_quantize(a_dtype, a_global_scale)\n b_fp4, b_scale_linear = pytorch_nvfp4_quantize(b_dtype, b_global_scale)\n a_scale_interleaved = linear_to_swizzled_128_4(a_scale_linear)\n b_scale_interleaved = linear_to_swizzled_128_4(b_scale_linear)\n\n expected_out = get_ref_results(\n a_fp4,\n b_fp4,\n a_scale_interleaved,\n b_scale_interleaved,\n a_global_scale,\n b_global_scale,\n m,\n n,\n dtype,\n block_size,\n \"cuda\",\n )\n out = nvf_cutlass.nvfp4_scaled_mm(\n a_fp4, b_fp4, a_scale_interleaved, b_scale_interleaved, alpha, dtype\n )\n\n torch.testing.assert_close(out, expected_out.to(dtype=dtype), atol=1e-1, rtol=1e-1)\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(\n \"shape\", [(128, 128, 64), (128, 128, 128), (256, 128, 64), (128, 256, 128)]\n)\n@torch.inference_mode()\ndef test_nvfp4_gemm_epilogue(\n dtype: torch.dtype,\n shape: tuple[int, int, int],\n) -> None:\n m, n, packed_k = shape\n k = packed_k * 2\n block_size = 16\n a_dtype = torch.randn((m, k), dtype=dtype, device=\"cuda\")\n b_dtype = torch.randn((n, k), dtype=dtype, device=\"cuda\")\n\n a_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(a_dtype.flatten(), dim=-1)\n ).to(torch.float32)\n b_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(b_dtype.flatten(), dim=-1)\n ).to(torch.float32)\n alpha = 1.0 / (a_global_scale * b_global_scale)\n global_normconst = torch.tensor(2, dtype=torch.float, device=\"cuda\")\n\n a_fp4, a_scale_linear = pytorch_nvfp4_quantize(a_dtype, a_global_scale)\n b_fp4, b_scale_linear = pytorch_nvfp4_quantize(b_dtype, b_global_scale)\n a_scale_interleaved = linear_to_swizzled_128_4(a_scale_linear)\n b_scale_interleaved = linear_to_swizzled_128_4(b_scale_linear)\n\n expected_out = get_ref_results(\n a_fp4,\n b_fp4,\n a_scale_interleaved,\n b_scale_interleaved,\n a_global_scale,\n b_global_scale,\n m,\n n,\n dtype,\n block_size,\n \"cuda\",\n )\n\n expected_out_fp4, expected_out_scale_linear = pytorch_nvfp4_quantize(\n expected_out, global_normconst\n )\n expected_out_scale_interleaved = linear_to_swizzled_128_4(expected_out_scale_linear)\n\n out_fp4, out_scale_interleaved = nvf_cutlass.nvfp4_scaled_mm_blockscale(\n a_fp4, b_fp4, a_scale_interleaved, b_scale_interleaved, alpha, global_normconst\n )\n\n # Convert to unpacked fp32 to check nvfp4 tensors.\n expected_out_fp32 = fp4_to_fp32(unpack_fp4(expected_out_fp4.view(torch.uint8)))\n out_fp32 = fp4_to_fp32(unpack_fp4(out_fp4.view(torch.uint8)))\n\n # The absolute max difference is 2.0.\n abs_diff = torch.abs(expected_out_fp32 - out_fp32)\n assert torch.max(abs_diff) <= 2.0\n\n # The percentage of mismatched values is 1%.\n nonzero = torch.count_nonzero(torch.ne(abs_diff, 0.0))\n assert (nonzero / abs_diff.numel()) < 0.1\n\n # Compare scale factors\n # rtol = epsilon = 2**(-3) for fp8_m4e3\n # atol = 2**(num_exponent_bits + smallest_exponent_value)\n torch.testing.assert_close(\n out_scale_interleaved.to(torch.float),\n expected_out_scale_interleaved.to(torch.float),\n atol=2e-3,\n rtol=0.125,\n )\n\n\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16, torch.float16])\ndef test_nvfp4_grouped_mm(\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n nvfp4_block_size = 16\n\n # k dimension is multiple of 128 to avoid padding\n m, n, k = config\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1 = torch.testing.make_tensor((m, k), dtype=torch.float32, device=\"cuda:0\")\n mat2 = torch.testing.make_tensor((g, n, k), dtype=torch.float32, device=\"cuda:0\")\n ab_strides = torch.full((g,), k, dtype=torch.int64, device=\"cuda:0\")\n c_strides = torch.full((g,), n, dtype=torch.int64, device=\"cuda:0\")\n\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n blockscale_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n mat2_gs = torch.empty((g,), dtype=torch.float32, device=\"cuda:0\")\n scale2 = torch.empty(\n (g, n, k // nvfp4_block_size), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n\n accumulated_tokens = 0\n rounded_accumulated_tokens = 0\n mat2_fp4 = torch.empty(\n (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n # Use tokens_per_expert to calculate offsets into m dimension of input tensor.\n # The blockscale offset per expert is rounded to 128 to match the alignment\n # requirements for blockscale factor.\n for i in range(g):\n mat2_gs[i] = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2[i].max()\n offsets[i] = accumulated_tokens\n blockscale_offsets[i] = rounded_accumulated_tokens\n accumulated_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_accumulated_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n mat2_fp4_i, mat2_sf_i = pytorch_nvfp4_quantize(mat2[i], mat2_gs[i])\n mat2_fp4[i] = mat2_fp4_i\n scale2[i] = linear_to_swizzled_128_4(mat2_sf_i)\n\n # prepare quantization for mat1\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")\n mat1_fp4, scale1 = activation_scale_to_nvfp4(\n mat1, mat1_gs, offsets, blockscale_offsets, nvfp4_block_size\n )\n\n out = nvf_cutlass.nvfp4_scaled_grouped_mm(\n mat1_fp4,\n mat2_fp4,\n scale1,\n scale2,\n mat2_gs,\n ab_strides,\n c_strides,\n problem_sizes,\n offsets,\n blockscale_offsets,\n out_dtype,\n )\n\n # Create pytorch expected output reference\n # For each expert, apply nvfp4 gemm. Slice the input matrix given the tokens_per_expert.\n # C[start:stop] = A[start:stop] @ B[expert].\n out_decomposed_ref = torch.empty(m, n, dtype=out_dtype, device=\"cuda:0\")\n for i in range(g):\n l = offsets[i]\n l_sf = blockscale_offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n r_sf = round_up(tokens_per_expert[i], 128) + l_sf\n # A cublas invalid value error occurs when passing in mat2_gs[i] as\n # alpha in the torch kernel.\n out_decomposed_ref[l:r] = (\n torch._scaled_mm(\n mat1_fp4[l:r],\n mat2_fp4[i].transpose(-1, -2),\n scale1[l_sf:r_sf],\n scale2[i],\n None,\n None,\n out_dtype,\n )\n * mat2_gs[i]\n )\n\n torch.testing.assert_close(out_decomposed_ref, out, atol=1e-2, rtol=1e-2)","source_hash":"11120d40e8965626932725fad0e2e4222686aa63290220b5f25cce499ae7eb55","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_nvfp4_gemm.get_ref_results","uri":"program://Fuser/function/tests.python.direct.test_cutlass_nvfp4_gemm.get_ref_results#L30-L52","kind":"function","name":"get_ref_results","path":"tests/python/direct/test_cutlass_nvfp4_gemm.py","language":"python","start_line":30,"end_line":52,"context_start_line":10,"context_end_line":72,"code":"\nif not microarchitecture_is(10, 0):\n pytest.skip(\n reason=\"Nvfp4 Requires compute capability 10.0, other arches are not tested.\",\n allow_module_level=True,\n )\n\nfrom python.direct_utils import (\n FLOAT4_E2M1_MAX,\n FLOAT8_E4M3_MAX,\n dequantize_to_dtype,\n linear_to_swizzled_128_4,\n pytorch_nvfp4_quantize,\n round_up,\n activation_scale_to_nvfp4,\n fp4_to_fp32,\n unpack_fp4,\n)\n\n\ndef get_ref_results(\n a_fp4,\n b_fp4,\n a_sf,\n b_sf,\n a_global_scale,\n b_global_scale,\n m,\n n,\n dtype,\n block_size,\n device,\n):\n _, m_k = a_fp4.shape\n _, n_k = b_fp4.shape\n assert m_k == n_k\n a_in_dtype = dequantize_to_dtype(\n a_fp4, a_sf, a_global_scale, dtype=dtype, device=device, block_size=block_size\n )\n b_in_dtype = dequantize_to_dtype(\n b_fp4, b_sf, b_global_scale, dtype=dtype, device=device, block_size=block_size\n )\n return torch.matmul(a_in_dtype, b_in_dtype.t())\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(\n \"shape\", [(128, 128, 64), (128, 128, 128), (256, 128, 64), (128, 256, 128)]\n)\n@torch.inference_mode()\ndef test_nvfp4_gemm(\n dtype: torch.dtype,\n shape: tuple[int, int, int],\n) -> None:\n m, n, packed_k = shape\n k = packed_k * 2\n block_size = 16\n a_dtype = torch.randn((m, k), dtype=dtype, device=\"cuda\")\n b_dtype = torch.randn((n, k), dtype=dtype, device=\"cuda\")\n\n a_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(a_dtype.flatten(), dim=-1)\n ).to(torch.float32)","source_hash":"11120d40e8965626932725fad0e2e4222686aa63290220b5f25cce499ae7eb55","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_nvfp4_gemm.test_nvfp4_gemm","uri":"program://Fuser/function/tests.python.direct.test_cutlass_nvfp4_gemm.test_nvfp4_gemm#L60-L100","kind":"function","name":"test_nvfp4_gemm","path":"tests/python/direct/test_cutlass_nvfp4_gemm.py","language":"python","start_line":60,"end_line":100,"context_start_line":40,"context_end_line":120,"code":" block_size,\n device,\n):\n _, m_k = a_fp4.shape\n _, n_k = b_fp4.shape\n assert m_k == n_k\n a_in_dtype = dequantize_to_dtype(\n a_fp4, a_sf, a_global_scale, dtype=dtype, device=device, block_size=block_size\n )\n b_in_dtype = dequantize_to_dtype(\n b_fp4, b_sf, b_global_scale, dtype=dtype, device=device, block_size=block_size\n )\n return torch.matmul(a_in_dtype, b_in_dtype.t())\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(\n \"shape\", [(128, 128, 64), (128, 128, 128), (256, 128, 64), (128, 256, 128)]\n)\n@torch.inference_mode()\ndef test_nvfp4_gemm(\n dtype: torch.dtype,\n shape: tuple[int, int, int],\n) -> None:\n m, n, packed_k = shape\n k = packed_k * 2\n block_size = 16\n a_dtype = torch.randn((m, k), dtype=dtype, device=\"cuda\")\n b_dtype = torch.randn((n, k), dtype=dtype, device=\"cuda\")\n\n a_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(a_dtype.flatten(), dim=-1)\n ).to(torch.float32)\n b_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(b_dtype.flatten(), dim=-1)\n ).to(torch.float32)\n alpha = 1.0 / (a_global_scale * b_global_scale)\n\n a_fp4, a_scale_linear = pytorch_nvfp4_quantize(a_dtype, a_global_scale)\n b_fp4, b_scale_linear = pytorch_nvfp4_quantize(b_dtype, b_global_scale)\n a_scale_interleaved = linear_to_swizzled_128_4(a_scale_linear)\n b_scale_interleaved = linear_to_swizzled_128_4(b_scale_linear)\n\n expected_out = get_ref_results(\n a_fp4,\n b_fp4,\n a_scale_interleaved,\n b_scale_interleaved,\n a_global_scale,\n b_global_scale,\n m,\n n,\n dtype,\n block_size,\n \"cuda\",\n )\n out = nvf_cutlass.nvfp4_scaled_mm(\n a_fp4, b_fp4, a_scale_interleaved, b_scale_interleaved, alpha, dtype\n )\n\n torch.testing.assert_close(out, expected_out.to(dtype=dtype), atol=1e-1, rtol=1e-1)\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(\n \"shape\", [(128, 128, 64), (128, 128, 128), (256, 128, 64), (128, 256, 128)]\n)\n@torch.inference_mode()\ndef test_nvfp4_gemm_epilogue(\n dtype: torch.dtype,\n shape: tuple[int, int, int],\n) -> None:\n m, n, packed_k = shape\n k = packed_k * 2\n block_size = 16\n a_dtype = torch.randn((m, k), dtype=dtype, device=\"cuda\")\n b_dtype = torch.randn((n, k), dtype=dtype, device=\"cuda\")\n\n a_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(a_dtype.flatten(), dim=-1)\n ).to(torch.float32)","source_hash":"11120d40e8965626932725fad0e2e4222686aa63290220b5f25cce499ae7eb55","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_nvfp4_gemm.test_nvfp4_gemm_epilogue","uri":"program://Fuser/function/tests.python.direct.test_cutlass_nvfp4_gemm.test_nvfp4_gemm_epilogue#L108-L175","kind":"function","name":"test_nvfp4_gemm_epilogue","path":"tests/python/direct/test_cutlass_nvfp4_gemm.py","language":"python","start_line":108,"end_line":175,"context_start_line":88,"context_end_line":195,"code":" a_global_scale,\n b_global_scale,\n m,\n n,\n dtype,\n block_size,\n \"cuda\",\n )\n out = nvf_cutlass.nvfp4_scaled_mm(\n a_fp4, b_fp4, a_scale_interleaved, b_scale_interleaved, alpha, dtype\n )\n\n torch.testing.assert_close(out, expected_out.to(dtype=dtype), atol=1e-1, rtol=1e-1)\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\n@pytest.mark.parametrize(\n \"shape\", [(128, 128, 64), (128, 128, 128), (256, 128, 64), (128, 256, 128)]\n)\n@torch.inference_mode()\ndef test_nvfp4_gemm_epilogue(\n dtype: torch.dtype,\n shape: tuple[int, int, int],\n) -> None:\n m, n, packed_k = shape\n k = packed_k * 2\n block_size = 16\n a_dtype = torch.randn((m, k), dtype=dtype, device=\"cuda\")\n b_dtype = torch.randn((n, k), dtype=dtype, device=\"cuda\")\n\n a_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(a_dtype.flatten(), dim=-1)\n ).to(torch.float32)\n b_global_scale = (\n (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.amax(b_dtype.flatten(), dim=-1)\n ).to(torch.float32)\n alpha = 1.0 / (a_global_scale * b_global_scale)\n global_normconst = torch.tensor(2, dtype=torch.float, device=\"cuda\")\n\n a_fp4, a_scale_linear = pytorch_nvfp4_quantize(a_dtype, a_global_scale)\n b_fp4, b_scale_linear = pytorch_nvfp4_quantize(b_dtype, b_global_scale)\n a_scale_interleaved = linear_to_swizzled_128_4(a_scale_linear)\n b_scale_interleaved = linear_to_swizzled_128_4(b_scale_linear)\n\n expected_out = get_ref_results(\n a_fp4,\n b_fp4,\n a_scale_interleaved,\n b_scale_interleaved,\n a_global_scale,\n b_global_scale,\n m,\n n,\n dtype,\n block_size,\n \"cuda\",\n )\n\n expected_out_fp4, expected_out_scale_linear = pytorch_nvfp4_quantize(\n expected_out, global_normconst\n )\n expected_out_scale_interleaved = linear_to_swizzled_128_4(expected_out_scale_linear)\n\n out_fp4, out_scale_interleaved = nvf_cutlass.nvfp4_scaled_mm_blockscale(\n a_fp4, b_fp4, a_scale_interleaved, b_scale_interleaved, alpha, global_normconst\n )\n\n # Convert to unpacked fp32 to check nvfp4 tensors.\n expected_out_fp32 = fp4_to_fp32(unpack_fp4(expected_out_fp4.view(torch.uint8)))\n out_fp32 = fp4_to_fp32(unpack_fp4(out_fp4.view(torch.uint8)))\n\n # The absolute max difference is 2.0.\n abs_diff = torch.abs(expected_out_fp32 - out_fp32)\n assert torch.max(abs_diff) <= 2.0\n\n # The percentage of mismatched values is 1%.\n nonzero = torch.count_nonzero(torch.ne(abs_diff, 0.0))\n assert (nonzero / abs_diff.numel()) < 0.1\n\n # Compare scale factors\n # rtol = epsilon = 2**(-3) for fp8_m4e3\n # atol = 2**(num_exponent_bits + smallest_exponent_value)\n torch.testing.assert_close(\n out_scale_interleaved.to(torch.float),\n expected_out_scale_interleaved.to(torch.float),\n atol=2e-3,\n rtol=0.125,\n )\n\n\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16, torch.float16])\ndef test_nvfp4_grouped_mm(\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n nvfp4_block_size = 16\n\n # k dimension is multiple of 128 to avoid padding\n m, n, k = config\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1 = torch.testing.make_tensor((m, k), dtype=torch.float32, device=\"cuda:0\")\n mat2 = torch.testing.make_tensor((g, n, k), dtype=torch.float32, device=\"cuda:0\")","source_hash":"11120d40e8965626932725fad0e2e4222686aa63290220b5f25cce499ae7eb55","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_cutlass_nvfp4_gemm.test_nvfp4_grouped_mm","uri":"program://Fuser/function/tests.python.direct.test_cutlass_nvfp4_gemm.test_nvfp4_grouped_mm#L181-L281","kind":"function","name":"test_nvfp4_grouped_mm","path":"tests/python/direct/test_cutlass_nvfp4_gemm.py","language":"python","start_line":181,"end_line":281,"context_start_line":161,"context_end_line":281,"code":" assert torch.max(abs_diff) <= 2.0\n\n # The percentage of mismatched values is 1%.\n nonzero = torch.count_nonzero(torch.ne(abs_diff, 0.0))\n assert (nonzero / abs_diff.numel()) < 0.1\n\n # Compare scale factors\n # rtol = epsilon = 2**(-3) for fp8_m4e3\n # atol = 2**(num_exponent_bits + smallest_exponent_value)\n torch.testing.assert_close(\n out_scale_interleaved.to(torch.float),\n expected_out_scale_interleaved.to(torch.float),\n atol=2e-3,\n rtol=0.125,\n )\n\n\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256]])\n@pytest.mark.parametrize(\"tokens_per_expert_neg_one\", [[115, 144, 8]])\n@pytest.mark.parametrize(\"out_dtype\", [torch.bfloat16, torch.float16])\ndef test_nvfp4_grouped_mm(\n config,\n tokens_per_expert_neg_one,\n out_dtype,\n):\n nvfp4_block_size = 16\n\n # k dimension is multiple of 128 to avoid padding\n m, n, k = config\n tokens_per_expert = list(tokens_per_expert_neg_one)\n tokens_per_expert.append(m - sum(tokens_per_expert))\n g = len(tokens_per_expert)\n\n mat1 = torch.testing.make_tensor((m, k), dtype=torch.float32, device=\"cuda:0\")\n mat2 = torch.testing.make_tensor((g, n, k), dtype=torch.float32, device=\"cuda:0\")\n ab_strides = torch.full((g,), k, dtype=torch.int64, device=\"cuda:0\")\n c_strides = torch.full((g,), n, dtype=torch.int64, device=\"cuda:0\")\n\n offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n blockscale_offsets = torch.empty((g,), dtype=torch.int32, device=\"cuda:0\")\n problem_sizes = torch.empty((g, 3), dtype=torch.int32, device=\"cuda:0\")\n mat2_gs = torch.empty((g,), dtype=torch.float32, device=\"cuda:0\")\n scale2 = torch.empty(\n (g, n, k // nvfp4_block_size), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n\n accumulated_tokens = 0\n rounded_accumulated_tokens = 0\n mat2_fp4 = torch.empty(\n (g, n, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\"\n )\n\n # Use tokens_per_expert to calculate offsets into m dimension of input tensor.\n # The blockscale offset per expert is rounded to 128 to match the alignment\n # requirements for blockscale factor.\n for i in range(g):\n mat2_gs[i] = FLOAT4_E2M1_MAX * FLOAT8_E4M3_MAX / mat2[i].max()\n offsets[i] = accumulated_tokens\n blockscale_offsets[i] = rounded_accumulated_tokens\n accumulated_tokens += tokens_per_expert[i]\n # Note: we technically don't need to round up, since k is perfectly sized.\n rounded_accumulated_tokens += round_up(tokens_per_expert[i], 128)\n\n problem_sizes[i][0] = tokens_per_expert[i]\n problem_sizes[i][1] = n\n problem_sizes[i][2] = k\n\n mat2_fp4_i, mat2_sf_i = pytorch_nvfp4_quantize(mat2[i], mat2_gs[i])\n mat2_fp4[i] = mat2_fp4_i\n scale2[i] = linear_to_swizzled_128_4(mat2_sf_i)\n\n # prepare quantization for mat1\n # note: following sglang implementation, not computing global scaling factor for mat1\n # similarly, we don't need to apply mat1_gs to alpha\n mat1_gs = torch.ones((g,), dtype=torch.float32, device=\"cuda:0\")\n mat1_fp4, scale1 = activation_scale_to_nvfp4(\n mat1, mat1_gs, offsets, blockscale_offsets, nvfp4_block_size\n )\n\n out = nvf_cutlass.nvfp4_scaled_grouped_mm(\n mat1_fp4,\n mat2_fp4,\n scale1,\n scale2,\n mat2_gs,\n ab_strides,\n c_strides,\n problem_sizes,\n offsets,\n blockscale_offsets,\n out_dtype,\n )\n\n # Create pytorch expected output reference\n # For each expert, apply nvfp4 gemm. Slice the input matrix given the tokens_per_expert.\n # C[start:stop] = A[start:stop] @ B[expert].\n out_decomposed_ref = torch.empty(m, n, dtype=out_dtype, device=\"cuda:0\")\n for i in range(g):\n l = offsets[i]\n l_sf = blockscale_offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n r_sf = round_up(tokens_per_expert[i], 128) + l_sf\n # A cublas invalid value error occurs when passing in mat2_gs[i] as\n # alpha in the torch kernel.\n out_decomposed_ref[l:r] = (\n torch._scaled_mm(\n mat1_fp4[l:r],\n mat2_fp4[i].transpose(-1, -2),\n scale1[l_sf:r_sf],\n scale2[i],\n None,\n None,\n out_dtype,\n )\n * mat2_gs[i]\n )\n\n torch.testing.assert_close(out_decomposed_ref, out, atol=1e-2, rtol=1e-2)","source_hash":"11120d40e8965626932725fad0e2e4222686aa63290220b5f25cce499ae7eb55","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_matmul","uri":"program://Fuser/module/tests.python.direct.test_matmul#L1-L223","kind":"module","name":"tests.python.direct.test_matmul","path":"tests/python/direct/test_matmul.py","language":"python","start_line":1,"end_line":223,"context_start_line":1,"context_end_line":223,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom python.direct_utils import verify_stride_order\nfrom nvfuser_direct import FusionDefinition\nfrom functools import partial\nimport itertools\nimport torch.nn.functional as F\n\n\ndef test_matmul(nvfuser_direct_test):\n m = 24\n n = 16\n k = 8\n inputs_tt = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.float16),\n torch.randn(k, n, device=\"cuda\", dtype=torch.float16),\n ]\n\n inputs_tn = [\n inputs_tt[0].clone(),\n inputs_tt[1].clone().as_strided(size=[k, n], stride=[1, k]),\n ]\n\n inputs_nt = [\n inputs_tt[0].clone().as_strided(size=[m, k], stride=[1, m]),\n inputs_tt[1].clone(),\n ]\n\n inputs_tn = [inputs_tt[0].clone(), inputs_tn[1].clone()]\n\n inputs_nn = [inputs_nt[0].clone(), inputs_tn[1].clone()]\n\n def fusion_func(fd: FusionDefinition, inps) -> None:\n t0 = fd.from_pytorch(inps[0])\n t1 = fd.from_pytorch(inps[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n for inps in [inputs_tt, inputs_tn, inputs_nt, inputs_nn]:\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, inps=inps), inps\n )\n eager_out = torch.matmul(inps[0], inps[1])\n fp16_nvf_out = nvf_out[0]\n nvfuser_direct_test.assertEqual(eager_out, fp16_nvf_out)\n\n\ndef test_linear_without_bias(nvfuser_direct_test):\n \"\"\"\n Test linear without bias. Check that bias keyword argument does not appear in python representation.\n \"\"\"\n m = 24\n n = 16\n k = 8\n inputs = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.bfloat16),\n torch.randn(n, k, device=\"cuda\", dtype=torch.bfloat16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.linear(t0, t1)\n fd.add_output(t2)\n\n # Check that bias is not included with linear\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv2 = fd.ops.linear(tv0, tv1)\n fd.add_output(tv2)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n eager_out = torch.nn.functional.linear(inputs[0], inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_linear_with_bias(nvfuser_direct_test):\n \"\"\"\n Test linear with bias. Check that bias keyword argument appears in python representation.\n \"\"\"\n m = 24\n n = 16\n k = 8\n inputs = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.bfloat16),\n torch.randn(n, k, device=\"cuda\", dtype=torch.bfloat16),\n torch.randn(n, device=\"cuda\", dtype=torch.bfloat16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.linear(t0, t1, t2)\n fd.add_output(t3)\n\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv2 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.BFloat16, is_cpu=False)\n tv3 = fd.ops.linear(tv0, tv1, bias=tv2)\n fd.add_output(tv3)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n eager_out = torch.nn.functional.linear(inputs[0], inputs[1], inputs[2])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n@pytest.mark.parametrize(\"bias\", [False, True])\ndef test_linear(nvfuser_direct_test, bias):\n m = 24\n n = 16\n k = 8\n bias1d = torch.randn(n, device=\"cuda\", dtype=torch.float16) if bias else None\n\n inputs_mk_nk = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.float16),\n torch.randn(n, k, device=\"cuda\", dtype=torch.float16),\n ]\n\n inputs_mk_kn = [\n inputs_mk_nk[0].clone(),\n inputs_mk_nk[1].clone().as_strided(size=[n, k], stride=[1, n]),\n ]\n\n inputs_km_nk = [\n inputs_mk_nk[0].clone().as_strided(size=[m, k], stride=[1, m]),\n inputs_mk_nk[1].clone(),\n ]\n\n inputs_km_kn = [\n inputs_km_nk[0].clone(),\n inputs_mk_kn[1].clone(),\n ]\n\n def fusion_func(\n fd: FusionDefinition,\n inp: torch.Tensor,\n wt: torch.Tensor,\n bias: torch.Tensor | None,\n ) -> None:\n t0 = fd.from_pytorch(inp)\n t1 = fd.from_pytorch(wt)\n if bias is not None:\n t2 = fd.from_pytorch(bias)\n t_out = fd.ops.linear(t0, t1, t2)\n else:\n t_out = fd.ops.linear(t0, t1)\n fd.add_output(t_out)\n\n in_tensors = [inputs_mk_nk, inputs_mk_kn, inputs_km_nk, inputs_km_kn]\n for inp, wt in in_tensors:\n input_tensors = (inp, wt, bias1d) if bias1d is not None else (inp, wt)\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, inp=inp, wt=wt, bias=bias1d),\n input_tensors,\n )\n eager_out = F.linear(inp, wt, bias1d)\n fp16_nvf_out = nvf_out[0]\n nvfuser_direct_test.assertEqual(fp16_nvf_out, eager_out, atol=1e-3, rtol=0)\n\n\ndef test_linear_slice(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n a = fd.define_tensor([1, 2, 3])\n b = fd.define_tensor([4, 3])\n c = fd.ops.linear(a, b)\n d = fd.ops.slice(c, start_indices=[0, 0, 0], end_indices=[1, 2, 3])\n fd.add_output(d)\n\n inputs = [\n torch.randn(1, 2, 3, device=\"cuda:0\"),\n torch.randn(4, 3, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_matmul_operandA_2d_operandB_3d(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n a = fd.define_tensor([2, 3])\n b = fd.define_tensor([7, 3, 5])\n c = fd.ops.matmul(a, b)\n assert c.ndim == 3\n fd.add_output(c)\n\n inputs = [\n torch.testing.make_tensor(2, 3, dtype=torch.float32, device=\"cuda\"),\n torch.testing.make_tensor(7, 3, 5, dtype=torch.float32, device=\"cuda\"),\n ]\n outputs, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n assert outputs[0].ndim == 3\n\n\ndef test_matmul_stride(nvfuser_direct_test):\n n, h, l, s, e = 4, 8, 16, 16, 8\n inputs = [\n torch.randn(n, h, l, e, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(n, h, s, e, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n ]\n for stride_order in itertools.permutations(range(4)):\n\n def fusion_func(fd: FusionDefinition) -> None:\n q = fd.from_pytorch(inputs[0])\n k = fd.from_pytorch(inputs[1])\n k_t = fd.ops.permute(k, [0, 1, 3, 2])\n out = fd.ops.matmul(q, k_t)\n strided_out = fd.ops.stride_order(out, stride_order)\n fd.add_output(strided_out)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.matmul(inputs[0], torch.transpose(inputs[1], -2, -1))\n verify_stride_order(nvf_out[0].stride(), stride_order)\n nvfuser_direct_test.assertEqual(nvf_out[0], eager_out)","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_matmul.test_matmul","uri":"program://Fuser/function/tests.python.direct.test_matmul.test_matmul#L15-L50","kind":"function","name":"test_matmul","path":"tests/python/direct/test_matmul.py","language":"python","start_line":15,"end_line":50,"context_start_line":1,"context_end_line":70,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom python.direct_utils import verify_stride_order\nfrom nvfuser_direct import FusionDefinition\nfrom functools import partial\nimport itertools\nimport torch.nn.functional as F\n\n\ndef test_matmul(nvfuser_direct_test):\n m = 24\n n = 16\n k = 8\n inputs_tt = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.float16),\n torch.randn(k, n, device=\"cuda\", dtype=torch.float16),\n ]\n\n inputs_tn = [\n inputs_tt[0].clone(),\n inputs_tt[1].clone().as_strided(size=[k, n], stride=[1, k]),\n ]\n\n inputs_nt = [\n inputs_tt[0].clone().as_strided(size=[m, k], stride=[1, m]),\n inputs_tt[1].clone(),\n ]\n\n inputs_tn = [inputs_tt[0].clone(), inputs_tn[1].clone()]\n\n inputs_nn = [inputs_nt[0].clone(), inputs_tn[1].clone()]\n\n def fusion_func(fd: FusionDefinition, inps) -> None:\n t0 = fd.from_pytorch(inps[0])\n t1 = fd.from_pytorch(inps[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n for inps in [inputs_tt, inputs_tn, inputs_nt, inputs_nn]:\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, inps=inps), inps\n )\n eager_out = torch.matmul(inps[0], inps[1])\n fp16_nvf_out = nvf_out[0]\n nvfuser_direct_test.assertEqual(eager_out, fp16_nvf_out)\n\n\ndef test_linear_without_bias(nvfuser_direct_test):\n \"\"\"\n Test linear without bias. Check that bias keyword argument does not appear in python representation.\n \"\"\"\n m = 24\n n = 16\n k = 8\n inputs = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.bfloat16),\n torch.randn(n, k, device=\"cuda\", dtype=torch.bfloat16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.linear(t0, t1)\n fd.add_output(t2)\n","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_matmul.test_linear_without_bias","uri":"program://Fuser/function/tests.python.direct.test_matmul.test_linear_without_bias#L53-L82","kind":"function","name":"test_linear_without_bias","path":"tests/python/direct/test_matmul.py","language":"python","start_line":53,"end_line":82,"context_start_line":33,"context_end_line":102,"code":"\n inputs_tn = [inputs_tt[0].clone(), inputs_tn[1].clone()]\n\n inputs_nn = [inputs_nt[0].clone(), inputs_tn[1].clone()]\n\n def fusion_func(fd: FusionDefinition, inps) -> None:\n t0 = fd.from_pytorch(inps[0])\n t1 = fd.from_pytorch(inps[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n for inps in [inputs_tt, inputs_tn, inputs_nt, inputs_nn]:\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, inps=inps), inps\n )\n eager_out = torch.matmul(inps[0], inps[1])\n fp16_nvf_out = nvf_out[0]\n nvfuser_direct_test.assertEqual(eager_out, fp16_nvf_out)\n\n\ndef test_linear_without_bias(nvfuser_direct_test):\n \"\"\"\n Test linear without bias. Check that bias keyword argument does not appear in python representation.\n \"\"\"\n m = 24\n n = 16\n k = 8\n inputs = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.bfloat16),\n torch.randn(n, k, device=\"cuda\", dtype=torch.bfloat16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.linear(t0, t1)\n fd.add_output(t2)\n\n # Check that bias is not included with linear\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv2 = fd.ops.linear(tv0, tv1)\n fd.add_output(tv2)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n eager_out = torch.nn.functional.linear(inputs[0], inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_linear_with_bias(nvfuser_direct_test):\n \"\"\"\n Test linear with bias. Check that bias keyword argument appears in python representation.\n \"\"\"\n m = 24\n n = 16\n k = 8\n inputs = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.bfloat16),\n torch.randn(n, k, device=\"cuda\", dtype=torch.bfloat16),\n torch.randn(n, device=\"cuda\", dtype=torch.bfloat16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.linear(t0, t1, t2)","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_matmul.test_linear_with_bias","uri":"program://Fuser/function/tests.python.direct.test_matmul.test_linear_with_bias#L85-L116","kind":"function","name":"test_linear_with_bias","path":"tests/python/direct/test_matmul.py","language":"python","start_line":85,"end_line":116,"context_start_line":65,"context_end_line":136,"code":" def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.linear(t0, t1)\n fd.add_output(t2)\n\n # Check that bias is not included with linear\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv2 = fd.ops.linear(tv0, tv1)\n fd.add_output(tv2)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n eager_out = torch.nn.functional.linear(inputs[0], inputs[1])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_linear_with_bias(nvfuser_direct_test):\n \"\"\"\n Test linear with bias. Check that bias keyword argument appears in python representation.\n \"\"\"\n m = 24\n n = 16\n k = 8\n inputs = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.bfloat16),\n torch.randn(n, k, device=\"cuda\", dtype=torch.bfloat16),\n torch.randn(n, device=\"cuda\", dtype=torch.bfloat16),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.linear(t0, t1, t2)\n fd.add_output(t3)\n\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv2 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.BFloat16, is_cpu=False)\n tv3 = fd.ops.linear(tv0, tv1, bias=tv2)\n fd.add_output(tv3)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n eager_out = torch.nn.functional.linear(inputs[0], inputs[1], inputs[2])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n@pytest.mark.parametrize(\"bias\", [False, True])\ndef test_linear(nvfuser_direct_test, bias):\n m = 24\n n = 16\n k = 8\n bias1d = torch.randn(n, device=\"cuda\", dtype=torch.float16) if bias else None\n\n inputs_mk_nk = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.float16),\n torch.randn(n, k, device=\"cuda\", dtype=torch.float16),\n ]\n\n inputs_mk_kn = [\n inputs_mk_nk[0].clone(),\n inputs_mk_nk[1].clone().as_strided(size=[n, k], stride=[1, n]),\n ]\n\n inputs_km_nk = [","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_matmul.test_linear","uri":"program://Fuser/function/tests.python.direct.test_matmul.test_linear#L120-L170","kind":"function","name":"test_linear","path":"tests/python/direct/test_matmul.py","language":"python","start_line":120,"end_line":170,"context_start_line":100,"context_end_line":190,"code":" t1 = fd.from_pytorch(inputs[1])\n t2 = fd.from_pytorch(inputs[2])\n t3 = fd.ops.linear(t0, t1, t2)\n fd.add_output(t3)\n\n fd_str = \"\"\"def nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1], contiguity=[True, True], dtype=DataType.BFloat16, is_cpu=False)\n tv2 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.BFloat16, is_cpu=False)\n tv3 = fd.ops.linear(tv0, tv1, bias=tv2)\n fd.add_output(tv3)\"\"\"\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func, inputs, expected_fd_str=fd_str\n )\n eager_out = torch.nn.functional.linear(inputs[0], inputs[1], inputs[2])\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n@pytest.mark.parametrize(\"bias\", [False, True])\ndef test_linear(nvfuser_direct_test, bias):\n m = 24\n n = 16\n k = 8\n bias1d = torch.randn(n, device=\"cuda\", dtype=torch.float16) if bias else None\n\n inputs_mk_nk = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.float16),\n torch.randn(n, k, device=\"cuda\", dtype=torch.float16),\n ]\n\n inputs_mk_kn = [\n inputs_mk_nk[0].clone(),\n inputs_mk_nk[1].clone().as_strided(size=[n, k], stride=[1, n]),\n ]\n\n inputs_km_nk = [\n inputs_mk_nk[0].clone().as_strided(size=[m, k], stride=[1, m]),\n inputs_mk_nk[1].clone(),\n ]\n\n inputs_km_kn = [\n inputs_km_nk[0].clone(),\n inputs_mk_kn[1].clone(),\n ]\n\n def fusion_func(\n fd: FusionDefinition,\n inp: torch.Tensor,\n wt: torch.Tensor,\n bias: torch.Tensor | None,\n ) -> None:\n t0 = fd.from_pytorch(inp)\n t1 = fd.from_pytorch(wt)\n if bias is not None:\n t2 = fd.from_pytorch(bias)\n t_out = fd.ops.linear(t0, t1, t2)\n else:\n t_out = fd.ops.linear(t0, t1)\n fd.add_output(t_out)\n\n in_tensors = [inputs_mk_nk, inputs_mk_kn, inputs_km_nk, inputs_km_kn]\n for inp, wt in in_tensors:\n input_tensors = (inp, wt, bias1d) if bias1d is not None else (inp, wt)\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, inp=inp, wt=wt, bias=bias1d),\n input_tensors,\n )\n eager_out = F.linear(inp, wt, bias1d)\n fp16_nvf_out = nvf_out[0]\n nvfuser_direct_test.assertEqual(fp16_nvf_out, eager_out, atol=1e-3, rtol=0)\n\n\ndef test_linear_slice(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n a = fd.define_tensor([1, 2, 3])\n b = fd.define_tensor([4, 3])\n c = fd.ops.linear(a, b)\n d = fd.ops.slice(c, start_indices=[0, 0, 0], end_indices=[1, 2, 3])\n fd.add_output(d)\n\n inputs = [\n torch.randn(1, 2, 3, device=\"cuda:0\"),\n torch.randn(4, 3, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_matmul_operandA_2d_operandB_3d(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n a = fd.define_tensor([2, 3])","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_matmul.test_linear_slice","uri":"program://Fuser/function/tests.python.direct.test_matmul.test_linear_slice#L173-L185","kind":"function","name":"test_linear_slice","path":"tests/python/direct/test_matmul.py","language":"python","start_line":173,"end_line":185,"context_start_line":153,"context_end_line":205,"code":" t1 = fd.from_pytorch(wt)\n if bias is not None:\n t2 = fd.from_pytorch(bias)\n t_out = fd.ops.linear(t0, t1, t2)\n else:\n t_out = fd.ops.linear(t0, t1)\n fd.add_output(t_out)\n\n in_tensors = [inputs_mk_nk, inputs_mk_kn, inputs_km_nk, inputs_km_kn]\n for inp, wt in in_tensors:\n input_tensors = (inp, wt, bias1d) if bias1d is not None else (inp, wt)\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, inp=inp, wt=wt, bias=bias1d),\n input_tensors,\n )\n eager_out = F.linear(inp, wt, bias1d)\n fp16_nvf_out = nvf_out[0]\n nvfuser_direct_test.assertEqual(fp16_nvf_out, eager_out, atol=1e-3, rtol=0)\n\n\ndef test_linear_slice(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n a = fd.define_tensor([1, 2, 3])\n b = fd.define_tensor([4, 3])\n c = fd.ops.linear(a, b)\n d = fd.ops.slice(c, start_indices=[0, 0, 0], end_indices=[1, 2, 3])\n fd.add_output(d)\n\n inputs = [\n torch.randn(1, 2, 3, device=\"cuda:0\"),\n torch.randn(4, 3, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_matmul_operandA_2d_operandB_3d(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n a = fd.define_tensor([2, 3])\n b = fd.define_tensor([7, 3, 5])\n c = fd.ops.matmul(a, b)\n assert c.ndim == 3\n fd.add_output(c)\n\n inputs = [\n torch.testing.make_tensor(2, 3, dtype=torch.float32, device=\"cuda\"),\n torch.testing.make_tensor(7, 3, 5, dtype=torch.float32, device=\"cuda\"),\n ]\n outputs, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n assert outputs[0].ndim == 3\n\n\ndef test_matmul_stride(nvfuser_direct_test):\n n, h, l, s, e = 4, 8, 16, 16, 8","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_matmul.test_matmul_operandA_2d_operandB_3d","uri":"program://Fuser/function/tests.python.direct.test_matmul.test_matmul_operandA_2d_operandB_3d#L188-L201","kind":"function","name":"test_matmul_operandA_2d_operandB_3d","path":"tests/python/direct/test_matmul.py","language":"python","start_line":188,"end_line":201,"context_start_line":168,"context_end_line":221,"code":" eager_out = F.linear(inp, wt, bias1d)\n fp16_nvf_out = nvf_out[0]\n nvfuser_direct_test.assertEqual(fp16_nvf_out, eager_out, atol=1e-3, rtol=0)\n\n\ndef test_linear_slice(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n a = fd.define_tensor([1, 2, 3])\n b = fd.define_tensor([4, 3])\n c = fd.ops.linear(a, b)\n d = fd.ops.slice(c, start_indices=[0, 0, 0], end_indices=[1, 2, 3])\n fd.add_output(d)\n\n inputs = [\n torch.randn(1, 2, 3, device=\"cuda:0\"),\n torch.randn(4, 3, device=\"cuda:0\"),\n ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_matmul_operandA_2d_operandB_3d(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n a = fd.define_tensor([2, 3])\n b = fd.define_tensor([7, 3, 5])\n c = fd.ops.matmul(a, b)\n assert c.ndim == 3\n fd.add_output(c)\n\n inputs = [\n torch.testing.make_tensor(2, 3, dtype=torch.float32, device=\"cuda\"),\n torch.testing.make_tensor(7, 3, 5, dtype=torch.float32, device=\"cuda\"),\n ]\n outputs, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n assert outputs[0].ndim == 3\n\n\ndef test_matmul_stride(nvfuser_direct_test):\n n, h, l, s, e = 4, 8, 16, 16, 8\n inputs = [\n torch.randn(n, h, l, e, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(n, h, s, e, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n ]\n for stride_order in itertools.permutations(range(4)):\n\n def fusion_func(fd: FusionDefinition) -> None:\n q = fd.from_pytorch(inputs[0])\n k = fd.from_pytorch(inputs[1])\n k_t = fd.ops.permute(k, [0, 1, 3, 2])\n out = fd.ops.matmul(q, k_t)\n strided_out = fd.ops.stride_order(out, stride_order)\n fd.add_output(strided_out)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.matmul(inputs[0], torch.transpose(inputs[1], -2, -1))","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_matmul.test_matmul_stride","uri":"program://Fuser/function/tests.python.direct.test_matmul.test_matmul_stride#L204-L223","kind":"function","name":"test_matmul_stride","path":"tests/python/direct/test_matmul.py","language":"python","start_line":204,"end_line":223,"context_start_line":184,"context_end_line":223,"code":" ]\n nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n\ndef test_matmul_operandA_2d_operandB_3d(nvfuser_direct_test):\n def fusion_func(fd: FusionDefinition) -> None:\n a = fd.define_tensor([2, 3])\n b = fd.define_tensor([7, 3, 5])\n c = fd.ops.matmul(a, b)\n assert c.ndim == 3\n fd.add_output(c)\n\n inputs = [\n torch.testing.make_tensor(2, 3, dtype=torch.float32, device=\"cuda\"),\n torch.testing.make_tensor(7, 3, 5, dtype=torch.float32, device=\"cuda\"),\n ]\n outputs, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n assert outputs[0].ndim == 3\n\n\ndef test_matmul_stride(nvfuser_direct_test):\n n, h, l, s, e = 4, 8, 16, 16, 8\n inputs = [\n torch.randn(n, h, l, e, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(n, h, s, e, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n ]\n for stride_order in itertools.permutations(range(4)):\n\n def fusion_func(fd: FusionDefinition) -> None:\n q = fd.from_pytorch(inputs[0])\n k = fd.from_pytorch(inputs[1])\n k_t = fd.ops.permute(k, [0, 1, 3, 2])\n out = fd.ops.matmul(q, k_t)\n strided_out = fd.ops.stride_order(out, stride_order)\n fd.add_output(strided_out)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.matmul(inputs[0], torch.transpose(inputs[1], -2, -1))\n verify_stride_order(nvf_out[0].stride(), stride_order)\n nvfuser_direct_test.assertEqual(nvf_out[0], eager_out)","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_matmul.fusion_func","uri":"program://Fuser/function/tests.python.direct.test_matmul.fusion_func#L212-L218","kind":"function","name":"fusion_func","path":"tests/python/direct/test_matmul.py","language":"python","start_line":212,"end_line":218,"context_start_line":192,"context_end_line":223,"code":" c = fd.ops.matmul(a, b)\n assert c.ndim == 3\n fd.add_output(c)\n\n inputs = [\n torch.testing.make_tensor(2, 3, dtype=torch.float32, device=\"cuda\"),\n torch.testing.make_tensor(7, 3, 5, dtype=torch.float32, device=\"cuda\"),\n ]\n outputs, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n assert outputs[0].ndim == 3\n\n\ndef test_matmul_stride(nvfuser_direct_test):\n n, h, l, s, e = 4, 8, 16, 16, 8\n inputs = [\n torch.randn(n, h, l, e, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(n, h, s, e, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n ]\n for stride_order in itertools.permutations(range(4)):\n\n def fusion_func(fd: FusionDefinition) -> None:\n q = fd.from_pytorch(inputs[0])\n k = fd.from_pytorch(inputs[1])\n k_t = fd.ops.permute(k, [0, 1, 3, 2])\n out = fd.ops.matmul(q, k_t)\n strided_out = fd.ops.stride_order(out, stride_order)\n fd.add_output(strided_out)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n eager_out = torch.matmul(inputs[0], torch.transpose(inputs[1], -2, -1))\n verify_stride_order(nvf_out[0].stride(), stride_order)\n nvfuser_direct_test.assertEqual(nvf_out[0], eager_out)","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity","uri":"program://Fuser/module/tests.python.direct.test_high_complexity#L1-L1130","kind":"module","name":"tests.python.direct.test_high_complexity","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":1,"end_line":1130,"context_start_line":1,"context_end_line":1130,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport torch._refs as refs\nimport torch._prims as prims\n\nimport io\nfrom contextlib import redirect_stdout, redirect_stderr\nimport pytest\n\nfrom nvfuser_direct import FusionDefinition, DataType\nimport random\nimport itertools\nimport math\nfrom functools import partial\nfrom typing import List\n\n\ndef test_broadcast_in_dim_with_dynamic_shapes(nvfuser_direct_test):\n inputs_1 = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(4, device=\"cuda\"),\n ]\n inputs_2 = [\n torch.randn(2, 3, 1024, device=\"cuda\"),\n torch.randn(1024, device=\"cuda\"),\n ]\n\n def fusion_func_1(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_2(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_1[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_3(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_2[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n # Func_1 uses tensor.shape() to propagate dynamic size, therefore, it is\n # expected that test 2 should be cached based on test 2\n\n # Test 1\n inputs = inputs_1\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_1, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Test 2\n inputs = inputs_2\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func_1, inputs, new_fusion_expected=False\n )\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Func_2 and Func_3 are nearly identical except that have a different\n # concrete output shape for their broadcast_in_dim. Therefore, test 4\n # should not be cached.\n # Note: It is assumed that definition will change with Tensor Size with\n # concrete shapes.\n\n # Test 3\n inputs = inputs_1\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_2, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Test 4\n inputs = inputs_2\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_3, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n# Test that symbolic IterDomains can be concatenated\n# https://github.com/NVIDIA/Fuser/issues/1554\ndef test_cat_symbolic(nvfuser_direct_test):\n inputs = [\n 0.29730177875068026,\n 0.29730177875068026,\n 4,\n 64,\n 768,\n 4,\n 64,\n 768,\n 2,\n torch.randn([4, 6, 64, 128], dtype=torch.float32, device=\"cuda\"),\n torch.randn([4, 6, 64, 128], dtype=torch.float32, device=\"cuda\"),\n torch.randn([4, 64, 768], dtype=torch.float32, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Double)\n S1 = fd.define_scalar(None, dtype=DataType.Double)\n S2 = fd.define_scalar(None, dtype=DataType.Int)\n S3 = fd.define_scalar(None, dtype=DataType.Int)\n S4 = fd.define_scalar(None, dtype=DataType.Int)\n S5 = fd.define_scalar(None, dtype=DataType.Int)\n S6 = fd.define_scalar(None, dtype=DataType.Int)\n S7 = fd.define_scalar(None, dtype=DataType.Int)\n S8 = fd.define_scalar(None, dtype=DataType.Int)\n T9 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T10 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T11 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T12 = fd.ops.mul(T10, S1)\n T13 = fd.ops.permute(T12, dims=[0, 1, 3, 2])\n T14 = fd.ops.mul(T9, S0)\n T15 = fd.ops.permute(T14, dims=[0, 2, 1, 3])\n S16 = fd.define_scalar(4, dtype=DataType.Int)\n S17 = fd.define_scalar(64, dtype=DataType.Int)\n S18 = fd.define_scalar(768, dtype=DataType.Int)\n T20 = fd.ops.reshape(T15, new_shape=[S16, S17, S18])\n T21 = fd.ops.permute(T13, dims=[0, 2, 1, 3])\n S22 = fd.define_scalar(4, dtype=DataType.Int)\n S23 = fd.define_scalar(64, dtype=DataType.Int)\n S24 = fd.define_scalar(768, dtype=DataType.Int)\n T26 = fd.ops.reshape(T21, new_shape=[S22, S23, S24])\n T27 = fd.ops.cat([T20, T26, T11], dim=2)\n T28 = fd.ops.sum(T27, [0, 1], keepdim=False, dtype=DataType.Null)\n fd.add_output(T27)\n fd.add_output(T28)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n t12 = inputs[1] * inputs[-2]\n t13 = torch.permute(t12, [0, 1, 3, 2])\n t14 = inputs[0] * inputs[-3]\n t15 = torch.permute(t14, [0, 2, 1, 3])\n t20 = torch.reshape(t15, [4, 64, 768])\n t21 = torch.permute(t13, [0, 2, 1, 3])\n t26 = torch.reshape(t21, [4, 64, 768])\n t27 = torch.cat([t20, t26, inputs[-1]], dim=2)\n t28 = t27.sum([0, 1])\n\n nvfuser_direct_test.assertEqual(nvf_out[0], t27)\n nvfuser_direct_test.assertEqual(nvf_out[1], t28)\n\n\ndef test_slice_error_checks(nvfuser_direct_test):\n inputs = [\n [torch.randn(10, 10, device=\"cuda\")],\n [torch.randn(5, 5, device=\"cuda\")],\n ]\n\n def check_start_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[-1, -2], end_indices=[5, 5], strides=[7, 7]\n )\n fd.add_output(T1)\n\n def check_end_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[3, 4], end_indices=[1, 2], strides=[1, 1])\n fd.add_output(T1)\n\n def check_strides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[0, 0], end_indices=[5, 5], strides=[5, 5])\n fd.add_output(T1)\n\n def check_tensor_dims(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_start(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_end(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_stride(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_nostrides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[2, 2], end_indices=[4, 4])\n fd.add_output(T1)\n\n def legal(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[6, 6], end_indices=[8, 8], strides=[1, 1])\n fd.add_output(T1)\n\n checks = [\n (\n check_start_indices,\n \"Slice operation start_indices must be greater than or equal to 0..*\",\n ),\n (\n check_end_indices,\n \"Slice operation end_indices must be greater than or equal to start_indices..*\",\n ),\n (\n check_strides,\n \"nvFuser Limitation: All slice operation strides must be of const size 1.*\",\n ),\n (\n check_tensor_dims,\n \"Number of tensor dimensions does not match slice dimensions!.*\",\n ),\n (\n check_slice_dims_start,\n \"Slice start_indices and strides don't match!.*\",\n ),\n (\n check_slice_dims_end,\n \"Slice indexing attribute dimensions don't match!.*\",\n ),\n (\n check_slice_dims_stride,\n \"Slice start_indices and strides don't match!.*\",\n ),\n (check_nostrides, None),\n (legal, None),\n ]\n\n # Redirect stdout and stderr messages to log to avoid false positives in\n # the CI.\n stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n for combination in itertools.product(inputs, checks):\n inputs, (check, error_msg) = combination\n if error_msg is None:\n out = nvfuser_direct_test.exec_nvfuser(\n partial(check, acts=inputs), inputs, new_fusion_expected=None\n )\n else:\n with pytest.raises(RuntimeError, match=error_msg), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n nvfuser_direct_test.exec_nvfuser(\n partial(check, acts=inputs),\n inputs,\n )\n\n\n# Test that deterministic random ops (uniform, normal) give same results as\n# their stochastic versions\ndef test_deterministic_random(nvfuser_direct_test):\n inputs = [\n torch.randn([5, 9], device=\"cuda\", dtype=torch.float32),\n ]\n\n for rand_op_name in [\"uniform\", \"normal\"]:\n\n def fusion_func(fd: FusionDefinition, *, deterministic) -> None:\n t1 = fd.from_pytorch(inputs[0])\n a = fd.define_scalar(0.3, DataType.Float)\n b = fd.define_scalar(1.7, DataType.Float)\n rand_op = getattr(fd.ops, rand_op_name)\n if deterministic:\n rng_seed = fd.define_scalar(DataType.Int)\n rng_offset = fd.define_scalar(DataType.Int)\n u = rand_op(\n a, b, shape=[5, 9], rng_seed=rng_seed, rng_offset=rng_offset\n )\n else:\n u = rand_op(a, b, shape=[5, 9])\n t2 = fd.ops.mul(t1, u)\n fd.add_output(t2)\n\n # exec_nvfuser tests printing and serde, so run that for each definition first\n nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, deterministic=False), inputs\n )\n nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, deterministic=True), [inputs[0], 0, 0]\n )\n\n # Now instantiate FusionDefinitions in each mode\n with FusionDefinition() as fd_stoch:\n fusion_func(fd_stoch, deterministic=False)\n with FusionDefinition() as fd_det:\n fusion_func(fd_det, deterministic=True)\n\n # Get the current RNG state to restore after this test.\n state = torch.cuda.get_rng_state()\n # Test with three different random seeds\n for _ in range(3):\n max_seed = 2**63 - 1\n seed = random.randint(0, max_seed)\n torch.manual_seed(seed)\n\n stateful_sequence = [fd_stoch.execute(inputs) for _ in range(10)]\n # Each call to uniform with DataType::Float will advance the offset by one\n # See Note [Divide offset by 4] in rng.cpp for more information\n stateless_sequence = [\n fd_det.execute([inputs[0], seed, rng_offset])\n for rng_offset in range(10)\n ]\n\n for i, (sful, sless) in enumerate(\n zip(stateful_sequence, stateless_sequence)\n ):\n nvfuser_direct_test.assertEqual(sful[0], sless[0])\n # Restore the RNG state\n torch.cuda.set_rng_state(state)\n\n\n# Test that the range of generated uniform values spans the proper range\n# https://github.com/NVIDIA/Fuser/issues/1653\ndef test_uniform_range(nvfuser_direct_test):\n dtypes = [DataType.Double, DataType.Float, DataType.Half, DataType.BFloat16]\n\n def run_test(left: float, right: float, dtype: DataType):\n samples_per_run = 2**29\n\n def fusion_fn(fd: FusionDefinition):\n # Generate enough values to reasonably expect to sample the ends of the range\n S0 = fd.define_scalar(left, dtype=DataType.Double)\n S1 = fd.define_scalar(right, dtype=DataType.Double)\n output = fd.ops.uniform(S0, S1, shape=[samples_per_run], dtype=dtype)\n fd.add_output(output)\n\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n output = fd.execute([])[0]\n\n x = output.amax()\n m = output.amin()\n mu = output.type(torch.float64).mean()\n # Repeat to improve chances of sampling extreme values\n num_runs = 100\n num_samples = num_runs * samples_per_run\n for i in range(num_runs):\n u = fd.execute([])[0]\n x = torch.maximum(x, u.amax())\n m = torch.minimum(m, u.amin())\n mu = mu + (u.type(torch.float64).mean() - mu) / (i + 2)\n\n # round-trip cast to find expected min\n theomin = torch.tensor(left, dtype=output.dtype).item()\n theomu = 0.5 * (right + left)\n theomax = torch.nextafter(\n torch.tensor(right, dtype=output.dtype),\n torch.tensor(left, dtype=output.dtype),\n )\n\n assert (\n m.item() >= theomin\n ), f\"{output.dtype} expected min generated value {theomin} but found {m.item()}\"\n assert (\n m.item() <= theomax\n ), f\"{output.dtype} expected max generated value {theomax} but found {x.item()}\"\n\n # uniform distribution on [0, 1) has mean 0.5 and variance 1/12\n # The standard error of the mean is then 1/sqrt(12 *\n # num_samples). We use the precision at 1.0 as a surrogate for\n # the contribution of rounding to the standard error of the\n # finite-precision mean.\n assert abs(mu.item() - theomu) < (right - left) * max(\n right - x.item(), 3.0 / math.sqrt(12 * num_samples)\n ), f\"{output.dtype} expected mean generated value {theomu} but found {mu.item()}\"\n\n if dtype not in [DataType.Float, DataType.Double]:\n # For reduced precision types, check that we sample the extreme\n # values. We don't do this for full precision types since the\n # amount of samples required would be too large.\n assert (\n m.item() == theomin\n ), f\"{output.dtype} expected min generated value {theomin} but found {m.item()}\"\n assert (\n x.item() == theomax\n ), f\"{output.dtype} expected max generated value {theomax} but found {x.item()}\"\n\n # test standard and non-standard uniform\n for left, right in [[0.0, 1.0], [-1.5, 3.7]]:\n for dtype in dtypes:\n run_test(left, right, dtype)\n\n\ndef test_cat_qwen2_v2(nvfuser_direct_test):\n def qwen2_cat_fusion_2(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2048, 512],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n S1 = fd.define_scalar(None, dtype=DataType.Int)\n S2 = fd.define_scalar(None, dtype=DataType.Int)\n T3 = fd.define_tensor(\n shape=[1, 4, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T5 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T6 = fd.define_tensor(\n shape=[1, 28, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T7 = fd.define_tensor(\n shape=[1, 2048, 512],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T12 = fd.ops.reshape(T0, new_shape=[1, 2048, 512])\n T13 = fd.ops.cast(T12, dtype=DataType.Float)\n S14 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S15 = fd.define_scalar(1.00000, dtype=DataType.Double)\n S16 = fd.define_scalar(1, dtype=DataType.Int)\n S17 = fd.define_scalar(2048, dtype=DataType.Int)\n S18 = fd.define_scalar(512, dtype=DataType.Int)\n T20 = fd.ops.uniform(\n S14,\n S15,\n shape=[S16, S17, S18],\n rng_seed=S2,\n rng_offset=S1,\n dtype=DataType.BFloat16,\n )\n S21 = fd.define_scalar(4.00000, dtype=DataType.Double)\n T22 = fd.ops.mul(T13, S21)\n S23 = fd.define_scalar(0.900000, dtype=DataType.Double)\n T24 = fd.ops.lt(T20, S23)\n T25 = fd.ops.cast(T24, dtype=DataType.Float)\n T41 = fd.ops.slice(\n T3,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 4, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T42 = fd.ops.mul(T22, T25)\n T43 = fd.ops.cast(T41, dtype=DataType.Float)\n T44 = fd.ops.neg(T43)\n T50 = fd.ops.broadcast_in_dim(\n T4, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3]\n )\n T66 = fd.ops.slice(\n T3,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 4, 2048, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T67 = fd.ops.cast(T44, dtype=DataType.BFloat16)\n T73 = fd.ops.broadcast_in_dim(\n T5, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3]\n )\n T89 = fd.ops.slice(\n T6,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 28, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n S90 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T91 = fd.ops.mul(T42, S90)\n T97 = fd.ops.broadcast_in_dim(\n T50, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T98 = fd.ops.cat([T67, T66], dim=-1, manual_padding=0)\n T104 = fd.ops.broadcast_in_dim(\n T73, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T105 = fd.ops.cast(T89, dtype=DataType.Float)\n T106 = fd.ops.cast(T97, dtype=DataType.Float)\n T107 = fd.ops.cast(T98, dtype=DataType.Float)\n# ... truncated ...","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_broadcast_in_dim_with_dynamic_shapes","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_broadcast_in_dim_with_dynamic_shapes#L22-L100","kind":"function","name":"test_broadcast_in_dim_with_dynamic_shapes","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":22,"end_line":100,"context_start_line":2,"context_end_line":120,"code":"# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport torch._refs as refs\nimport torch._prims as prims\n\nimport io\nfrom contextlib import redirect_stdout, redirect_stderr\nimport pytest\n\nfrom nvfuser_direct import FusionDefinition, DataType\nimport random\nimport itertools\nimport math\nfrom functools import partial\nfrom typing import List\n\n\ndef test_broadcast_in_dim_with_dynamic_shapes(nvfuser_direct_test):\n inputs_1 = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(4, device=\"cuda\"),\n ]\n inputs_2 = [\n torch.randn(2, 3, 1024, device=\"cuda\"),\n torch.randn(1024, device=\"cuda\"),\n ]\n\n def fusion_func_1(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_2(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_1[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_3(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_2[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n # Func_1 uses tensor.shape() to propagate dynamic size, therefore, it is\n # expected that test 2 should be cached based on test 2\n\n # Test 1\n inputs = inputs_1\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_1, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Test 2\n inputs = inputs_2\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func_1, inputs, new_fusion_expected=False\n )\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Func_2 and Func_3 are nearly identical except that have a different\n # concrete output shape for their broadcast_in_dim. Therefore, test 4\n # should not be cached.\n # Note: It is assumed that definition will change with Tensor Size with\n # concrete shapes.\n\n # Test 3\n inputs = inputs_1\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_2, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Test 4\n inputs = inputs_2\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_3, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n# Test that symbolic IterDomains can be concatenated\n# https://github.com/NVIDIA/Fuser/issues/1554\ndef test_cat_symbolic(nvfuser_direct_test):\n inputs = [\n 0.29730177875068026,\n 0.29730177875068026,\n 4,\n 64,\n 768,\n 4,\n 64,\n 768,\n 2,\n torch.randn([4, 6, 64, 128], dtype=torch.float32, device=\"cuda\"),\n torch.randn([4, 6, 64, 128], dtype=torch.float32, device=\"cuda\"),\n torch.randn([4, 64, 768], dtype=torch.float32, device=\"cuda\"),\n ]\n","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_cat_symbolic","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_cat_symbolic#L105-L183","kind":"function","name":"test_cat_symbolic","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":105,"end_line":183,"context_start_line":85,"context_end_line":203,"code":"\n # Test 3\n inputs = inputs_1\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_2, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Test 4\n inputs = inputs_2\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_3, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\n# Test that symbolic IterDomains can be concatenated\n# https://github.com/NVIDIA/Fuser/issues/1554\ndef test_cat_symbolic(nvfuser_direct_test):\n inputs = [\n 0.29730177875068026,\n 0.29730177875068026,\n 4,\n 64,\n 768,\n 4,\n 64,\n 768,\n 2,\n torch.randn([4, 6, 64, 128], dtype=torch.float32, device=\"cuda\"),\n torch.randn([4, 6, 64, 128], dtype=torch.float32, device=\"cuda\"),\n torch.randn([4, 64, 768], dtype=torch.float32, device=\"cuda\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n S0 = fd.define_scalar(None, dtype=DataType.Double)\n S1 = fd.define_scalar(None, dtype=DataType.Double)\n S2 = fd.define_scalar(None, dtype=DataType.Int)\n S3 = fd.define_scalar(None, dtype=DataType.Int)\n S4 = fd.define_scalar(None, dtype=DataType.Int)\n S5 = fd.define_scalar(None, dtype=DataType.Int)\n S6 = fd.define_scalar(None, dtype=DataType.Int)\n S7 = fd.define_scalar(None, dtype=DataType.Int)\n S8 = fd.define_scalar(None, dtype=DataType.Int)\n T9 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T10 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[3, 2, 1, 0],\n )\n T11 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T12 = fd.ops.mul(T10, S1)\n T13 = fd.ops.permute(T12, dims=[0, 1, 3, 2])\n T14 = fd.ops.mul(T9, S0)\n T15 = fd.ops.permute(T14, dims=[0, 2, 1, 3])\n S16 = fd.define_scalar(4, dtype=DataType.Int)\n S17 = fd.define_scalar(64, dtype=DataType.Int)\n S18 = fd.define_scalar(768, dtype=DataType.Int)\n T20 = fd.ops.reshape(T15, new_shape=[S16, S17, S18])\n T21 = fd.ops.permute(T13, dims=[0, 2, 1, 3])\n S22 = fd.define_scalar(4, dtype=DataType.Int)\n S23 = fd.define_scalar(64, dtype=DataType.Int)\n S24 = fd.define_scalar(768, dtype=DataType.Int)\n T26 = fd.ops.reshape(T21, new_shape=[S22, S23, S24])\n T27 = fd.ops.cat([T20, T26, T11], dim=2)\n T28 = fd.ops.sum(T27, [0, 1], keepdim=False, dtype=DataType.Null)\n fd.add_output(T27)\n fd.add_output(T28)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n t12 = inputs[1] * inputs[-2]\n t13 = torch.permute(t12, [0, 1, 3, 2])\n t14 = inputs[0] * inputs[-3]\n t15 = torch.permute(t14, [0, 2, 1, 3])\n t20 = torch.reshape(t15, [4, 64, 768])\n t21 = torch.permute(t13, [0, 2, 1, 3])\n t26 = torch.reshape(t21, [4, 64, 768])\n t27 = torch.cat([t20, t26, inputs[-1]], dim=2)\n t28 = t27.sum([0, 1])\n\n nvfuser_direct_test.assertEqual(nvf_out[0], t27)\n nvfuser_direct_test.assertEqual(nvf_out[1], t28)\n\n\ndef test_slice_error_checks(nvfuser_direct_test):\n inputs = [\n [torch.randn(10, 10, device=\"cuda\")],\n [torch.randn(5, 5, device=\"cuda\")],\n ]\n\n def check_start_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[-1, -2], end_indices=[5, 5], strides=[7, 7]\n )\n fd.add_output(T1)\n\n def check_end_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[3, 4], end_indices=[1, 2], strides=[1, 1])\n fd.add_output(T1)\n","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_slice_error_checks","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_slice_error_checks#L186-L297","kind":"function","name":"test_slice_error_checks","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":186,"end_line":297,"context_start_line":166,"context_end_line":317,"code":" T28 = fd.ops.sum(T27, [0, 1], keepdim=False, dtype=DataType.Null)\n fd.add_output(T27)\n fd.add_output(T28)\n\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n t12 = inputs[1] * inputs[-2]\n t13 = torch.permute(t12, [0, 1, 3, 2])\n t14 = inputs[0] * inputs[-3]\n t15 = torch.permute(t14, [0, 2, 1, 3])\n t20 = torch.reshape(t15, [4, 64, 768])\n t21 = torch.permute(t13, [0, 2, 1, 3])\n t26 = torch.reshape(t21, [4, 64, 768])\n t27 = torch.cat([t20, t26, inputs[-1]], dim=2)\n t28 = t27.sum([0, 1])\n\n nvfuser_direct_test.assertEqual(nvf_out[0], t27)\n nvfuser_direct_test.assertEqual(nvf_out[1], t28)\n\n\ndef test_slice_error_checks(nvfuser_direct_test):\n inputs = [\n [torch.randn(10, 10, device=\"cuda\")],\n [torch.randn(5, 5, device=\"cuda\")],\n ]\n\n def check_start_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[-1, -2], end_indices=[5, 5], strides=[7, 7]\n )\n fd.add_output(T1)\n\n def check_end_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[3, 4], end_indices=[1, 2], strides=[1, 1])\n fd.add_output(T1)\n\n def check_strides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[0, 0], end_indices=[5, 5], strides=[5, 5])\n fd.add_output(T1)\n\n def check_tensor_dims(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_start(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_end(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_stride(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_nostrides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[2, 2], end_indices=[4, 4])\n fd.add_output(T1)\n\n def legal(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[6, 6], end_indices=[8, 8], strides=[1, 1])\n fd.add_output(T1)\n\n checks = [\n (\n check_start_indices,\n \"Slice operation start_indices must be greater than or equal to 0..*\",\n ),\n (\n check_end_indices,\n \"Slice operation end_indices must be greater than or equal to start_indices..*\",\n ),\n (\n check_strides,\n \"nvFuser Limitation: All slice operation strides must be of const size 1.*\",\n ),\n (\n check_tensor_dims,\n \"Number of tensor dimensions does not match slice dimensions!.*\",\n ),\n (\n check_slice_dims_start,\n \"Slice start_indices and strides don't match!.*\",\n ),\n (\n check_slice_dims_end,\n \"Slice indexing attribute dimensions don't match!.*\",\n ),\n (\n check_slice_dims_stride,\n \"Slice start_indices and strides don't match!.*\",\n ),\n (check_nostrides, None),\n (legal, None),\n ]\n\n # Redirect stdout and stderr messages to log to avoid false positives in\n # the CI.\n stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n for combination in itertools.product(inputs, checks):\n inputs, (check, error_msg) = combination\n if error_msg is None:\n out = nvfuser_direct_test.exec_nvfuser(\n partial(check, acts=inputs), inputs, new_fusion_expected=None\n )\n else:\n with pytest.raises(RuntimeError, match=error_msg), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n nvfuser_direct_test.exec_nvfuser(\n partial(check, acts=inputs),\n inputs,\n )\n\n\n# Test that deterministic random ops (uniform, normal) give same results as\n# their stochastic versions\ndef test_deterministic_random(nvfuser_direct_test):\n inputs = [\n torch.randn([5, 9], device=\"cuda\", dtype=torch.float32),\n ]\n\n for rand_op_name in [\"uniform\", \"normal\"]:\n\n def fusion_func(fd: FusionDefinition, *, deterministic) -> None:\n t1 = fd.from_pytorch(inputs[0])\n a = fd.define_scalar(0.3, DataType.Float)\n b = fd.define_scalar(1.7, DataType.Float)\n rand_op = getattr(fd.ops, rand_op_name)\n if deterministic:\n rng_seed = fd.define_scalar(DataType.Int)\n rng_offset = fd.define_scalar(DataType.Int)\n u = rand_op(","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_deterministic_random","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_deterministic_random#L302-L360","kind":"function","name":"test_deterministic_random","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":302,"end_line":360,"context_start_line":282,"context_end_line":380,"code":" stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n for combination in itertools.product(inputs, checks):\n inputs, (check, error_msg) = combination\n if error_msg is None:\n out = nvfuser_direct_test.exec_nvfuser(\n partial(check, acts=inputs), inputs, new_fusion_expected=None\n )\n else:\n with pytest.raises(RuntimeError, match=error_msg), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n nvfuser_direct_test.exec_nvfuser(\n partial(check, acts=inputs),\n inputs,\n )\n\n\n# Test that deterministic random ops (uniform, normal) give same results as\n# their stochastic versions\ndef test_deterministic_random(nvfuser_direct_test):\n inputs = [\n torch.randn([5, 9], device=\"cuda\", dtype=torch.float32),\n ]\n\n for rand_op_name in [\"uniform\", \"normal\"]:\n\n def fusion_func(fd: FusionDefinition, *, deterministic) -> None:\n t1 = fd.from_pytorch(inputs[0])\n a = fd.define_scalar(0.3, DataType.Float)\n b = fd.define_scalar(1.7, DataType.Float)\n rand_op = getattr(fd.ops, rand_op_name)\n if deterministic:\n rng_seed = fd.define_scalar(DataType.Int)\n rng_offset = fd.define_scalar(DataType.Int)\n u = rand_op(\n a, b, shape=[5, 9], rng_seed=rng_seed, rng_offset=rng_offset\n )\n else:\n u = rand_op(a, b, shape=[5, 9])\n t2 = fd.ops.mul(t1, u)\n fd.add_output(t2)\n\n # exec_nvfuser tests printing and serde, so run that for each definition first\n nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, deterministic=False), inputs\n )\n nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, deterministic=True), [inputs[0], 0, 0]\n )\n\n # Now instantiate FusionDefinitions in each mode\n with FusionDefinition() as fd_stoch:\n fusion_func(fd_stoch, deterministic=False)\n with FusionDefinition() as fd_det:\n fusion_func(fd_det, deterministic=True)\n\n # Get the current RNG state to restore after this test.\n state = torch.cuda.get_rng_state()\n # Test with three different random seeds\n for _ in range(3):\n max_seed = 2**63 - 1\n seed = random.randint(0, max_seed)\n torch.manual_seed(seed)\n\n stateful_sequence = [fd_stoch.execute(inputs) for _ in range(10)]\n # Each call to uniform with DataType::Float will advance the offset by one\n # See Note [Divide offset by 4] in rng.cpp for more information\n stateless_sequence = [\n fd_det.execute([inputs[0], seed, rng_offset])\n for rng_offset in range(10)\n ]\n\n for i, (sful, sless) in enumerate(\n zip(stateful_sequence, stateless_sequence)\n ):\n nvfuser_direct_test.assertEqual(sful[0], sless[0])\n # Restore the RNG state\n torch.cuda.set_rng_state(state)\n\n\n# Test that the range of generated uniform values spans the proper range\n# https://github.com/NVIDIA/Fuser/issues/1653\ndef test_uniform_range(nvfuser_direct_test):\n dtypes = [DataType.Double, DataType.Float, DataType.Half, DataType.BFloat16]\n\n def run_test(left: float, right: float, dtype: DataType):\n samples_per_run = 2**29\n\n def fusion_fn(fd: FusionDefinition):\n # Generate enough values to reasonably expect to sample the ends of the range\n S0 = fd.define_scalar(left, dtype=DataType.Double)\n S1 = fd.define_scalar(right, dtype=DataType.Double)\n output = fd.ops.uniform(S0, S1, shape=[samples_per_run], dtype=dtype)\n fd.add_output(output)\n\n with FusionDefinition() as fd:\n fusion_fn(fd)\n","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_uniform_range","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_uniform_range#L365-L433","kind":"function","name":"test_uniform_range","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":365,"end_line":433,"context_start_line":345,"context_end_line":453,"code":" torch.manual_seed(seed)\n\n stateful_sequence = [fd_stoch.execute(inputs) for _ in range(10)]\n # Each call to uniform with DataType::Float will advance the offset by one\n # See Note [Divide offset by 4] in rng.cpp for more information\n stateless_sequence = [\n fd_det.execute([inputs[0], seed, rng_offset])\n for rng_offset in range(10)\n ]\n\n for i, (sful, sless) in enumerate(\n zip(stateful_sequence, stateless_sequence)\n ):\n nvfuser_direct_test.assertEqual(sful[0], sless[0])\n # Restore the RNG state\n torch.cuda.set_rng_state(state)\n\n\n# Test that the range of generated uniform values spans the proper range\n# https://github.com/NVIDIA/Fuser/issues/1653\ndef test_uniform_range(nvfuser_direct_test):\n dtypes = [DataType.Double, DataType.Float, DataType.Half, DataType.BFloat16]\n\n def run_test(left: float, right: float, dtype: DataType):\n samples_per_run = 2**29\n\n def fusion_fn(fd: FusionDefinition):\n # Generate enough values to reasonably expect to sample the ends of the range\n S0 = fd.define_scalar(left, dtype=DataType.Double)\n S1 = fd.define_scalar(right, dtype=DataType.Double)\n output = fd.ops.uniform(S0, S1, shape=[samples_per_run], dtype=dtype)\n fd.add_output(output)\n\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n output = fd.execute([])[0]\n\n x = output.amax()\n m = output.amin()\n mu = output.type(torch.float64).mean()\n # Repeat to improve chances of sampling extreme values\n num_runs = 100\n num_samples = num_runs * samples_per_run\n for i in range(num_runs):\n u = fd.execute([])[0]\n x = torch.maximum(x, u.amax())\n m = torch.minimum(m, u.amin())\n mu = mu + (u.type(torch.float64).mean() - mu) / (i + 2)\n\n # round-trip cast to find expected min\n theomin = torch.tensor(left, dtype=output.dtype).item()\n theomu = 0.5 * (right + left)\n theomax = torch.nextafter(\n torch.tensor(right, dtype=output.dtype),\n torch.tensor(left, dtype=output.dtype),\n )\n\n assert (\n m.item() >= theomin\n ), f\"{output.dtype} expected min generated value {theomin} but found {m.item()}\"\n assert (\n m.item() <= theomax\n ), f\"{output.dtype} expected max generated value {theomax} but found {x.item()}\"\n\n # uniform distribution on [0, 1) has mean 0.5 and variance 1/12\n # The standard error of the mean is then 1/sqrt(12 *\n # num_samples). We use the precision at 1.0 as a surrogate for\n # the contribution of rounding to the standard error of the\n # finite-precision mean.\n assert abs(mu.item() - theomu) < (right - left) * max(\n right - x.item(), 3.0 / math.sqrt(12 * num_samples)\n ), f\"{output.dtype} expected mean generated value {theomu} but found {mu.item()}\"\n\n if dtype not in [DataType.Float, DataType.Double]:\n # For reduced precision types, check that we sample the extreme\n # values. We don't do this for full precision types since the\n # amount of samples required would be too large.\n assert (\n m.item() == theomin\n ), f\"{output.dtype} expected min generated value {theomin} but found {m.item()}\"\n assert (\n x.item() == theomax\n ), f\"{output.dtype} expected max generated value {theomax} but found {x.item()}\"\n\n # test standard and non-standard uniform\n for left, right in [[0.0, 1.0], [-1.5, 3.7]]:\n for dtype in dtypes:\n run_test(left, right, dtype)\n\n\ndef test_cat_qwen2_v2(nvfuser_direct_test):\n def qwen2_cat_fusion_2(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2048, 512],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n S1 = fd.define_scalar(None, dtype=DataType.Int)\n S2 = fd.define_scalar(None, dtype=DataType.Int)\n T3 = fd.define_tensor(\n shape=[1, 4, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_cat_qwen2_v2","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_cat_qwen2_v2#L436-L624","kind":"function","name":"test_cat_qwen2_v2","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":436,"end_line":624,"context_start_line":416,"context_end_line":644,"code":" right - x.item(), 3.0 / math.sqrt(12 * num_samples)\n ), f\"{output.dtype} expected mean generated value {theomu} but found {mu.item()}\"\n\n if dtype not in [DataType.Float, DataType.Double]:\n # For reduced precision types, check that we sample the extreme\n # values. We don't do this for full precision types since the\n # amount of samples required would be too large.\n assert (\n m.item() == theomin\n ), f\"{output.dtype} expected min generated value {theomin} but found {m.item()}\"\n assert (\n x.item() == theomax\n ), f\"{output.dtype} expected max generated value {theomax} but found {x.item()}\"\n\n # test standard and non-standard uniform\n for left, right in [[0.0, 1.0], [-1.5, 3.7]]:\n for dtype in dtypes:\n run_test(left, right, dtype)\n\n\ndef test_cat_qwen2_v2(nvfuser_direct_test):\n def qwen2_cat_fusion_2(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2048, 512],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n S1 = fd.define_scalar(None, dtype=DataType.Int)\n S2 = fd.define_scalar(None, dtype=DataType.Int)\n T3 = fd.define_tensor(\n shape=[1, 4, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T5 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T6 = fd.define_tensor(\n shape=[1, 28, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T7 = fd.define_tensor(\n shape=[1, 2048, 512],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T12 = fd.ops.reshape(T0, new_shape=[1, 2048, 512])\n T13 = fd.ops.cast(T12, dtype=DataType.Float)\n S14 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S15 = fd.define_scalar(1.00000, dtype=DataType.Double)\n S16 = fd.define_scalar(1, dtype=DataType.Int)\n S17 = fd.define_scalar(2048, dtype=DataType.Int)\n S18 = fd.define_scalar(512, dtype=DataType.Int)\n T20 = fd.ops.uniform(\n S14,\n S15,\n shape=[S16, S17, S18],\n rng_seed=S2,\n rng_offset=S1,\n dtype=DataType.BFloat16,\n )\n S21 = fd.define_scalar(4.00000, dtype=DataType.Double)\n T22 = fd.ops.mul(T13, S21)\n S23 = fd.define_scalar(0.900000, dtype=DataType.Double)\n T24 = fd.ops.lt(T20, S23)\n T25 = fd.ops.cast(T24, dtype=DataType.Float)\n T41 = fd.ops.slice(\n T3,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 4, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T42 = fd.ops.mul(T22, T25)\n T43 = fd.ops.cast(T41, dtype=DataType.Float)\n T44 = fd.ops.neg(T43)\n T50 = fd.ops.broadcast_in_dim(\n T4, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3]\n )\n T66 = fd.ops.slice(\n T3,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 4, 2048, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T67 = fd.ops.cast(T44, dtype=DataType.BFloat16)\n T73 = fd.ops.broadcast_in_dim(\n T5, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3]\n )\n T89 = fd.ops.slice(\n T6,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 28, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n S90 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T91 = fd.ops.mul(T42, S90)\n T97 = fd.ops.broadcast_in_dim(\n T50, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T98 = fd.ops.cat([T67, T66], dim=-1, manual_padding=0)\n T104 = fd.ops.broadcast_in_dim(\n T73, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T105 = fd.ops.cast(T89, dtype=DataType.Float)\n T106 = fd.ops.cast(T97, dtype=DataType.Float)\n T107 = fd.ops.cast(T98, dtype=DataType.Float)\n T108 = fd.ops.cast(T104, dtype=DataType.Float)\n T109 = fd.ops.cast(T3, dtype=DataType.Float)\n T110 = fd.ops.neg(T105)\n T111 = fd.ops.cast(T7, dtype=DataType.Float)\n T112 = fd.ops.mul(T107, T106)\n T113 = fd.ops.mul(T109, T108)\n T129 = fd.ops.slice(\n T6,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 28, 2048, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T130 = fd.ops.cast(T110, dtype=DataType.BFloat16)\n T131 = fd.ops.add(T111, T91)\n T137 = fd.ops.broadcast_in_dim(\n T50, shape=[1, 28, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T138 = fd.ops.cat([T130, T129], dim=-1, manual_padding=0)\n T144 = fd.ops.broadcast_in_dim(\n T73, shape=[1, 28, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T145 = fd.ops.cast(T131, dtype=DataType.BFloat16)\n T146 = fd.ops.cast(T137, dtype=DataType.Float)\n T147 = fd.ops.cast(T138, dtype=DataType.Float)\n T148 = fd.ops.cast(T144, dtype=DataType.Float)\n T149 = fd.ops.cast(T6, dtype=DataType.Float)\n T155 = fd.ops.reshape(T145, new_shape=[1, 2048, 4, 128])\n T156 = fd.ops.add(T113, T112)\n T157 = fd.ops.mul(T147, T146)\n T158 = fd.ops.mul(T149, T148)\n T159 = fd.ops.permute(T155, dims=[0, 2, 1, 3])\n T160 = fd.ops.cast(T156, dtype=DataType.BFloat16)\n T167 = fd.ops.broadcast_in_dim(\n T159, shape=[1, 4, 1, 2048, 128], broadcast_dims=[0, 1, 3, 4]\n )\n T174 = fd.ops.broadcast_in_dim(\n T160, shape=[1, 4, 1, 2048, 128], broadcast_dims=[0, 1, 3, 4]\n )\n T181 = fd.ops.broadcast_in_dim(\n T167, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T188 = fd.ops.broadcast_in_dim(\n T174, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T189 = fd.ops.add(T158, T157)\n T195 = fd.ops.reshape(T181, new_shape=[1, 28, 2048, 128])\n T201 = fd.ops.reshape(T188, new_shape=[1, 28, 2048, 128])\n T202 = fd.ops.cast(T189, dtype=DataType.BFloat16)\n T203 = fd.ops.stride_order(T195, stride_order=[3, 2, 1, 0])\n T204 = fd.ops.stride_order(T201, stride_order=[3, 2, 1, 0])\n T205 = fd.ops.stride_order(T202, stride_order=[3, 2, 1, 0])\n fd.add_output(T159)\n fd.add_output(T160)\n fd.add_output(T203)\n fd.add_output(T204)\n fd.add_output(T205)\n\n inputs = [\n torch.testing.make_tensor((2048, 512), dtype=torch.bfloat16, device=\"cuda:0\"),\n 25546,\n 1400552702872758,\n torch.randn(1048576, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 4, 2048, 128), (1048576, 128, 512, 1)\n ),\n torch.randn(262144, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 128), (262144, 1, 2048)\n ),\n torch.randn(262144, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 128), (262144, 1, 2048)\n ),\n torch.randn(7340032, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 28, 2048, 128), (7340032, 128, 3584, 1)\n ),\n torch.testing.make_tensor(\n (1, 2048, 512), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n ]\n\n nvfuser_direct_test.exec_nvfuser(qwen2_cat_fusion_2, inputs)\n\n\ndef test_nanogpt_mha_dpa(nvfuser_direct_test):\n inputs = [\n torch.randn(16, 16, 128, 128, device=\"cuda\"),\n torch.randn(1, 1, 1024, 1024, device=\"cuda\"),\n ]\n\n def nvfuser_fusion(fd: FusionDefinition, prob) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, 1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_nanogpt_mha_dpa","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_nanogpt_mha_dpa#L627-L715","kind":"function","name":"test_nanogpt_mha_dpa","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":627,"end_line":715,"context_start_line":607,"context_end_line":735,"code":" torch.randn(1048576, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 4, 2048, 128), (1048576, 128, 512, 1)\n ),\n torch.randn(262144, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 128), (262144, 1, 2048)\n ),\n torch.randn(262144, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 128), (262144, 1, 2048)\n ),\n torch.randn(7340032, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 28, 2048, 128), (7340032, 128, 3584, 1)\n ),\n torch.testing.make_tensor(\n (1, 2048, 512), dtype=torch.bfloat16, device=\"cuda:0\"\n ),\n ]\n\n nvfuser_direct_test.exec_nvfuser(qwen2_cat_fusion_2, inputs)\n\n\ndef test_nanogpt_mha_dpa(nvfuser_direct_test):\n inputs = [\n torch.randn(16, 16, 128, 128, device=\"cuda\"),\n torch.randn(1, 1, 1024, 1024, device=\"cuda\"),\n ]\n\n def nvfuser_fusion(fd: FusionDefinition, prob) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, 1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n S2 = fd.define_scalar(0.125000, dtype=DataType.Double)\n T3 = fd.ops.mul(T0, S2)\n T4 = fd.ops.slice(\n T1,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 1, 128, 128],\n strides=[1, 1, 1, 1],\n )\n S5 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T6 = fd.ops.eq(S5, T4)\n T7 = fd.ops.broadcast_in_dim(\n T6, shape=[16, 16, 128, 128], broadcast_dims=[0, 1, 2, 3]\n )\n S8 = fd.define_scalar(float(\"-inf\"), dtype=DataType.Double)\n T9 = fd.ops.where(T7, S8, T3)\n S10 = fd.define_scalar(-1, dtype=DataType.Int)\n S11 = fd.define_scalar(4, dtype=DataType.Int)\n S12 = fd.ops.add(S10, S11)\n T13 = fd.ops.max(T9, dims=[3], keepdim=False, dtype=DataType.Null)\n T14 = fd.ops.broadcast_in_dim(\n T13, shape=[16, 16, 128, 1], broadcast_dims=[0, 1, 2]\n )\n T15 = fd.ops.broadcast_in_dim(\n T14, shape=[16, 16, 128, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T16 = fd.ops.sub(T9, T15)\n T17 = fd.ops.exp(T16)\n S18 = fd.define_scalar(-1, dtype=DataType.Int)\n S19 = fd.define_scalar(4, dtype=DataType.Int)\n S20 = fd.ops.add(S18, S19)\n T21 = fd.ops.sum(T17, dims=[3], keepdim=False, dtype=DataType.Null)\n T22 = fd.ops.broadcast_in_dim(\n T21, shape=[16, 16, 128, 1], broadcast_dims=[0, 1, 2]\n )\n T23 = fd.ops.broadcast_in_dim(\n T22, shape=[16, 16, 128, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T24 = fd.ops.div(T17, T23)\n S25 = fd.define_scalar(16, dtype=DataType.Int)\n S26 = fd.define_scalar(16, dtype=DataType.Int)\n S27 = fd.define_scalar(128, dtype=DataType.Int)\n S28 = fd.define_scalar(128, dtype=DataType.Int)\n S29 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S30 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T31 = fd.ops.uniform(S29, S30, shape=[S25, S26, S27, S28], dtype=DataType.Float)\n S32 = fd.define_scalar(1.0 - prob, dtype=DataType.Double)\n T33 = fd.ops.lt(T31, S32)\n T34 = fd.ops.cast(T33, dtype=DataType.Float)\n T35 = fd.ops.mul(T24, T34)\n S36 = fd.define_scalar(1.0 / (1.0 - prob), dtype=DataType.Double)\n T37 = fd.ops.mul(T35, S36)\n fd.add_output(T37)\n\n def torch_def(acts, bias, n_seq_len, n_head_dim, prob):\n att = acts * (1.0 / math.sqrt(n_head_dim))\n att = att.masked_fill(bias[:, :, :n_seq_len, :n_seq_len] == 0, float(\"-inf\"))\n att = torch.nn.functional.softmax(att, dim=-1)\n att = torch.nn.functional.dropout(att, p=prob)\n return att\n\n # NOTE: The dropout probabilities need to be set to 0 elements zeroed out\n # in order to match implementations as eager and nvFuser do not have matching\n # blocking.\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(nvfuser_fusion, prob=0.0), inputs\n )\n eager_out = torch_def(inputs[0], inputs[1], 128, 64, 0.0)\n\n for idx in range(len(nvf_out)):\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[idx])\n\n\ndef test_nanogpt_split_mha_linears(nvfuser_direct_test):\n inputs = [\n torch.randn(16, 128, 3072, device=\"cuda\"),\n ]\n\n def nvfuser_fusion_0(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T0_slice1 = fd.ops.slice(T0, [0, 0, 0], [16, 128, 1024], [1, 1, 1])\n T0_slice2 = fd.ops.slice(T0, [0, 0, 1024], [16, 128, 2048], [1, 1, 1])\n T0_slice3 = fd.ops.slice(T0, [0, 0, 2048], [16, 128, 3072], [1, 1, 1])\n T1_slice1 = fd.ops.reshape(T0_slice1, [16, 128, 16, 64])\n T1_slice2 = fd.ops.reshape(T0_slice2, [16, 128, 16, 64])\n T1_slice3 = fd.ops.reshape(T0_slice3, [16, 128, 16, 64])\n T2_slice1 = fd.ops.permute(T1_slice1, [0, 2, 1, 3])\n T2_slice2 = fd.ops.permute(T1_slice2, [0, 2, 1, 3])\n T2_slice3 = fd.ops.permute(T1_slice3, [0, 2, 1, 3])\n fd.add_output(T2_slice1)\n fd.add_output(T2_slice2)","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_nanogpt_split_mha_linears","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_nanogpt_split_mha_linears#L718-L797","kind":"function","name":"test_nanogpt_split_mha_linears","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":718,"end_line":797,"context_start_line":698,"context_end_line":817,"code":"\n def torch_def(acts, bias, n_seq_len, n_head_dim, prob):\n att = acts * (1.0 / math.sqrt(n_head_dim))\n att = att.masked_fill(bias[:, :, :n_seq_len, :n_seq_len] == 0, float(\"-inf\"))\n att = torch.nn.functional.softmax(att, dim=-1)\n att = torch.nn.functional.dropout(att, p=prob)\n return att\n\n # NOTE: The dropout probabilities need to be set to 0 elements zeroed out\n # in order to match implementations as eager and nvFuser do not have matching\n # blocking.\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(nvfuser_fusion, prob=0.0), inputs\n )\n eager_out = torch_def(inputs[0], inputs[1], 128, 64, 0.0)\n\n for idx in range(len(nvf_out)):\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[idx])\n\n\ndef test_nanogpt_split_mha_linears(nvfuser_direct_test):\n inputs = [\n torch.randn(16, 128, 3072, device=\"cuda\"),\n ]\n\n def nvfuser_fusion_0(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T0_slice1 = fd.ops.slice(T0, [0, 0, 0], [16, 128, 1024], [1, 1, 1])\n T0_slice2 = fd.ops.slice(T0, [0, 0, 1024], [16, 128, 2048], [1, 1, 1])\n T0_slice3 = fd.ops.slice(T0, [0, 0, 2048], [16, 128, 3072], [1, 1, 1])\n T1_slice1 = fd.ops.reshape(T0_slice1, [16, 128, 16, 64])\n T1_slice2 = fd.ops.reshape(T0_slice2, [16, 128, 16, 64])\n T1_slice3 = fd.ops.reshape(T0_slice3, [16, 128, 16, 64])\n T2_slice1 = fd.ops.permute(T1_slice1, [0, 2, 1, 3])\n T2_slice2 = fd.ops.permute(T1_slice2, [0, 2, 1, 3])\n T2_slice3 = fd.ops.permute(T1_slice3, [0, 2, 1, 3])\n fd.add_output(T2_slice1)\n fd.add_output(T2_slice2)\n fd.add_output(T2_slice3)\n\n def torch_def_0(acts, n_embd, n_head):\n B, T, C = acts.size()\n q, k, v = acts.split(n_embd, dim=2)\n k = k.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n q = q.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n v = v.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n return (\n q,\n k,\n v,\n )\n\n def nvfuser_fusion_1(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 0],\n end_indices=[16, 128, 1024],\n strides=[1, 1, 1],\n )\n T2 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 1024],\n end_indices=[16, 128, 2048],\n strides=[1, 1, 1],\n )\n T3 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 2048],\n end_indices=[16, 128, 3072],\n strides=[1, 1, 1],\n )\n fd.add_output(T1)\n fd.add_output(T2)\n fd.add_output(T3)\n\n def torch_def_1(acts, n_embd, n_head):\n B, T, C = acts.size()\n q, k, v = acts.split(n_embd, dim=2)\n return (\n q,\n k,\n v,\n )\n\n tests = [\n (nvfuser_fusion_0, torch_def_0),\n (nvfuser_fusion_1, torch_def_1),\n ]\n\n for nvf_func, torch_func in tests:\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(nvf_func, inputs)\n eager_out = torch_func(*inputs, 1024, 16)\n for idx in range(len(eager_out)):\n nvfuser_direct_test.assertEqual(eager_out[idx], nvf_out[idx])\n\n\ndef test_prim_layer_norm_fwd(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, requires_grad=True),\n torch.nn.Parameter(torch.randn(input_size[2], dtype=dtype, device=device)),\n torch.nn.Parameter(torch.randn(input_size[2], dtype=dtype, device=device)),\n ]\n\n def primitive_definition(\n inputs: torch.Tensor,\n weight: torch.Tensor,\n bias: torch.Tensor,\n normalization_axis: int,\n keepdim: bool,\n ) -> torch.Tensor:\n mean = inputs.mean(normalization_axis, keepdim=keepdim)","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_prim_layer_norm_fwd","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_prim_layer_norm_fwd#L800-L921","kind":"function","name":"test_prim_layer_norm_fwd","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":800,"end_line":921,"context_start_line":780,"context_end_line":941,"code":" B, T, C = acts.size()\n q, k, v = acts.split(n_embd, dim=2)\n return (\n q,\n k,\n v,\n )\n\n tests = [\n (nvfuser_fusion_0, torch_def_0),\n (nvfuser_fusion_1, torch_def_1),\n ]\n\n for nvf_func, torch_func in tests:\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(nvf_func, inputs)\n eager_out = torch_func(*inputs, 1024, 16)\n for idx in range(len(eager_out)):\n nvfuser_direct_test.assertEqual(eager_out[idx], nvf_out[idx])\n\n\ndef test_prim_layer_norm_fwd(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, requires_grad=True),\n torch.nn.Parameter(torch.randn(input_size[2], dtype=dtype, device=device)),\n torch.nn.Parameter(torch.randn(input_size[2], dtype=dtype, device=device)),\n ]\n\n def primitive_definition(\n inputs: torch.Tensor,\n weight: torch.Tensor,\n bias: torch.Tensor,\n normalization_axis: int,\n keepdim: bool,\n ) -> torch.Tensor:\n mean = inputs.mean(normalization_axis, keepdim=keepdim)\n diff = inputs - mean\n diff_sq = diff * diff\n var = diff_sq.mean(normalization_axis, keepdim=keepdim)\n pre_shift_scale_norm_output = (inputs - mean) / torch.sqrt(var + 1e-12)\n norm_output = weight * pre_shift_scale_norm_output + bias\n return norm_output\n\n def nvfuser_fusion(\n fd: FusionDefinition,\n normalization_axis: int,\n norm_size: int,\n input_shape: List[int],\n eps: float,\n keepDim: bool,\n ) -> None:\n inputs = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n )\n weights = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float)\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float)\n sum0 = fd.ops.sum(inputs, dims=[normalization_axis], keepdim=keepDim)\n norm_const = fd.define_scalar(norm_size)\n mean = fd.ops.div(sum0, norm_const)\n diff = fd.ops.sub(inputs, mean)\n diff_sq = fd.ops.mul(diff, diff)\n sum1 = fd.ops.sum(diff_sq, dims=[normalization_axis], keepdim=keepDim)\n var = fd.ops.div(sum1, norm_const)\n eps_const = fd.define_scalar(eps)\n var_eps = fd.ops.add(var, eps_const)\n invstd = fd.ops.rsqrt(var_eps)\n pre_scale_bias = fd.ops.mul(diff, invstd)\n weights_bcast = fd.ops.broadcast_in_dim(\n weights, shape=input_shape, broadcast_dims=[2]\n )\n scale = fd.ops.mul(pre_scale_bias, weights_bcast)\n bias_bcast = fd.ops.broadcast_in_dim(\n bias, shape=input_shape, broadcast_dims=[2]\n )\n out = fd.ops.add(scale, bias_bcast)\n fd.add_output(out)\n fd.add_output(mean)\n fd.add_output(invstd)\n\n def nvfuser_fusion_var_mean(\n fd: FusionDefinition,\n normalization_axis: int,\n norm_size: int,\n input_shape: List[int],\n eps: float,\n keepDim: bool,\n ) -> None:\n inputs = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n )\n weights = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float)\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float)\n var, mean = fd.ops.var_mean(\n inputs, dims=[normalization_axis], correction=0, keepdim=keepDim\n )\n eps_const = fd.define_scalar(eps)\n var_eps = fd.ops.add(var, eps_const)\n invstd = fd.ops.rsqrt(var_eps)\n diff = fd.ops.sub(inputs, mean)\n pre_scale_bias = fd.ops.mul(diff, invstd)\n weights_bcast = fd.ops.broadcast_in_dim(\n weights, shape=input_shape, broadcast_dims=[2]\n )\n scale = fd.ops.mul(pre_scale_bias, weights_bcast)\n bias_bcast = fd.ops.broadcast_in_dim(\n bias, shape=input_shape, broadcast_dims=[2]\n )\n out = fd.ops.add(scale, bias_bcast)\n fd.add_output(out)\n fd.add_output(mean)\n fd.add_output(invstd)\n\n fusion_func_1 = partial(\n nvfuser_fusion,\n normalization_axis=2,\n norm_size=inputs[0].size()[2],\n input_shape=inputs[0].size(),\n eps=1e-12,\n keepDim=True,\n )\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_1, inputs)\n\n fusion_func_2 = partial(\n nvfuser_fusion_var_mean,\n normalization_axis=2,\n norm_size=inputs[0].size()[2],\n input_shape=inputs[0].size(),\n eps=1e-12,\n keepDim=True,\n )\n nvf_var_mean_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_2, inputs)\n\n eager_out = primitive_definition(inputs[0], inputs[1], inputs[2], 2, True)\n\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n nvfuser_direct_test.assertEqual(eager_out, nvf_var_mean_out[0])\n\n\ndef test_prim_rms_norm_fwd(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, requires_grad=True),\n torch.nn.Parameter(torch.randn(input_size[2], dtype=dtype, device=device)),\n ]\n\n def primitive_definition(\n inputs: torch.Tensor,\n weight: torch.Tensor,\n normalization_axis: int,\n keepdim: bool,\n ) -> torch.Tensor:\n var = inputs.mul(inputs).mean(normalization_axis, keepdim)\n pre_shift_scale_norm_output = inputs / torch.sqrt(var + 1e-12)\n norm_output = weight * pre_shift_scale_norm_output","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_prim_rms_norm_fwd","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_prim_rms_norm_fwd#L924-L985","kind":"function","name":"test_prim_rms_norm_fwd","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":924,"end_line":985,"context_start_line":904,"context_end_line":1005,"code":" keepDim=True,\n )\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_1, inputs)\n\n fusion_func_2 = partial(\n nvfuser_fusion_var_mean,\n normalization_axis=2,\n norm_size=inputs[0].size()[2],\n input_shape=inputs[0].size(),\n eps=1e-12,\n keepDim=True,\n )\n nvf_var_mean_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_2, inputs)\n\n eager_out = primitive_definition(inputs[0], inputs[1], inputs[2], 2, True)\n\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n nvfuser_direct_test.assertEqual(eager_out, nvf_var_mean_out[0])\n\n\ndef test_prim_rms_norm_fwd(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, requires_grad=True),\n torch.nn.Parameter(torch.randn(input_size[2], dtype=dtype, device=device)),\n ]\n\n def primitive_definition(\n inputs: torch.Tensor,\n weight: torch.Tensor,\n normalization_axis: int,\n keepdim: bool,\n ) -> torch.Tensor:\n var = inputs.mul(inputs).mean(normalization_axis, keepdim)\n pre_shift_scale_norm_output = inputs / torch.sqrt(var + 1e-12)\n norm_output = weight * pre_shift_scale_norm_output\n return norm_output\n\n def nvfuser_fusion(\n fd: FusionDefinition,\n normalization_axis: int,\n norm_size: int,\n input_shape: List[int],\n eps: float,\n keepDim: bool,\n ) -> None:\n inputs = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n )\n weights = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float)\n inputs_sq = fd.ops.mul(inputs, inputs)\n sum0 = fd.ops.sum(inputs_sq, dims=[normalization_axis], keepdim=keepDim)\n norm_const = fd.define_scalar(norm_size)\n var = fd.ops.div(sum0, norm_const)\n eps_const = fd.define_scalar(eps)\n var_eps = fd.ops.add(var, eps_const)\n invstd = fd.ops.rsqrt(var_eps)\n pre_scale = fd.ops.mul(inputs, invstd)\n weights_bcast = fd.ops.broadcast_in_dim(\n weights, shape=input_shape, broadcast_dims=[2]\n )\n out = fd.ops.mul(pre_scale, weights_bcast)\n fd.add_output(out)\n fd.add_output(invstd)\n\n fusion_func = partial(\n nvfuser_fusion,\n normalization_axis=2,\n norm_size=inputs[0].size()[2],\n input_shape=inputs[0].size(),\n eps=1e-12,\n keepDim=True,\n )\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = primitive_definition(inputs[0], inputs[1], 2, True)\n\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_litgpt_variants_gpt_neox_like(nvfuser_direct_test):\n \"\"\"\n This test hits a segfault in nvfuser::preseg_passes::MovePadPass::replaceCat.\n The old optimization pass updates the fusion within the filterByType generator\n This causes a dynamic cast on a dangling pointer.\n \"\"\"\n\n def nvfuser_fusion_id4(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[128, 16],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[128, 16],\n contiguity=[True, True],","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.test_litgpt_variants_gpt_neox_like","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.test_litgpt_variants_gpt_neox_like#L988-L1130","kind":"function","name":"test_litgpt_variants_gpt_neox_like","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":988,"end_line":1130,"context_start_line":968,"context_end_line":1130,"code":" )\n out = fd.ops.mul(pre_scale, weights_bcast)\n fd.add_output(out)\n fd.add_output(invstd)\n\n fusion_func = partial(\n nvfuser_fusion,\n normalization_axis=2,\n norm_size=inputs[0].size()[2],\n input_shape=inputs[0].size(),\n eps=1e-12,\n keepDim=True,\n )\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = primitive_definition(inputs[0], inputs[1], 2, True)\n\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_litgpt_variants_gpt_neox_like(nvfuser_direct_test):\n \"\"\"\n This test hits a segfault in nvfuser::preseg_passes::MovePadPass::replaceCat.\n The old optimization pass updates the fusion within the filterByType generator\n This causes a dynamic cast on a dangling pointer.\n \"\"\"\n\n def nvfuser_fusion_id4(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[128, 16],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[128, 16],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[5, 5, 192],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T12 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[5, 16], strides=[1, 1]\n )\n T22 = fd.ops.slice(\n T1, start_indices=[0, 0], end_indices=[5, 16], strides=[1, 1]\n )\n T29 = fd.ops.reshape(T2, new_shape=[5, 5, 4, 3, 16])\n T30 = fd.ops.permute(T29, dims=[0, 2, 3, 1, 4])\n T49 = fd.ops.slice(\n T30,\n start_indices=[0, 0, 0, 0, 0],\n end_indices=[5, 4, 1, 5, 16],\n strides=[1, 1, 1, 1, 1],\n )\n T68 = fd.ops.slice(\n T30,\n start_indices=[0, 0, 1, 0, 0],\n end_indices=[5, 4, 2, 5, 16],\n strides=[1, 1, 1, 1, 1],\n )\n T87 = fd.ops.slice(\n T30,\n start_indices=[0, 0, 2, 0, 0],\n end_indices=[5, 4, 3, 5, 16],\n strides=[1, 1, 1, 1, 1],\n )\n T93 = fd.ops.reshape(T49, new_shape=[5, 4, 5, 16])\n T99 = fd.ops.reshape(T68, new_shape=[5, 4, 5, 16])\n T105 = fd.ops.reshape(T87, new_shape=[5, 4, 5, 16])\n T121 = fd.ops.slice(\n T93,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 8],\n strides=[1, 1, 1, 1],\n )\n T137 = fd.ops.slice(\n T93,\n start_indices=[0, 0, 0, 8],\n end_indices=[5, 4, 5, 16],\n strides=[1, 1, 1, 1],\n )\n T138 = fd.ops.neg(T137)\n T139 = fd.ops.cat([T138, T121], dim=-1)\n S140 = fd.define_scalar(5, dtype=DataType.Int)\n S141 = fd.define_scalar(4, dtype=DataType.Int)\n S142 = fd.define_scalar(5, dtype=DataType.Int)\n S143 = fd.define_scalar(16, dtype=DataType.Int)\n T145 = fd.ops.broadcast_in_dim(\n T12, shape=[S140, S141, S142, S143], broadcast_dims=[2, 3]\n )\n T146 = fd.ops.mul(T93, T145)\n S147 = fd.define_scalar(5, dtype=DataType.Int)\n S148 = fd.define_scalar(4, dtype=DataType.Int)\n S149 = fd.define_scalar(5, dtype=DataType.Int)\n S150 = fd.define_scalar(16, dtype=DataType.Int)\n T152 = fd.ops.broadcast_in_dim(\n T22, shape=[S147, S148, S149, S150], broadcast_dims=[2, 3]\n )\n T153 = fd.ops.mul(T139, T152)\n T154 = fd.ops.add(T146, T153)\n T170 = fd.ops.slice(\n T99,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 8],\n strides=[1, 1, 1, 1],\n )\n T186 = fd.ops.slice(\n T99,\n start_indices=[0, 0, 0, 8],\n end_indices=[5, 4, 5, 16],\n strides=[1, 1, 1, 1],\n )\n T187 = fd.ops.neg(T186)\n T188 = fd.ops.cat([T187, T170], dim=-1)\n T189 = fd.ops.mul(T99, T145)\n T190 = fd.ops.mul(T188, T152)\n T191 = fd.ops.add(T189, T190)\n T207 = fd.ops.slice(\n T93,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 0],\n strides=[1, 1, 1, 1],\n )\n T208 = fd.ops.cat([T154, T207], dim=-1)\n T224 = fd.ops.slice(\n T99,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 0],\n strides=[1, 1, 1, 1],\n )\n T225 = fd.ops.cat([T191, T224], dim=-1)\n S226 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T227 = fd.ops.mul(T208, S226)\n T228 = fd.ops.permute(T225, dims=[0, 1, 3, 2])\n S229 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T230 = fd.ops.mul(T228, S229)\n fd.add_output(T105)\n fd.add_output(T145)\n fd.add_output(T152)\n fd.add_output(T227)\n fd.add_output(T230)\n\n with FusionDefinition() as fd:\n nvfuser_fusion_id4(fd)\n\n inputs = [\n torch.testing.make_tensor((128, 16), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((128, 16), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((5, 5, 192), dtype=torch.float32, device=\"cuda:0\"),\n ]\n fd.validate(inputs)\n\n # check python reproduction\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id4, inputs)","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.fusion_func_1","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.fusion_func_1#L32-L39","kind":"function","name":"fusion_func_1","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":32,"end_line":39,"context_start_line":12,"context_end_line":59,"code":"import pytest\n\nfrom nvfuser_direct import FusionDefinition, DataType\nimport random\nimport itertools\nimport math\nfrom functools import partial\nfrom typing import List\n\n\ndef test_broadcast_in_dim_with_dynamic_shapes(nvfuser_direct_test):\n inputs_1 = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(4, device=\"cuda\"),\n ]\n inputs_2 = [\n torch.randn(2, 3, 1024, device=\"cuda\"),\n torch.randn(1024, device=\"cuda\"),\n ]\n\n def fusion_func_1(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_2(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_1[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_3(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_2[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n # Func_1 uses tensor.shape() to propagate dynamic size, therefore, it is","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.fusion_func_2","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.fusion_func_2#L41-L48","kind":"function","name":"fusion_func_2","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":41,"end_line":48,"context_start_line":21,"context_end_line":68,"code":"\ndef test_broadcast_in_dim_with_dynamic_shapes(nvfuser_direct_test):\n inputs_1 = [\n torch.randn(2, 3, 4, device=\"cuda\"),\n torch.randn(4, device=\"cuda\"),\n ]\n inputs_2 = [\n torch.randn(2, 3, 1024, device=\"cuda\"),\n torch.randn(1024, device=\"cuda\"),\n ]\n\n def fusion_func_1(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_2(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_1[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_3(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_2[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n # Func_1 uses tensor.shape() to propagate dynamic size, therefore, it is\n # expected that test 2 should be cached based on test 2\n\n # Test 1\n inputs = inputs_1\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_1, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.fusion_func_3","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.fusion_func_3#L50-L57","kind":"function","name":"fusion_func_3","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":50,"end_line":57,"context_start_line":30,"context_end_line":77,"code":" ]\n\n def fusion_func_1(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, t0.shape(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_2(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_1[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n def fusion_func_3(fd: FusionDefinition):\n t0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True])\n t1 = fd.define_tensor(shape=[-1], contiguity=[True])\n\n t1_b = fd.ops.broadcast_in_dim(t1, inputs_2[0].size(), [2])\n t2 = fd.ops.add(t0, t1_b)\n\n fd.add_output(t2)\n\n # Func_1 uses tensor.shape() to propagate dynamic size, therefore, it is\n # expected that test 2 should be cached based on test 2\n\n # Test 1\n inputs = inputs_1\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_1, inputs)\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n # Test 2\n inputs = inputs_2\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n fusion_func_1, inputs, new_fusion_expected=False\n )\n eager_out = refs.add(\n inputs[0], prims.broadcast_in_dim(inputs[1], inputs[0].size(), [2])\n )","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.fusion_func","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.fusion_func#L309-L323","kind":"function","name":"fusion_func","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":309,"end_line":323,"context_start_line":289,"context_end_line":343,"code":" )\n else:\n with pytest.raises(RuntimeError, match=error_msg), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n nvfuser_direct_test.exec_nvfuser(\n partial(check, acts=inputs),\n inputs,\n )\n\n\n# Test that deterministic random ops (uniform, normal) give same results as\n# their stochastic versions\ndef test_deterministic_random(nvfuser_direct_test):\n inputs = [\n torch.randn([5, 9], device=\"cuda\", dtype=torch.float32),\n ]\n\n for rand_op_name in [\"uniform\", \"normal\"]:\n\n def fusion_func(fd: FusionDefinition, *, deterministic) -> None:\n t1 = fd.from_pytorch(inputs[0])\n a = fd.define_scalar(0.3, DataType.Float)\n b = fd.define_scalar(1.7, DataType.Float)\n rand_op = getattr(fd.ops, rand_op_name)\n if deterministic:\n rng_seed = fd.define_scalar(DataType.Int)\n rng_offset = fd.define_scalar(DataType.Int)\n u = rand_op(\n a, b, shape=[5, 9], rng_seed=rng_seed, rng_offset=rng_offset\n )\n else:\n u = rand_op(a, b, shape=[5, 9])\n t2 = fd.ops.mul(t1, u)\n fd.add_output(t2)\n\n # exec_nvfuser tests printing and serde, so run that for each definition first\n nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, deterministic=False), inputs\n )\n nvfuser_direct_test.exec_nvfuser(\n partial(fusion_func, deterministic=True), [inputs[0], 0, 0]\n )\n\n # Now instantiate FusionDefinitions in each mode\n with FusionDefinition() as fd_stoch:\n fusion_func(fd_stoch, deterministic=False)\n with FusionDefinition() as fd_det:\n fusion_func(fd_det, deterministic=True)\n\n # Get the current RNG state to restore after this test.\n state = torch.cuda.get_rng_state()\n # Test with three different random seeds\n for _ in range(3):\n max_seed = 2**63 - 1","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.check_start_indices","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.check_start_indices#L192-L197","kind":"function","name":"check_start_indices","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":192,"end_line":197,"context_start_line":172,"context_end_line":217,"code":" t12 = inputs[1] * inputs[-2]\n t13 = torch.permute(t12, [0, 1, 3, 2])\n t14 = inputs[0] * inputs[-3]\n t15 = torch.permute(t14, [0, 2, 1, 3])\n t20 = torch.reshape(t15, [4, 64, 768])\n t21 = torch.permute(t13, [0, 2, 1, 3])\n t26 = torch.reshape(t21, [4, 64, 768])\n t27 = torch.cat([t20, t26, inputs[-1]], dim=2)\n t28 = t27.sum([0, 1])\n\n nvfuser_direct_test.assertEqual(nvf_out[0], t27)\n nvfuser_direct_test.assertEqual(nvf_out[1], t28)\n\n\ndef test_slice_error_checks(nvfuser_direct_test):\n inputs = [\n [torch.randn(10, 10, device=\"cuda\")],\n [torch.randn(5, 5, device=\"cuda\")],\n ]\n\n def check_start_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[-1, -2], end_indices=[5, 5], strides=[7, 7]\n )\n fd.add_output(T1)\n\n def check_end_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[3, 4], end_indices=[1, 2], strides=[1, 1])\n fd.add_output(T1)\n\n def check_strides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[0, 0], end_indices=[5, 5], strides=[5, 5])\n fd.add_output(T1)\n\n def check_tensor_dims(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_start(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.check_end_indices","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.check_end_indices#L199-L202","kind":"function","name":"check_end_indices","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":199,"end_line":202,"context_start_line":179,"context_end_line":222,"code":" t27 = torch.cat([t20, t26, inputs[-1]], dim=2)\n t28 = t27.sum([0, 1])\n\n nvfuser_direct_test.assertEqual(nvf_out[0], t27)\n nvfuser_direct_test.assertEqual(nvf_out[1], t28)\n\n\ndef test_slice_error_checks(nvfuser_direct_test):\n inputs = [\n [torch.randn(10, 10, device=\"cuda\")],\n [torch.randn(5, 5, device=\"cuda\")],\n ]\n\n def check_start_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[-1, -2], end_indices=[5, 5], strides=[7, 7]\n )\n fd.add_output(T1)\n\n def check_end_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[3, 4], end_indices=[1, 2], strides=[1, 1])\n fd.add_output(T1)\n\n def check_strides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[0, 0], end_indices=[5, 5], strides=[5, 5])\n fd.add_output(T1)\n\n def check_tensor_dims(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_start(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.check_strides","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.check_strides#L204-L207","kind":"function","name":"check_strides","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":204,"end_line":207,"context_start_line":184,"context_end_line":227,"code":"\n\ndef test_slice_error_checks(nvfuser_direct_test):\n inputs = [\n [torch.randn(10, 10, device=\"cuda\")],\n [torch.randn(5, 5, device=\"cuda\")],\n ]\n\n def check_start_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[-1, -2], end_indices=[5, 5], strides=[7, 7]\n )\n fd.add_output(T1)\n\n def check_end_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[3, 4], end_indices=[1, 2], strides=[1, 1])\n fd.add_output(T1)\n\n def check_strides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[0, 0], end_indices=[5, 5], strides=[5, 5])\n fd.add_output(T1)\n\n def check_tensor_dims(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_start(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_end(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4, 4], strides=[1, 1]\n )","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.check_tensor_dims","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.check_tensor_dims#L209-L214","kind":"function","name":"check_tensor_dims","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":209,"end_line":214,"context_start_line":189,"context_end_line":234,"code":" [torch.randn(5, 5, device=\"cuda\")],\n ]\n\n def check_start_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[-1, -2], end_indices=[5, 5], strides=[7, 7]\n )\n fd.add_output(T1)\n\n def check_end_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[3, 4], end_indices=[1, 2], strides=[1, 1])\n fd.add_output(T1)\n\n def check_strides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[0, 0], end_indices=[5, 5], strides=[5, 5])\n fd.add_output(T1)\n\n def check_tensor_dims(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_start(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_end(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_stride(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4], strides=[1, 1, 1]\n )","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.check_slice_dims_start","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.check_slice_dims_start#L216-L221","kind":"function","name":"check_slice_dims_start","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":216,"end_line":221,"context_start_line":196,"context_end_line":241,"code":" )\n fd.add_output(T1)\n\n def check_end_indices(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[3, 4], end_indices=[1, 2], strides=[1, 1])\n fd.add_output(T1)\n\n def check_strides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[0, 0], end_indices=[5, 5], strides=[5, 5])\n fd.add_output(T1)\n\n def check_tensor_dims(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_start(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_end(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_stride(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_nostrides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[2, 2], end_indices=[4, 4])\n fd.add_output(T1)\n","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.check_slice_dims_end","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.check_slice_dims_end#L223-L228","kind":"function","name":"check_slice_dims_end","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":223,"end_line":228,"context_start_line":203,"context_end_line":248,"code":"\n def check_strides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[0, 0], end_indices=[5, 5], strides=[5, 5])\n fd.add_output(T1)\n\n def check_tensor_dims(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_start(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_end(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_stride(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_nostrides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[2, 2], end_indices=[4, 4])\n fd.add_output(T1)\n\n def legal(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[6, 6], end_indices=[8, 8], strides=[1, 1])\n fd.add_output(T1)\n\n checks = [\n (","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.check_slice_dims_stride","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.check_slice_dims_stride#L230-L235","kind":"function","name":"check_slice_dims_stride","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":230,"end_line":235,"context_start_line":210,"context_end_line":255,"code":" T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_start(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_end(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_stride(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_nostrides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[2, 2], end_indices=[4, 4])\n fd.add_output(T1)\n\n def legal(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[6, 6], end_indices=[8, 8], strides=[1, 1])\n fd.add_output(T1)\n\n checks = [\n (\n check_start_indices,\n \"Slice operation start_indices must be greater than or equal to 0..*\",\n ),\n (\n check_end_indices,\n \"Slice operation end_indices must be greater than or equal to start_indices..*\",\n ),","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.check_nostrides","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.check_nostrides#L237-L240","kind":"function","name":"check_nostrides","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":237,"end_line":240,"context_start_line":217,"context_end_line":260,"code":" T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0, 0], end_indices=[4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_end(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_stride(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_nostrides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[2, 2], end_indices=[4, 4])\n fd.add_output(T1)\n\n def legal(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[6, 6], end_indices=[8, 8], strides=[1, 1])\n fd.add_output(T1)\n\n checks = [\n (\n check_start_indices,\n \"Slice operation start_indices must be greater than or equal to 0..*\",\n ),\n (\n check_end_indices,\n \"Slice operation end_indices must be greater than or equal to start_indices..*\",\n ),\n (\n check_strides,\n \"nvFuser Limitation: All slice operation strides must be of const size 1.*\",\n ),\n (","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.legal","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.legal#L242-L245","kind":"function","name":"legal","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":242,"end_line":245,"context_start_line":222,"context_end_line":265,"code":"\n def check_slice_dims_end(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4, 4], strides=[1, 1]\n )\n fd.add_output(T1)\n\n def check_slice_dims_stride(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[4, 4], strides=[1, 1, 1]\n )\n fd.add_output(T1)\n\n def check_nostrides(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[2, 2], end_indices=[4, 4])\n fd.add_output(T1)\n\n def legal(fd: FusionDefinition, acts) -> None:\n T0 = fd.from_pytorch(acts[0])\n T1 = fd.ops.slice(T0, start_indices=[6, 6], end_indices=[8, 8], strides=[1, 1])\n fd.add_output(T1)\n\n checks = [\n (\n check_start_indices,\n \"Slice operation start_indices must be greater than or equal to 0..*\",\n ),\n (\n check_end_indices,\n \"Slice operation end_indices must be greater than or equal to start_indices..*\",\n ),\n (\n check_strides,\n \"nvFuser Limitation: All slice operation strides must be of const size 1.*\",\n ),\n (\n check_tensor_dims,\n \"Number of tensor dimensions does not match slice dimensions!.*\",\n ),\n (\n check_slice_dims_start,","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.run_test","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.run_test#L368-L428","kind":"function","name":"run_test","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":368,"end_line":428,"context_start_line":348,"context_end_line":448,"code":" # Each call to uniform with DataType::Float will advance the offset by one\n # See Note [Divide offset by 4] in rng.cpp for more information\n stateless_sequence = [\n fd_det.execute([inputs[0], seed, rng_offset])\n for rng_offset in range(10)\n ]\n\n for i, (sful, sless) in enumerate(\n zip(stateful_sequence, stateless_sequence)\n ):\n nvfuser_direct_test.assertEqual(sful[0], sless[0])\n # Restore the RNG state\n torch.cuda.set_rng_state(state)\n\n\n# Test that the range of generated uniform values spans the proper range\n# https://github.com/NVIDIA/Fuser/issues/1653\ndef test_uniform_range(nvfuser_direct_test):\n dtypes = [DataType.Double, DataType.Float, DataType.Half, DataType.BFloat16]\n\n def run_test(left: float, right: float, dtype: DataType):\n samples_per_run = 2**29\n\n def fusion_fn(fd: FusionDefinition):\n # Generate enough values to reasonably expect to sample the ends of the range\n S0 = fd.define_scalar(left, dtype=DataType.Double)\n S1 = fd.define_scalar(right, dtype=DataType.Double)\n output = fd.ops.uniform(S0, S1, shape=[samples_per_run], dtype=dtype)\n fd.add_output(output)\n\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n output = fd.execute([])[0]\n\n x = output.amax()\n m = output.amin()\n mu = output.type(torch.float64).mean()\n # Repeat to improve chances of sampling extreme values\n num_runs = 100\n num_samples = num_runs * samples_per_run\n for i in range(num_runs):\n u = fd.execute([])[0]\n x = torch.maximum(x, u.amax())\n m = torch.minimum(m, u.amin())\n mu = mu + (u.type(torch.float64).mean() - mu) / (i + 2)\n\n # round-trip cast to find expected min\n theomin = torch.tensor(left, dtype=output.dtype).item()\n theomu = 0.5 * (right + left)\n theomax = torch.nextafter(\n torch.tensor(right, dtype=output.dtype),\n torch.tensor(left, dtype=output.dtype),\n )\n\n assert (\n m.item() >= theomin\n ), f\"{output.dtype} expected min generated value {theomin} but found {m.item()}\"\n assert (\n m.item() <= theomax\n ), f\"{output.dtype} expected max generated value {theomax} but found {x.item()}\"\n\n # uniform distribution on [0, 1) has mean 0.5 and variance 1/12\n # The standard error of the mean is then 1/sqrt(12 *\n # num_samples). We use the precision at 1.0 as a surrogate for\n # the contribution of rounding to the standard error of the\n # finite-precision mean.\n assert abs(mu.item() - theomu) < (right - left) * max(\n right - x.item(), 3.0 / math.sqrt(12 * num_samples)\n ), f\"{output.dtype} expected mean generated value {theomu} but found {mu.item()}\"\n\n if dtype not in [DataType.Float, DataType.Double]:\n # For reduced precision types, check that we sample the extreme\n # values. We don't do this for full precision types since the\n # amount of samples required would be too large.\n assert (\n m.item() == theomin\n ), f\"{output.dtype} expected min generated value {theomin} but found {m.item()}\"\n assert (\n x.item() == theomax\n ), f\"{output.dtype} expected max generated value {theomax} but found {x.item()}\"\n\n # test standard and non-standard uniform\n for left, right in [[0.0, 1.0], [-1.5, 3.7]]:\n for dtype in dtypes:\n run_test(left, right, dtype)\n\n\ndef test_cat_qwen2_v2(nvfuser_direct_test):\n def qwen2_cat_fusion_2(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2048, 512],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n S1 = fd.define_scalar(None, dtype=DataType.Int)\n S2 = fd.define_scalar(None, dtype=DataType.Int)\n T3 = fd.define_tensor(\n shape=[1, 4, 2048, 128],","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.qwen2_cat_fusion_2","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.qwen2_cat_fusion_2#L437-L601","kind":"function","name":"qwen2_cat_fusion_2","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":437,"end_line":601,"context_start_line":417,"context_end_line":621,"code":" ), f\"{output.dtype} expected mean generated value {theomu} but found {mu.item()}\"\n\n if dtype not in [DataType.Float, DataType.Double]:\n # For reduced precision types, check that we sample the extreme\n # values. We don't do this for full precision types since the\n # amount of samples required would be too large.\n assert (\n m.item() == theomin\n ), f\"{output.dtype} expected min generated value {theomin} but found {m.item()}\"\n assert (\n x.item() == theomax\n ), f\"{output.dtype} expected max generated value {theomax} but found {x.item()}\"\n\n # test standard and non-standard uniform\n for left, right in [[0.0, 1.0], [-1.5, 3.7]]:\n for dtype in dtypes:\n run_test(left, right, dtype)\n\n\ndef test_cat_qwen2_v2(nvfuser_direct_test):\n def qwen2_cat_fusion_2(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2048, 512],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n S1 = fd.define_scalar(None, dtype=DataType.Int)\n S2 = fd.define_scalar(None, dtype=DataType.Int)\n T3 = fd.define_tensor(\n shape=[1, 4, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T4 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T5 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T6 = fd.define_tensor(\n shape=[1, 28, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T7 = fd.define_tensor(\n shape=[1, 2048, 512],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T12 = fd.ops.reshape(T0, new_shape=[1, 2048, 512])\n T13 = fd.ops.cast(T12, dtype=DataType.Float)\n S14 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S15 = fd.define_scalar(1.00000, dtype=DataType.Double)\n S16 = fd.define_scalar(1, dtype=DataType.Int)\n S17 = fd.define_scalar(2048, dtype=DataType.Int)\n S18 = fd.define_scalar(512, dtype=DataType.Int)\n T20 = fd.ops.uniform(\n S14,\n S15,\n shape=[S16, S17, S18],\n rng_seed=S2,\n rng_offset=S1,\n dtype=DataType.BFloat16,\n )\n S21 = fd.define_scalar(4.00000, dtype=DataType.Double)\n T22 = fd.ops.mul(T13, S21)\n S23 = fd.define_scalar(0.900000, dtype=DataType.Double)\n T24 = fd.ops.lt(T20, S23)\n T25 = fd.ops.cast(T24, dtype=DataType.Float)\n T41 = fd.ops.slice(\n T3,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 4, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T42 = fd.ops.mul(T22, T25)\n T43 = fd.ops.cast(T41, dtype=DataType.Float)\n T44 = fd.ops.neg(T43)\n T50 = fd.ops.broadcast_in_dim(\n T4, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3]\n )\n T66 = fd.ops.slice(\n T3,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 4, 2048, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T67 = fd.ops.cast(T44, dtype=DataType.BFloat16)\n T73 = fd.ops.broadcast_in_dim(\n T5, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3]\n )\n T89 = fd.ops.slice(\n T6,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 28, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n S90 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T91 = fd.ops.mul(T42, S90)\n T97 = fd.ops.broadcast_in_dim(\n T50, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T98 = fd.ops.cat([T67, T66], dim=-1, manual_padding=0)\n T104 = fd.ops.broadcast_in_dim(\n T73, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T105 = fd.ops.cast(T89, dtype=DataType.Float)\n T106 = fd.ops.cast(T97, dtype=DataType.Float)\n T107 = fd.ops.cast(T98, dtype=DataType.Float)\n T108 = fd.ops.cast(T104, dtype=DataType.Float)\n T109 = fd.ops.cast(T3, dtype=DataType.Float)\n T110 = fd.ops.neg(T105)\n T111 = fd.ops.cast(T7, dtype=DataType.Float)\n T112 = fd.ops.mul(T107, T106)\n T113 = fd.ops.mul(T109, T108)\n T129 = fd.ops.slice(\n T6,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 28, 2048, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T130 = fd.ops.cast(T110, dtype=DataType.BFloat16)\n T131 = fd.ops.add(T111, T91)\n T137 = fd.ops.broadcast_in_dim(\n T50, shape=[1, 28, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T138 = fd.ops.cat([T130, T129], dim=-1, manual_padding=0)\n T144 = fd.ops.broadcast_in_dim(\n T73, shape=[1, 28, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T145 = fd.ops.cast(T131, dtype=DataType.BFloat16)\n T146 = fd.ops.cast(T137, dtype=DataType.Float)\n T147 = fd.ops.cast(T138, dtype=DataType.Float)\n T148 = fd.ops.cast(T144, dtype=DataType.Float)\n T149 = fd.ops.cast(T6, dtype=DataType.Float)\n T155 = fd.ops.reshape(T145, new_shape=[1, 2048, 4, 128])\n T156 = fd.ops.add(T113, T112)\n T157 = fd.ops.mul(T147, T146)\n T158 = fd.ops.mul(T149, T148)\n T159 = fd.ops.permute(T155, dims=[0, 2, 1, 3])\n T160 = fd.ops.cast(T156, dtype=DataType.BFloat16)\n T167 = fd.ops.broadcast_in_dim(\n T159, shape=[1, 4, 1, 2048, 128], broadcast_dims=[0, 1, 3, 4]\n )\n T174 = fd.ops.broadcast_in_dim(\n T160, shape=[1, 4, 1, 2048, 128], broadcast_dims=[0, 1, 3, 4]\n )\n T181 = fd.ops.broadcast_in_dim(\n T167, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T188 = fd.ops.broadcast_in_dim(\n T174, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T189 = fd.ops.add(T158, T157)\n T195 = fd.ops.reshape(T181, new_shape=[1, 28, 2048, 128])\n T201 = fd.ops.reshape(T188, new_shape=[1, 28, 2048, 128])\n T202 = fd.ops.cast(T189, dtype=DataType.BFloat16)\n T203 = fd.ops.stride_order(T195, stride_order=[3, 2, 1, 0])\n T204 = fd.ops.stride_order(T201, stride_order=[3, 2, 1, 0])\n T205 = fd.ops.stride_order(T202, stride_order=[3, 2, 1, 0])\n fd.add_output(T159)\n fd.add_output(T160)\n fd.add_output(T203)\n fd.add_output(T204)\n fd.add_output(T205)\n\n inputs = [\n torch.testing.make_tensor((2048, 512), dtype=torch.bfloat16, device=\"cuda:0\"),\n 25546,\n 1400552702872758,\n torch.randn(1048576, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 4, 2048, 128), (1048576, 128, 512, 1)\n ),\n torch.randn(262144, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 128), (262144, 1, 2048)\n ),\n torch.randn(262144, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 2048, 128), (262144, 1, 2048)\n ),\n torch.randn(7340032, dtype=torch.bfloat16, device=\"cuda:0\").as_strided(\n (1, 28, 2048, 128), (7340032, 128, 3584, 1)\n ),\n torch.testing.make_tensor(\n (1, 2048, 512), dtype=torch.bfloat16, device=\"cuda:0\"\n ),","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.nvfuser_fusion","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.nvfuser_fusion#L944-L971","kind":"function","name":"nvfuser_fusion","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":944,"end_line":971,"context_start_line":924,"context_end_line":991,"code":"def test_prim_rms_norm_fwd(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, requires_grad=True),\n torch.nn.Parameter(torch.randn(input_size[2], dtype=dtype, device=device)),\n ]\n\n def primitive_definition(\n inputs: torch.Tensor,\n weight: torch.Tensor,\n normalization_axis: int,\n keepdim: bool,\n ) -> torch.Tensor:\n var = inputs.mul(inputs).mean(normalization_axis, keepdim)\n pre_shift_scale_norm_output = inputs / torch.sqrt(var + 1e-12)\n norm_output = weight * pre_shift_scale_norm_output\n return norm_output\n\n def nvfuser_fusion(\n fd: FusionDefinition,\n normalization_axis: int,\n norm_size: int,\n input_shape: List[int],\n eps: float,\n keepDim: bool,\n ) -> None:\n inputs = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n )\n weights = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float)\n inputs_sq = fd.ops.mul(inputs, inputs)\n sum0 = fd.ops.sum(inputs_sq, dims=[normalization_axis], keepdim=keepDim)\n norm_const = fd.define_scalar(norm_size)\n var = fd.ops.div(sum0, norm_const)\n eps_const = fd.define_scalar(eps)\n var_eps = fd.ops.add(var, eps_const)\n invstd = fd.ops.rsqrt(var_eps)\n pre_scale = fd.ops.mul(inputs, invstd)\n weights_bcast = fd.ops.broadcast_in_dim(\n weights, shape=input_shape, broadcast_dims=[2]\n )\n out = fd.ops.mul(pre_scale, weights_bcast)\n fd.add_output(out)\n fd.add_output(invstd)\n\n fusion_func = partial(\n nvfuser_fusion,\n normalization_axis=2,\n norm_size=inputs[0].size()[2],\n input_shape=inputs[0].size(),\n eps=1e-12,\n keepDim=True,\n )\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = primitive_definition(inputs[0], inputs[1], 2, True)\n\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_litgpt_variants_gpt_neox_like(nvfuser_direct_test):\n \"\"\"\n This test hits a segfault in nvfuser::preseg_passes::MovePadPass::replaceCat.\n The old optimization pass updates the fusion within the filterByType generator","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.torch_def","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.torch_def#L699-L704","kind":"function","name":"torch_def","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":699,"end_line":704,"context_start_line":679,"context_end_line":724,"code":" )\n T23 = fd.ops.broadcast_in_dim(\n T22, shape=[16, 16, 128, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T24 = fd.ops.div(T17, T23)\n S25 = fd.define_scalar(16, dtype=DataType.Int)\n S26 = fd.define_scalar(16, dtype=DataType.Int)\n S27 = fd.define_scalar(128, dtype=DataType.Int)\n S28 = fd.define_scalar(128, dtype=DataType.Int)\n S29 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S30 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T31 = fd.ops.uniform(S29, S30, shape=[S25, S26, S27, S28], dtype=DataType.Float)\n S32 = fd.define_scalar(1.0 - prob, dtype=DataType.Double)\n T33 = fd.ops.lt(T31, S32)\n T34 = fd.ops.cast(T33, dtype=DataType.Float)\n T35 = fd.ops.mul(T24, T34)\n S36 = fd.define_scalar(1.0 / (1.0 - prob), dtype=DataType.Double)\n T37 = fd.ops.mul(T35, S36)\n fd.add_output(T37)\n\n def torch_def(acts, bias, n_seq_len, n_head_dim, prob):\n att = acts * (1.0 / math.sqrt(n_head_dim))\n att = att.masked_fill(bias[:, :, :n_seq_len, :n_seq_len] == 0, float(\"-inf\"))\n att = torch.nn.functional.softmax(att, dim=-1)\n att = torch.nn.functional.dropout(att, p=prob)\n return att\n\n # NOTE: The dropout probabilities need to be set to 0 elements zeroed out\n # in order to match implementations as eager and nvFuser do not have matching\n # blocking.\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(nvfuser_fusion, prob=0.0), inputs\n )\n eager_out = torch_def(inputs[0], inputs[1], 128, 64, 0.0)\n\n for idx in range(len(nvf_out)):\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[idx])\n\n\ndef test_nanogpt_split_mha_linears(nvfuser_direct_test):\n inputs = [\n torch.randn(16, 128, 3072, device=\"cuda\"),\n ]\n\n def nvfuser_fusion_0(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.nvfuser_fusion_0","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.nvfuser_fusion_0#L723-L736","kind":"function","name":"nvfuser_fusion_0","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":723,"end_line":736,"context_start_line":703,"context_end_line":756,"code":" att = torch.nn.functional.dropout(att, p=prob)\n return att\n\n # NOTE: The dropout probabilities need to be set to 0 elements zeroed out\n # in order to match implementations as eager and nvFuser do not have matching\n # blocking.\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(\n partial(nvfuser_fusion, prob=0.0), inputs\n )\n eager_out = torch_def(inputs[0], inputs[1], 128, 64, 0.0)\n\n for idx in range(len(nvf_out)):\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[idx])\n\n\ndef test_nanogpt_split_mha_linears(nvfuser_direct_test):\n inputs = [\n torch.randn(16, 128, 3072, device=\"cuda\"),\n ]\n\n def nvfuser_fusion_0(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T0_slice1 = fd.ops.slice(T0, [0, 0, 0], [16, 128, 1024], [1, 1, 1])\n T0_slice2 = fd.ops.slice(T0, [0, 0, 1024], [16, 128, 2048], [1, 1, 1])\n T0_slice3 = fd.ops.slice(T0, [0, 0, 2048], [16, 128, 3072], [1, 1, 1])\n T1_slice1 = fd.ops.reshape(T0_slice1, [16, 128, 16, 64])\n T1_slice2 = fd.ops.reshape(T0_slice2, [16, 128, 16, 64])\n T1_slice3 = fd.ops.reshape(T0_slice3, [16, 128, 16, 64])\n T2_slice1 = fd.ops.permute(T1_slice1, [0, 2, 1, 3])\n T2_slice2 = fd.ops.permute(T1_slice2, [0, 2, 1, 3])\n T2_slice3 = fd.ops.permute(T1_slice3, [0, 2, 1, 3])\n fd.add_output(T2_slice1)\n fd.add_output(T2_slice2)\n fd.add_output(T2_slice3)\n\n def torch_def_0(acts, n_embd, n_head):\n B, T, C = acts.size()\n q, k, v = acts.split(n_embd, dim=2)\n k = k.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n q = q.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n v = v.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n return (\n q,\n k,\n v,\n )\n\n def nvfuser_fusion_1(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.torch_def_0","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.torch_def_0#L738-L748","kind":"function","name":"torch_def_0","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":738,"end_line":748,"context_start_line":718,"context_end_line":768,"code":"def test_nanogpt_split_mha_linears(nvfuser_direct_test):\n inputs = [\n torch.randn(16, 128, 3072, device=\"cuda\"),\n ]\n\n def nvfuser_fusion_0(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T0_slice1 = fd.ops.slice(T0, [0, 0, 0], [16, 128, 1024], [1, 1, 1])\n T0_slice2 = fd.ops.slice(T0, [0, 0, 1024], [16, 128, 2048], [1, 1, 1])\n T0_slice3 = fd.ops.slice(T0, [0, 0, 2048], [16, 128, 3072], [1, 1, 1])\n T1_slice1 = fd.ops.reshape(T0_slice1, [16, 128, 16, 64])\n T1_slice2 = fd.ops.reshape(T0_slice2, [16, 128, 16, 64])\n T1_slice3 = fd.ops.reshape(T0_slice3, [16, 128, 16, 64])\n T2_slice1 = fd.ops.permute(T1_slice1, [0, 2, 1, 3])\n T2_slice2 = fd.ops.permute(T1_slice2, [0, 2, 1, 3])\n T2_slice3 = fd.ops.permute(T1_slice3, [0, 2, 1, 3])\n fd.add_output(T2_slice1)\n fd.add_output(T2_slice2)\n fd.add_output(T2_slice3)\n\n def torch_def_0(acts, n_embd, n_head):\n B, T, C = acts.size()\n q, k, v = acts.split(n_embd, dim=2)\n k = k.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n q = q.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n v = v.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n return (\n q,\n k,\n v,\n )\n\n def nvfuser_fusion_1(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 0],\n end_indices=[16, 128, 1024],\n strides=[1, 1, 1],\n )\n T2 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 1024],\n end_indices=[16, 128, 2048],\n strides=[1, 1, 1],\n )","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.nvfuser_fusion_1","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.nvfuser_fusion_1#L750-L777","kind":"function","name":"nvfuser_fusion_1","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":750,"end_line":777,"context_start_line":730,"context_end_line":797,"code":" T1_slice3 = fd.ops.reshape(T0_slice3, [16, 128, 16, 64])\n T2_slice1 = fd.ops.permute(T1_slice1, [0, 2, 1, 3])\n T2_slice2 = fd.ops.permute(T1_slice2, [0, 2, 1, 3])\n T2_slice3 = fd.ops.permute(T1_slice3, [0, 2, 1, 3])\n fd.add_output(T2_slice1)\n fd.add_output(T2_slice2)\n fd.add_output(T2_slice3)\n\n def torch_def_0(acts, n_embd, n_head):\n B, T, C = acts.size()\n q, k, v = acts.split(n_embd, dim=2)\n k = k.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n q = q.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n v = v.view(B, T, n_head, (C // 3) // n_head).transpose(1, 2) # (B, nh, T, hs)\n return (\n q,\n k,\n v,\n )\n\n def nvfuser_fusion_1(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n T1 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 0],\n end_indices=[16, 128, 1024],\n strides=[1, 1, 1],\n )\n T2 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 1024],\n end_indices=[16, 128, 2048],\n strides=[1, 1, 1],\n )\n T3 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 2048],\n end_indices=[16, 128, 3072],\n strides=[1, 1, 1],\n )\n fd.add_output(T1)\n fd.add_output(T2)\n fd.add_output(T3)\n\n def torch_def_1(acts, n_embd, n_head):\n B, T, C = acts.size()\n q, k, v = acts.split(n_embd, dim=2)\n return (\n q,\n k,\n v,\n )\n\n tests = [\n (nvfuser_fusion_0, torch_def_0),\n (nvfuser_fusion_1, torch_def_1),\n ]\n\n for nvf_func, torch_func in tests:\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(nvf_func, inputs)\n eager_out = torch_func(*inputs, 1024, 16)\n for idx in range(len(eager_out)):\n nvfuser_direct_test.assertEqual(eager_out[idx], nvf_out[idx])","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.torch_def_1","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.torch_def_1#L779-L786","kind":"function","name":"torch_def_1","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":779,"end_line":786,"context_start_line":759,"context_end_line":806,"code":" start_indices=[0, 0, 0],\n end_indices=[16, 128, 1024],\n strides=[1, 1, 1],\n )\n T2 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 1024],\n end_indices=[16, 128, 2048],\n strides=[1, 1, 1],\n )\n T3 = fd.ops.slice(\n T0,\n start_indices=[0, 0, 2048],\n end_indices=[16, 128, 3072],\n strides=[1, 1, 1],\n )\n fd.add_output(T1)\n fd.add_output(T2)\n fd.add_output(T3)\n\n def torch_def_1(acts, n_embd, n_head):\n B, T, C = acts.size()\n q, k, v = acts.split(n_embd, dim=2)\n return (\n q,\n k,\n v,\n )\n\n tests = [\n (nvfuser_fusion_0, torch_def_0),\n (nvfuser_fusion_1, torch_def_1),\n ]\n\n for nvf_func, torch_func in tests:\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(nvf_func, inputs)\n eager_out = torch_func(*inputs, 1024, 16)\n for idx in range(len(eager_out)):\n nvfuser_direct_test.assertEqual(eager_out[idx], nvf_out[idx])\n\n\ndef test_prim_layer_norm_fwd(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, requires_grad=True),\n torch.nn.Parameter(torch.randn(input_size[2], dtype=dtype, device=device)),","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.primitive_definition","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.primitive_definition#L933-L942","kind":"function","name":"primitive_definition","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":933,"end_line":942,"context_start_line":913,"context_end_line":962,"code":" eps=1e-12,\n keepDim=True,\n )\n nvf_var_mean_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_2, inputs)\n\n eager_out = primitive_definition(inputs[0], inputs[1], inputs[2], 2, True)\n\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n nvfuser_direct_test.assertEqual(eager_out, nvf_var_mean_out[0])\n\n\ndef test_prim_rms_norm_fwd(nvfuser_direct_test):\n input_size = [64, 128, 1024]\n dtype = torch.float32\n device = \"cuda\"\n inputs = [\n torch.randn(*input_size, device=device, requires_grad=True),\n torch.nn.Parameter(torch.randn(input_size[2], dtype=dtype, device=device)),\n ]\n\n def primitive_definition(\n inputs: torch.Tensor,\n weight: torch.Tensor,\n normalization_axis: int,\n keepdim: bool,\n ) -> torch.Tensor:\n var = inputs.mul(inputs).mean(normalization_axis, keepdim)\n pre_shift_scale_norm_output = inputs / torch.sqrt(var + 1e-12)\n norm_output = weight * pre_shift_scale_norm_output\n return norm_output\n\n def nvfuser_fusion(\n fd: FusionDefinition,\n normalization_axis: int,\n norm_size: int,\n input_shape: List[int],\n eps: float,\n keepDim: bool,\n ) -> None:\n inputs = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n )\n weights = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float)\n inputs_sq = fd.ops.mul(inputs, inputs)\n sum0 = fd.ops.sum(inputs_sq, dims=[normalization_axis], keepdim=keepDim)\n norm_const = fd.define_scalar(norm_size)\n var = fd.ops.div(sum0, norm_const)\n eps_const = fd.define_scalar(eps)","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.nvfuser_fusion_var_mean","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.nvfuser_fusion_var_mean#L863-L896","kind":"function","name":"nvfuser_fusion_var_mean","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":863,"end_line":896,"context_start_line":843,"context_end_line":916,"code":" diff = fd.ops.sub(inputs, mean)\n diff_sq = fd.ops.mul(diff, diff)\n sum1 = fd.ops.sum(diff_sq, dims=[normalization_axis], keepdim=keepDim)\n var = fd.ops.div(sum1, norm_const)\n eps_const = fd.define_scalar(eps)\n var_eps = fd.ops.add(var, eps_const)\n invstd = fd.ops.rsqrt(var_eps)\n pre_scale_bias = fd.ops.mul(diff, invstd)\n weights_bcast = fd.ops.broadcast_in_dim(\n weights, shape=input_shape, broadcast_dims=[2]\n )\n scale = fd.ops.mul(pre_scale_bias, weights_bcast)\n bias_bcast = fd.ops.broadcast_in_dim(\n bias, shape=input_shape, broadcast_dims=[2]\n )\n out = fd.ops.add(scale, bias_bcast)\n fd.add_output(out)\n fd.add_output(mean)\n fd.add_output(invstd)\n\n def nvfuser_fusion_var_mean(\n fd: FusionDefinition,\n normalization_axis: int,\n norm_size: int,\n input_shape: List[int],\n eps: float,\n keepDim: bool,\n ) -> None:\n inputs = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n )\n weights = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float)\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=DataType.Float)\n var, mean = fd.ops.var_mean(\n inputs, dims=[normalization_axis], correction=0, keepdim=keepDim\n )\n eps_const = fd.define_scalar(eps)\n var_eps = fd.ops.add(var, eps_const)\n invstd = fd.ops.rsqrt(var_eps)\n diff = fd.ops.sub(inputs, mean)\n pre_scale_bias = fd.ops.mul(diff, invstd)\n weights_bcast = fd.ops.broadcast_in_dim(\n weights, shape=input_shape, broadcast_dims=[2]\n )\n scale = fd.ops.mul(pre_scale_bias, weights_bcast)\n bias_bcast = fd.ops.broadcast_in_dim(\n bias, shape=input_shape, broadcast_dims=[2]\n )\n out = fd.ops.add(scale, bias_bcast)\n fd.add_output(out)\n fd.add_output(mean)\n fd.add_output(invstd)\n\n fusion_func_1 = partial(\n nvfuser_fusion,\n normalization_axis=2,\n norm_size=inputs[0].size()[2],\n input_shape=inputs[0].size(),\n eps=1e-12,\n keepDim=True,\n )\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_1, inputs)\n\n fusion_func_2 = partial(\n nvfuser_fusion_var_mean,\n normalization_axis=2,\n norm_size=inputs[0].size()[2],\n input_shape=inputs[0].size(),\n eps=1e-12,\n keepDim=True,\n )\n nvf_var_mean_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func_2, inputs)","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.nvfuser_fusion_id4","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.nvfuser_fusion_id4#L995-L1117","kind":"function","name":"nvfuser_fusion_id4","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":995,"end_line":1117,"context_start_line":975,"context_end_line":1130,"code":" normalization_axis=2,\n norm_size=inputs[0].size()[2],\n input_shape=inputs[0].size(),\n eps=1e-12,\n keepDim=True,\n )\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(fusion_func, inputs)\n\n eager_out = primitive_definition(inputs[0], inputs[1], 2, True)\n\n nvfuser_direct_test.assertEqual(eager_out, nvf_out[0])\n\n\ndef test_litgpt_variants_gpt_neox_like(nvfuser_direct_test):\n \"\"\"\n This test hits a segfault in nvfuser::preseg_passes::MovePadPass::replaceCat.\n The old optimization pass updates the fusion within the filterByType generator\n This causes a dynamic cast on a dangling pointer.\n \"\"\"\n\n def nvfuser_fusion_id4(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[128, 16],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[128, 16],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[5, 5, 192],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T12 = fd.ops.slice(\n T0, start_indices=[0, 0], end_indices=[5, 16], strides=[1, 1]\n )\n T22 = fd.ops.slice(\n T1, start_indices=[0, 0], end_indices=[5, 16], strides=[1, 1]\n )\n T29 = fd.ops.reshape(T2, new_shape=[5, 5, 4, 3, 16])\n T30 = fd.ops.permute(T29, dims=[0, 2, 3, 1, 4])\n T49 = fd.ops.slice(\n T30,\n start_indices=[0, 0, 0, 0, 0],\n end_indices=[5, 4, 1, 5, 16],\n strides=[1, 1, 1, 1, 1],\n )\n T68 = fd.ops.slice(\n T30,\n start_indices=[0, 0, 1, 0, 0],\n end_indices=[5, 4, 2, 5, 16],\n strides=[1, 1, 1, 1, 1],\n )\n T87 = fd.ops.slice(\n T30,\n start_indices=[0, 0, 2, 0, 0],\n end_indices=[5, 4, 3, 5, 16],\n strides=[1, 1, 1, 1, 1],\n )\n T93 = fd.ops.reshape(T49, new_shape=[5, 4, 5, 16])\n T99 = fd.ops.reshape(T68, new_shape=[5, 4, 5, 16])\n T105 = fd.ops.reshape(T87, new_shape=[5, 4, 5, 16])\n T121 = fd.ops.slice(\n T93,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 8],\n strides=[1, 1, 1, 1],\n )\n T137 = fd.ops.slice(\n T93,\n start_indices=[0, 0, 0, 8],\n end_indices=[5, 4, 5, 16],\n strides=[1, 1, 1, 1],\n )\n T138 = fd.ops.neg(T137)\n T139 = fd.ops.cat([T138, T121], dim=-1)\n S140 = fd.define_scalar(5, dtype=DataType.Int)\n S141 = fd.define_scalar(4, dtype=DataType.Int)\n S142 = fd.define_scalar(5, dtype=DataType.Int)\n S143 = fd.define_scalar(16, dtype=DataType.Int)\n T145 = fd.ops.broadcast_in_dim(\n T12, shape=[S140, S141, S142, S143], broadcast_dims=[2, 3]\n )\n T146 = fd.ops.mul(T93, T145)\n S147 = fd.define_scalar(5, dtype=DataType.Int)\n S148 = fd.define_scalar(4, dtype=DataType.Int)\n S149 = fd.define_scalar(5, dtype=DataType.Int)\n S150 = fd.define_scalar(16, dtype=DataType.Int)\n T152 = fd.ops.broadcast_in_dim(\n T22, shape=[S147, S148, S149, S150], broadcast_dims=[2, 3]\n )\n T153 = fd.ops.mul(T139, T152)\n T154 = fd.ops.add(T146, T153)\n T170 = fd.ops.slice(\n T99,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 8],\n strides=[1, 1, 1, 1],\n )\n T186 = fd.ops.slice(\n T99,\n start_indices=[0, 0, 0, 8],\n end_indices=[5, 4, 5, 16],\n strides=[1, 1, 1, 1],\n )\n T187 = fd.ops.neg(T186)\n T188 = fd.ops.cat([T187, T170], dim=-1)\n T189 = fd.ops.mul(T99, T145)\n T190 = fd.ops.mul(T188, T152)\n T191 = fd.ops.add(T189, T190)\n T207 = fd.ops.slice(\n T93,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 0],\n strides=[1, 1, 1, 1],\n )\n T208 = fd.ops.cat([T154, T207], dim=-1)\n T224 = fd.ops.slice(\n T99,\n start_indices=[0, 0, 0, 0],\n end_indices=[5, 4, 5, 0],\n strides=[1, 1, 1, 1],\n )\n T225 = fd.ops.cat([T191, T224], dim=-1)\n S226 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T227 = fd.ops.mul(T208, S226)\n T228 = fd.ops.permute(T225, dims=[0, 1, 3, 2])\n S229 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T230 = fd.ops.mul(T228, S229)\n fd.add_output(T105)\n fd.add_output(T145)\n fd.add_output(T152)\n fd.add_output(T227)\n fd.add_output(T230)\n\n with FusionDefinition() as fd:\n nvfuser_fusion_id4(fd)\n\n inputs = [\n torch.testing.make_tensor((128, 16), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((128, 16), dtype=torch.float32, device=\"cuda:0\"),\n torch.testing.make_tensor((5, 5, 192), dtype=torch.float32, device=\"cuda:0\"),\n ]\n fd.validate(inputs)\n\n # check python reproduction\n nvf_out, _ = nvfuser_direct_test.exec_nvfuser(nvfuser_fusion_id4, inputs)","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_high_complexity.fusion_fn","uri":"program://Fuser/function/tests.python.direct.test_high_complexity.fusion_fn#L371-L376","kind":"function","name":"fusion_fn","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":371,"end_line":376,"context_start_line":351,"context_end_line":396,"code":" fd_det.execute([inputs[0], seed, rng_offset])\n for rng_offset in range(10)\n ]\n\n for i, (sful, sless) in enumerate(\n zip(stateful_sequence, stateless_sequence)\n ):\n nvfuser_direct_test.assertEqual(sful[0], sless[0])\n # Restore the RNG state\n torch.cuda.set_rng_state(state)\n\n\n# Test that the range of generated uniform values spans the proper range\n# https://github.com/NVIDIA/Fuser/issues/1653\ndef test_uniform_range(nvfuser_direct_test):\n dtypes = [DataType.Double, DataType.Float, DataType.Half, DataType.BFloat16]\n\n def run_test(left: float, right: float, dtype: DataType):\n samples_per_run = 2**29\n\n def fusion_fn(fd: FusionDefinition):\n # Generate enough values to reasonably expect to sample the ends of the range\n S0 = fd.define_scalar(left, dtype=DataType.Double)\n S1 = fd.define_scalar(right, dtype=DataType.Double)\n output = fd.ops.uniform(S0, S1, shape=[samples_per_run], dtype=dtype)\n fd.add_output(output)\n\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n output = fd.execute([])[0]\n\n x = output.amax()\n m = output.amin()\n mu = output.type(torch.float64).mean()\n # Repeat to improve chances of sampling extreme values\n num_runs = 100\n num_samples = num_runs * samples_per_run\n for i in range(num_runs):\n u = fd.execute([])[0]\n x = torch.maximum(x, u.amax())\n m = torch.minimum(m, u.amin())\n mu = mu + (u.type(torch.float64).mean() - mu) / (i + 2)\n\n # round-trip cast to find expected min\n theomin = torch.tensor(left, dtype=output.dtype).item()","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_allocation","uri":"program://Fuser/module/tests.python.direct.test_allocation#L1-L28","kind":"module","name":"tests.python.direct.test_allocation","path":"tests/python/direct/test_allocation.py","language":"python","start_line":1,"end_line":28,"context_start_line":1,"context_end_line":28,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\n\nfrom nvfuser_direct import FusionDefinition, DataType\n\n\ndef test_contiguous():\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], dtype=DataType.Float, contiguity=True)\n out = fd.ops.sum(inp, [-1])\n fd.add_output(out)\n\n # It might not be obvious but this tensor is indeed contiguous by\n # definition. inp.size(0) == 1 so inp.stride(0) shouldn't matter.\n #\n # I ran into such a tensor when I shard a reference tensor for a particular\n # device using slicing:\n # ```\n # inp = torch.arange(4, device=\"cuda\").view(2, 2)\n # inp = inp[0:1, 0:1].contiguous()\n # ```\n # Despite `.contiguous()`, inp.stride(0) remains to be 2.\n inp = torch.as_strided(torch.ones([1], device=\"cuda\"), [1, 1], [2, 1])\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), torch.ones([1]))","source_hash":"61df72b81f5ba524e14ae7665fb7002f071878f58c1cf6ee523b11594c814e42","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_allocation.test_contiguous","uri":"program://Fuser/function/tests.python.direct.test_allocation.test_contiguous#L10-L28","kind":"function","name":"test_contiguous","path":"tests/python/direct/test_allocation.py","language":"python","start_line":10,"end_line":28,"context_start_line":1,"context_end_line":28,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\n\nfrom nvfuser_direct import FusionDefinition, DataType\n\n\ndef test_contiguous():\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], dtype=DataType.Float, contiguity=True)\n out = fd.ops.sum(inp, [-1])\n fd.add_output(out)\n\n # It might not be obvious but this tensor is indeed contiguous by\n # definition. inp.size(0) == 1 so inp.stride(0) shouldn't matter.\n #\n # I ran into such a tensor when I shard a reference tensor for a particular\n # device using slicing:\n # ```\n # inp = torch.arange(4, device=\"cuda\").view(2, 2)\n # inp = inp[0:1, 0:1].contiguous()\n # ```\n # Despite `.contiguous()`, inp.stride(0) remains to be 2.\n inp = torch.as_strided(torch.ones([1], device=\"cuda\"), [1, 1], [2, 1])\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), torch.ones([1]))","source_hash":"61df72b81f5ba524e14ae7665fb7002f071878f58c1cf6ee523b11594c814e42","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct","uri":"program://Fuser/module/tests.python.direct.test_python_direct#L1-L691","kind":"module","name":"tests.python.direct.test_python_direct","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":1,"end_line":691,"context_start_line":1,"context_end_line":691,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nfrom nvfuser_direct import (\n FusionDefinition,\n PythonProfiler,\n DataType,\n version,\n LruFusionCache,\n LRUCache,\n)\nimport torch\nimport pytest\nimport io\nimport re\nfrom contextlib import redirect_stdout, redirect_stderr\nfrom typing import Callable\n\n\ndef test_python_version_API():\n from nvfuser_direct.nvfuser_direct_version import Version\n\n assert version() > \"0.0.0\"\n assert version() > Version(\"0.0.0\")\n\n\ndef test_fusion_not_defined():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n # A FusionDefinition object is constructed but not defined, should trip an error\n try:\n fd = FusionDefinition()\n out = fd.execute(inputs)\n raise RuntimeError(\"Expecting an error for an empty FusionDefinition!\")\n except NotImplementedError as e:\n assert (\n \"Fusion does not exist! Use `with FusionDefinition() as fd: ...` to define a fusion.\"\n in str(e)\n )\n\n\ndef test_fusion_empty():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n # A FusionDefinition object is constructed but not defined, should trip an error\n with pytest.raises(NotImplementedError, match=\"Fusion is empty!\"):\n with FusionDefinition() as fd:\n pass\n out = fd.execute(inputs)\n\n\ndef test_from_pytorch_fails_on_cpu_tensor():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n error_msg = (\n \"Found unsupported device cpu, only scalar CPU or CUDA tensors are supported\"\n )\n with pytest.raises(ValueError, match=error_msg), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.relu(t0)\n fd.add_output(t1)\n\n\ndef test_fusion_definition_print():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv1 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion math representation\n prescheduled_fusion_definition = \"\"\"Inputs:\n T0_g_float[iS0{2}, iS1{4}, iS2{8}]\n T1_g_float[iS3{2}, iS4{4}, iS5{8}]\nOutputs:\n T2_g_float[iS6{2}, iS7{4}, iS8{8}]\n\n%kernel_math {\nT2_g_float[iS6{2}, iS7{4}, iS8{8}]\n = T0_g_float[iS0{2}, iS1{4}, iS2{8}]\n + T1_g_float[iS3{2}, iS4{4}, iS5{8}];\n} // %kernel_math \\n\\n\"\"\"\n assert fd.fusion.print_math() == prescheduled_fusion_definition\n\n # Test CUDA kernel representation\n cuda_kernel = \"\"\"// Codegen generated code\n__global__ void CUDAGeneratedKernel(Tensor T0, Tensor T1, Tensor T2) {\n NVFUSER_DEFINE_MAGIC_ZERO;\n #pragma unroll\n for(nvfuser_index_t i0 = 0LL; i0 < 2LL; ++i0) {\n nvfuser_index_t i1;\n i1 = T0.alloc_stride[0LL] * i0;\n nvfuser_index_t i2;\n i2 = T1.alloc_stride[0LL] * i0;\n nvfuser_index_t i3;\n i3 = 32LL * i0;\n #pragma unroll\n for(nvfuser_index_t i4 = 0LL; i4 < 4LL; ++i4) {\n nvfuser_index_t i5;\n i5 = i1 + (T0.alloc_stride[1LL] * i4);\n nvfuser_index_t i6;\n i6 = i2 + (T1.alloc_stride[1LL] * i4);\n nvfuser_index_t i7;\n i7 = i3 + (8LL * i4);\n #pragma unroll\n for(nvfuser_index_t i8 = 0LL; i8 < 8LL; ++i8) {\n nvfuser_index_t i9;\n i9 = i8 + nvfuser_zero;\n T2[(i7 + i9)]\n = T0[(i5 + (T0.alloc_stride[2LL] * i9))]\n + T1[(i6 + (T1.alloc_stride[2LL] * i9))];\n }\n }\n }\n NVFUSER_UPDATE_MAGIC_ZERO;\n}\n\"\"\"\n assert fd.fusion.print_kernel() == cuda_kernel\n\n # Test TensorView string representation\n assert str(tv0) == r\"T0_g_float[iS0{2}, iS1{4}, iS2{8}]\"\n assert str(tv1) == r\"T1_g_float[iS3{2}, iS4{4}, iS5{8}]\"\n assert str(tv2) == r\"T2_g_float[iS6{2}, iS7{4}, iS8{8}]\"\n\n # Test TensorDomain string representation\n assert str(tv0.domain()) == r\"[iS0{2}, iS1{4}, iS2{8}]\"\n assert str(tv1.domain()) == r\"[iS3{2}, iS4{4}, iS5{8}]\"\n assert str(tv2.domain()) == r\"[iS6{2}, iS7{4}, iS8{8}]\"\n\n # Test IterDomain string representation\n assert str(tv0.axis(0)) == r\"iS0{2}\"\n assert str(tv1.axis(0)) == r\"iS3{2}\"\n assert str(tv2.axis(0)) == r\"iS6{2}\"\n\n # Test axis extents\n assert str(tv0.axis(0).extent()) == r\"2\"\n assert str(tv1.axis(0).extent()) == r\"2\"\n assert str(tv2.axis(0).extent()) == r\"2\"\n\n\ndef test_fusion_execution_cache():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv1 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n results = fd.execute(inputs)\n torch.testing.assert_close(results[0], inputs[0] + inputs[1])\n\n # Check that TensorViews are accessible after running fusion\n assert str(tv0.domain()) == \"[iS0{2}, iS1{4}, iS2{8}]\"\n assert str(tv1.domain()) == \"[iS3{2}, iS4{4}, iS5{8}]\"\n assert str(tv2.domain()) == \"[iS6{2}, iS7{4}, iS8{8}]\"\n\n with pytest.raises(\n AssertionError,\n match=r\"FusionExecutorCache already exists! Use execute\\(\\) to execute the fusion.\",\n ):\n fd.manual_execute(inputs)\n\n # Test fusion math representation after compilation\n prescheduled_fusion_definition = \"\"\"Inputs:\n T0_g_float[iS0{2}, iS1{4}, iS2{8}]\n T1_g_float[iS3{2}, iS4{4}, iS5{8}]\nOutputs:\n T2_g_float[iS6{2}, iS7{4}, iS8{8}]\n\n%kernel_math {\nT2_g_float[iS6{2}, iS7{4}, iS8{8}]\n = T0_g_float[iS0{2}, iS1{4}, iS2{8}]\n + T1_g_float[iS3{2}, iS4{4}, iS5{8}];\n} // %kernel_math \\n\\n\"\"\"\n assert fd.fusion.print_math() == prescheduled_fusion_definition\n\n # Test compilation status\n assert fd.fec.is_compiled(inputs)\n\n # Test scheduled IR representation\n scheduled_ir = \"\"\"Inputs:\n T0_g_float[iS58{1}, iS59{1}, iS57{128}]\n T1_g_float[iS46{1}, iS47{1}, iS45{128}]\nOutputs:\n T2_g_float[iblockIdx.x28{1}, iUS29{1}, ithreadIdx.x27{128}] ca_pos( 2 ) produce_pos( 3 )\n\n%kernel {\nT3_l_float[iblockIdx.x52{1}, iUS53{1}, ithreadIdx.x51{128}] ca_pos( 2 )\n = Set( T0_g_float[iS58{1}, iS59{1}, iS57{128}], cache_op=Streaming )\nT4_l_float[iblockIdx.x40{1}, iUS41{1}, ithreadIdx.x39{128}] ca_pos( 2 )\n = Set( T1_g_float[iS46{1}, iS47{1}, iS45{128}], cache_op=Streaming )\nT5_l_float[iblockIdx.x34{1}, iUS35{1}, ithreadIdx.x33{128}] ca_pos( 3 ) produce_pos( 2 )\n = T3_l_float[iblockIdx.x52{1}, iUS53{1}, ithreadIdx.x51{128}] ca_pos( 2 )\n + T4_l_float[iblockIdx.x40{1}, iUS41{1}, ithreadIdx.x39{128}] ca_pos( 2 );\nT2_g_float[iblockIdx.x28{1}, iUS29{1}, ithreadIdx.x27{128}] ca_pos( 2 ) produce_pos( 3 )\n = Set( T5_l_float[iblockIdx.x34{1}, iUS35{1}, ithreadIdx.x33{128}] ca_pos( 3 ) produce_pos( 2 ), cache_op=Streaming )\n} // %kernel\\n\"\"\"\n assert fd.fec.get_scheduled_ir(inputs) == scheduled_ir\n assert fd.fec.get_most_recent_scheduled_ir() == scheduled_ir\n\n # Test CUDA kernel representation\n cuda_kernel = \"\"\"// Codegen generated code\n__global__ void nvfuser_pointwise_f0_c1_r0_g0(Tensor T0, Tensor T1, Tensor T2) {\n nvfuser_index_t i0;\n i0 = ((nvfuser_index_t)threadIdx.x) % 32;\n nvfuser_index_t i1;\n i1 = ((nvfuser_index_t)threadIdx.x) / 32;\n nvfuser_index_t i2;\n i2 = i0 / 8;\n nvfuser_index_t i3;\n i3 = i0 % 8;\n if ((((nvfuser_index_t)threadIdx.x) < 64)) {\n Array T4;\n T4[0] = 0;\n T4[0]\n = T1[(((T1.alloc_stride[0LL] * i1) + (T1.alloc_stride[1LL] * i2)) + (T1.alloc_stride[2LL] * i3))];\n Array T3;\n T3[0] = 0;\n T3[0]\n = T0[(((T0.alloc_stride[0LL] * i1) + (T0.alloc_stride[1LL] * i2)) + (T0.alloc_stride[2LL] * i3))];\n Array T5;\n T5[0]\n = T3[0]\n + T4[0];\n T2[((nvfuser_index_t)threadIdx.x)]\n = T5[0];\n }\n}\\n\"\"\"\n assert fd.fec.get_cuda_kernel(inputs) == cuda_kernel\n\n\ndef test_kernel_executor():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv1 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n results = fd.manual_execute(inputs)\n torch.testing.assert_close(results[0], inputs[0] + inputs[1])\n assert fd.ke.is_compiled()\n\n with pytest.raises(\n AssertionError,\n match=r\"KernelExecutor already exists! Use manual_execute\\(\\) to execute the fusion.\",\n ):\n fd.execute(inputs)\n\n\ndef test_repro_script_for():\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\"),\n torch.ones(2, 4, 8, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [1], False, DataType.Float)\n\n fd.add_output(t4)\n\n expected_repro = \"\"\"\nimport torch\nfrom nvfuser_direct import FusionDefinition, DataType\ndef nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv2 = fd.ops.add(tv0, tv1)\n tv3 = fd.ops.mul(tv2, 3.00000)\n tv4 = fd.ops.sum(tv3, dims=[1], dtype=DataType.Float)\n fd.add_output(tv4)\nwith FusionDefinition() as fd:\n nvfuser_fusion(fd)\n\"\"\"\n\n expected_inputs = \"\"\"\ninputs = [\n torch.testing.make_tensor((2, 4, 8), dtype=torch.float32, device='cuda:0'),\n torch.testing.make_tensor((2, 4, 8), dtype=torch.float32, device='cuda:0'),\n]\nfd.execute(inputs)\\n\"\"\"\n\n # fd.repro_script_for(inputs) should have input arguments\n repro_with_inputs = fd.repro_script_for(inputs)\n assert expected_repro in repro_with_inputs\n assert expected_inputs in repro_with_inputs\n\n # fd.repro_script_for() should NOT have input arguments\n repro_without_inputs = fd.repro_script_for()\n assert expected_repro in repro_without_inputs\n assert expected_inputs not in repro_without_inputs\n\n # Check last_repro_script fails gracefully.\n with pytest.raises(\n AssertionError,\n match=r\"fd.last_repro_script\\(\\) cannot provide a repro because fd.execute\\(inputs, save_repro_inputs=True\\) was not executed!\",\n ):\n fd.last_repro_script()\n\n # Test fd.execute(inputs, save_repro_inputs=True) ; fd.last_repro_script()\n fd.execute(inputs, save_repro_inputs=True)\n last_repro = fd.last_repro_script()\n assert repro_with_inputs == last_repro\n\n\ndef test_define_tensor():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n tv1 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution with dynamic shapes\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n outputs = fd.execute(inputs)\n torch.testing.assert_close(outputs[0], inputs[0] + inputs[1])\n\n\n@pytest.mark.skipif(\n torch.cuda.device_count() < 2,\n reason=\"test_selected_device requires multiple GPUs\",\n)\ndef test_execute_with_different_device():\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda:1\"),\n torch.ones(2, 4, 8, device=\"cuda:1\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [1], False, DataType.Float)\n\n fd.add_output(t4)\n\n outputs = fd.execute(inputs, device=\"cuda:1\")\n assert len(outputs) == 1\n assert outputs[0].device.index == 1\n\n\ndef test_enable_disable_options():\n m = 24\n n = 16\n k = 8\n inps = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.float),\n torch.randn(k, n, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition, inps) -> None:\n t0 = fd.from_pytorch(inps[0])\n t1 = fd.from_pytorch(inps[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n with FusionDefinition() as fd:\n fusion_func(fd, inps=inps)\n\n # By default, matmul will be be run through expr_eval scheduler.\n # Through setting the enable and disable options as below,\n # we can execute it through matmul scheduler. The above fusion will not\n # be accepted by the matmul scheduler since the outputs are of type Float and raises a RuntimeError.\n # Note: We use this error-based test since for compatible dtypes (float16/bfloat16),\n # the matmul scheduler ran into a scheduling error on H100. This test might be more robust against\n # changes in matmul scheduler in the interim.\n\n with pytest.raises(\n RuntimeError, match=\"Can not find a scheduler to schedule fusion segment\"\n ):\n fd.execute(\n inps, _enable_options=[\"fuse_matmul\"], _disable_options=[\"matmul_expr_eval\"]\n )\n\n\n# Test that we properly raise an error when passing inputs with the wrong types\ndef test_mismatched_input_types():\n scalar_inp = 2.0\n tensor_inp = torch.rand((15,), dtype=torch.float32, device=\"cuda:0\")\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n s0 = fd.define_scalar()\n T1 = fd.ops.mul(T0, s0)\n fd.add_output(T1)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n with pytest.raises(\n Exception,\n match=\"Expected input 0, .*, to be an at::Tensor but got scalar 2\",\n ):\n nvf_out = fd.execute([scalar_inp, scalar_inp])\n\n with pytest.raises(\n Exception,\n match=re.escape(\n \"Expected input 1, d2, to be a scalar but got float tensor of rank 1\"\n ),\n ):\n nvf_out = fd.execute([tensor_inp, tensor_inp])\n\n with pytest.raises(\n Exception,\n match=\"Expected input 0, .*, to be bound to a tensor of dtype float, but got a tensor of dtype __half\",\n ):\n wrong_tensor_inp = torch.rand((15,), dtype=torch.float16, device=\"cuda:0\")\n nvf_out = fd.execute([wrong_tensor_inp, 2.0])\n\n with pytest.raises(\n Exception,\n match=re.escape(\n \"Scalar value (2,1) is not compatible with the expected data type: double.\"\n ),\n ):\n nvf_out = fd.execute([tensor_inp, 2.0 + 1.0j])\n\n\ndef test_fusion_profiler_auto_scheduled():\n inputs = [\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.add(T0, T1)\n T3 = fd.ops.sum(T2, dim=-1)\n T4 = fd.ops.sum(T3, dim=-1)\n fd.add_output(T4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n # Testing that the profile returns 2 segments\n try:\n with PythonProfiler() as prof:\n fd.execute(inputs)\n assert prof.profile.segments == 2\n assert len(prof.profile.kernel_profiles) == 2\n except Exception as e:\n print(e)\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_fusion_profiler_user_scheduled():\n inputs = [\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.add(T0, T1)\n fd.add_output(T2)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n try:\n with PythonProfiler(auto_scheduled=False) as prof:\n fd.manual_execute(inputs)\n assert prof.profile.fusion_id >= 0\n assert prof.profile.kernel_profiles[0].scheduler == \"user\"\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_fusion_profiler_with_noncodegen_kernels():\n inputs = [\n torch.randn((2, 4, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((2, 4, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((16, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.from_pytorch(inputs[2])\n T3 = fd.ops.linear(T0, T2)\n T4 = fd.ops.add(T3, T1)\n fd.add_output(T4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n try:\n with PythonProfiler() as prof:\n fd.execute(inputs)\n assert len(prof.profile.kernel_profiles) == 2\n assert len(prof.profile.kernel_profiles[0].name) > 0\n assert len(prof.profile.kernel_profiles[1].name) > 0\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_lru_fusion_cache_decorator():\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(2, 4, device=\"cuda\"),\n ]\n\n def create_fd1(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n fd.add_output(t2)\n\n def create_fd2(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t1, t0)\n fd.add_output(t2)\n\n @LruFusionCache(max_fusions=10)\n def create_fusion(create_fd: Callable):\n with FusionDefinition() as fd:\n create_fd(fd)\n return fd\n\n empty_stats = \"\"\"Max Fusions Allowed: 10\nThe fusion cache is empty.\\n\"\"\"\n assert create_fusion.stats() == empty_stats\n\n # Test LRU cache compilation\n for i in range(5):\n fd1 = create_fusion(create_fd1)\n outputs = fd1.execute(inputs)\n assert torch.allclose(outputs[0], inputs[0] / inputs[1])\n\n fd2 = create_fusion(create_fd2)\n outputs = fd2.execute(inputs)\n assert torch.allclose(outputs[0], inputs[1] / inputs[0])\n assert fd1.fusion == fd1.fusion\n assert fd2.fusion == fd2.fusion\n assert fd1.fusion != fd2.fusion\n\n expected_stats = \"\"\"Max Fusions Allowed: 10\nTotal Fusions in Cache: 2\nTotal Unique Fusions Compiled: 2\nCache Hits by LRU ordering:\n\\t0 -> 4 hits\n\\t1 -> 4 hits\nCache Lookups: 10\nCache Hits: 8\nHit Rate: 80%\\n\"\"\"\n assert create_fusion.stats() == expected_stats\n\n\ndef test_lru_cache():\n bcast_input = torch.randn(1, 4, device=\"cuda\")\n full_input = torch.randn(2, 4, device=\"cuda\")\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.Float,\n# ... truncated ...","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_python_version_API","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_python_version_API#L22-L26","kind":"function","name":"test_python_version_API","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":22,"end_line":26,"context_start_line":2,"context_end_line":46,"code":"# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nfrom nvfuser_direct import (\n FusionDefinition,\n PythonProfiler,\n DataType,\n version,\n LruFusionCache,\n LRUCache,\n)\nimport torch\nimport pytest\nimport io\nimport re\nfrom contextlib import redirect_stdout, redirect_stderr\nfrom typing import Callable\n\n\ndef test_python_version_API():\n from nvfuser_direct.nvfuser_direct_version import Version\n\n assert version() > \"0.0.0\"\n assert version() > Version(\"0.0.0\")\n\n\ndef test_fusion_not_defined():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n # A FusionDefinition object is constructed but not defined, should trip an error\n try:\n fd = FusionDefinition()\n out = fd.execute(inputs)\n raise RuntimeError(\"Expecting an error for an empty FusionDefinition!\")\n except NotImplementedError as e:\n assert (\n \"Fusion does not exist! Use `with FusionDefinition() as fd: ...` to define a fusion.\"\n in str(e)\n )\n\n\ndef test_fusion_empty():","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_fusion_not_defined","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_fusion_not_defined#L29-L43","kind":"function","name":"test_fusion_not_defined","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":29,"end_line":43,"context_start_line":9,"context_end_line":63,"code":" DataType,\n version,\n LruFusionCache,\n LRUCache,\n)\nimport torch\nimport pytest\nimport io\nimport re\nfrom contextlib import redirect_stdout, redirect_stderr\nfrom typing import Callable\n\n\ndef test_python_version_API():\n from nvfuser_direct.nvfuser_direct_version import Version\n\n assert version() > \"0.0.0\"\n assert version() > Version(\"0.0.0\")\n\n\ndef test_fusion_not_defined():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n # A FusionDefinition object is constructed but not defined, should trip an error\n try:\n fd = FusionDefinition()\n out = fd.execute(inputs)\n raise RuntimeError(\"Expecting an error for an empty FusionDefinition!\")\n except NotImplementedError as e:\n assert (\n \"Fusion does not exist! Use `with FusionDefinition() as fd: ...` to define a fusion.\"\n in str(e)\n )\n\n\ndef test_fusion_empty():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n # A FusionDefinition object is constructed but not defined, should trip an error\n with pytest.raises(NotImplementedError, match=\"Fusion is empty!\"):\n with FusionDefinition() as fd:\n pass\n out = fd.execute(inputs)\n\n\ndef test_from_pytorch_fails_on_cpu_tensor():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n stdout_capture = io.StringIO()","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_fusion_empty","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_fusion_empty#L46-L55","kind":"function","name":"test_fusion_empty","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":46,"end_line":55,"context_start_line":26,"context_end_line":75,"code":" assert version() > Version(\"0.0.0\")\n\n\ndef test_fusion_not_defined():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n # A FusionDefinition object is constructed but not defined, should trip an error\n try:\n fd = FusionDefinition()\n out = fd.execute(inputs)\n raise RuntimeError(\"Expecting an error for an empty FusionDefinition!\")\n except NotImplementedError as e:\n assert (\n \"Fusion does not exist! Use `with FusionDefinition() as fd: ...` to define a fusion.\"\n in str(e)\n )\n\n\ndef test_fusion_empty():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n # A FusionDefinition object is constructed but not defined, should trip an error\n with pytest.raises(NotImplementedError, match=\"Fusion is empty!\"):\n with FusionDefinition() as fd:\n pass\n out = fd.execute(inputs)\n\n\ndef test_from_pytorch_fails_on_cpu_tensor():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n error_msg = (\n \"Found unsupported device cpu, only scalar CPU or CUDA tensors are supported\"\n )\n with pytest.raises(ValueError, match=error_msg), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.relu(t0)\n fd.add_output(t1)\n","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_from_pytorch_fails_on_cpu_tensor","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_from_pytorch_fails_on_cpu_tensor#L58-L74","kind":"function","name":"test_from_pytorch_fails_on_cpu_tensor","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":58,"end_line":74,"context_start_line":38,"context_end_line":94,"code":" raise RuntimeError(\"Expecting an error for an empty FusionDefinition!\")\n except NotImplementedError as e:\n assert (\n \"Fusion does not exist! Use `with FusionDefinition() as fd: ...` to define a fusion.\"\n in str(e)\n )\n\n\ndef test_fusion_empty():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n # A FusionDefinition object is constructed but not defined, should trip an error\n with pytest.raises(NotImplementedError, match=\"Fusion is empty!\"):\n with FusionDefinition() as fd:\n pass\n out = fd.execute(inputs)\n\n\ndef test_from_pytorch_fails_on_cpu_tensor():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n error_msg = (\n \"Found unsupported device cpu, only scalar CPU or CUDA tensors are supported\"\n )\n with pytest.raises(ValueError, match=error_msg), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.relu(t0)\n fd.add_output(t1)\n\n\ndef test_fusion_definition_print():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv1 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion math representation\n prescheduled_fusion_definition = \"\"\"Inputs:\n T0_g_float[iS0{2}, iS1{4}, iS2{8}]\n T1_g_float[iS3{2}, iS4{4}, iS5{8}]\nOutputs:\n T2_g_float[iS6{2}, iS7{4}, iS8{8}]\n","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_fusion_definition_print","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_fusion_definition_print#L77-L155","kind":"function","name":"test_fusion_definition_print","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":77,"end_line":155,"context_start_line":57,"context_end_line":175,"code":"\ndef test_from_pytorch_fails_on_cpu_tensor():\n inputs = [\n torch.randn(4, 4, device=\"cpu\"),\n ]\n\n stdout_capture = io.StringIO()\n stderr_capture = io.StringIO()\n error_msg = (\n \"Found unsupported device cpu, only scalar CPU or CUDA tensors are supported\"\n )\n with pytest.raises(ValueError, match=error_msg), redirect_stdout(\n stdout_capture\n ), redirect_stderr(stderr_capture):\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.ops.relu(t0)\n fd.add_output(t1)\n\n\ndef test_fusion_definition_print():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv1 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion math representation\n prescheduled_fusion_definition = \"\"\"Inputs:\n T0_g_float[iS0{2}, iS1{4}, iS2{8}]\n T1_g_float[iS3{2}, iS4{4}, iS5{8}]\nOutputs:\n T2_g_float[iS6{2}, iS7{4}, iS8{8}]\n\n%kernel_math {\nT2_g_float[iS6{2}, iS7{4}, iS8{8}]\n = T0_g_float[iS0{2}, iS1{4}, iS2{8}]\n + T1_g_float[iS3{2}, iS4{4}, iS5{8}];\n} // %kernel_math \\n\\n\"\"\"\n assert fd.fusion.print_math() == prescheduled_fusion_definition\n\n # Test CUDA kernel representation\n cuda_kernel = \"\"\"// Codegen generated code\n__global__ void CUDAGeneratedKernel(Tensor T0, Tensor T1, Tensor T2) {\n NVFUSER_DEFINE_MAGIC_ZERO;\n #pragma unroll\n for(nvfuser_index_t i0 = 0LL; i0 < 2LL; ++i0) {\n nvfuser_index_t i1;\n i1 = T0.alloc_stride[0LL] * i0;\n nvfuser_index_t i2;\n i2 = T1.alloc_stride[0LL] * i0;\n nvfuser_index_t i3;\n i3 = 32LL * i0;\n #pragma unroll\n for(nvfuser_index_t i4 = 0LL; i4 < 4LL; ++i4) {\n nvfuser_index_t i5;\n i5 = i1 + (T0.alloc_stride[1LL] * i4);\n nvfuser_index_t i6;\n i6 = i2 + (T1.alloc_stride[1LL] * i4);\n nvfuser_index_t i7;\n i7 = i3 + (8LL * i4);\n #pragma unroll\n for(nvfuser_index_t i8 = 0LL; i8 < 8LL; ++i8) {\n nvfuser_index_t i9;\n i9 = i8 + nvfuser_zero;\n T2[(i7 + i9)]\n = T0[(i5 + (T0.alloc_stride[2LL] * i9))]\n + T1[(i6 + (T1.alloc_stride[2LL] * i9))];\n }\n }\n }\n NVFUSER_UPDATE_MAGIC_ZERO;\n}\n\"\"\"\n assert fd.fusion.print_kernel() == cuda_kernel\n\n # Test TensorView string representation\n assert str(tv0) == r\"T0_g_float[iS0{2}, iS1{4}, iS2{8}]\"\n assert str(tv1) == r\"T1_g_float[iS3{2}, iS4{4}, iS5{8}]\"\n assert str(tv2) == r\"T2_g_float[iS6{2}, iS7{4}, iS8{8}]\"\n\n # Test TensorDomain string representation\n assert str(tv0.domain()) == r\"[iS0{2}, iS1{4}, iS2{8}]\"\n assert str(tv1.domain()) == r\"[iS3{2}, iS4{4}, iS5{8}]\"\n assert str(tv2.domain()) == r\"[iS6{2}, iS7{4}, iS8{8}]\"\n\n # Test IterDomain string representation\n assert str(tv0.axis(0)) == r\"iS0{2}\"\n assert str(tv1.axis(0)) == r\"iS3{2}\"\n assert str(tv2.axis(0)) == r\"iS6{2}\"\n\n # Test axis extents\n assert str(tv0.axis(0).extent()) == r\"2\"\n assert str(tv1.axis(0).extent()) == r\"2\"\n assert str(tv2.axis(0).extent()) == r\"2\"\n\n\ndef test_fusion_execution_cache():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv1 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n results = fd.execute(inputs)\n torch.testing.assert_close(results[0], inputs[0] + inputs[1])","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_fusion_execution_cache","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_fusion_execution_cache#L158-L254","kind":"function","name":"test_fusion_execution_cache","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":158,"end_line":254,"context_start_line":138,"context_end_line":274,"code":" assert str(tv0) == r\"T0_g_float[iS0{2}, iS1{4}, iS2{8}]\"\n assert str(tv1) == r\"T1_g_float[iS3{2}, iS4{4}, iS5{8}]\"\n assert str(tv2) == r\"T2_g_float[iS6{2}, iS7{4}, iS8{8}]\"\n\n # Test TensorDomain string representation\n assert str(tv0.domain()) == r\"[iS0{2}, iS1{4}, iS2{8}]\"\n assert str(tv1.domain()) == r\"[iS3{2}, iS4{4}, iS5{8}]\"\n assert str(tv2.domain()) == r\"[iS6{2}, iS7{4}, iS8{8}]\"\n\n # Test IterDomain string representation\n assert str(tv0.axis(0)) == r\"iS0{2}\"\n assert str(tv1.axis(0)) == r\"iS3{2}\"\n assert str(tv2.axis(0)) == r\"iS6{2}\"\n\n # Test axis extents\n assert str(tv0.axis(0).extent()) == r\"2\"\n assert str(tv1.axis(0).extent()) == r\"2\"\n assert str(tv2.axis(0).extent()) == r\"2\"\n\n\ndef test_fusion_execution_cache():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv1 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n results = fd.execute(inputs)\n torch.testing.assert_close(results[0], inputs[0] + inputs[1])\n\n # Check that TensorViews are accessible after running fusion\n assert str(tv0.domain()) == \"[iS0{2}, iS1{4}, iS2{8}]\"\n assert str(tv1.domain()) == \"[iS3{2}, iS4{4}, iS5{8}]\"\n assert str(tv2.domain()) == \"[iS6{2}, iS7{4}, iS8{8}]\"\n\n with pytest.raises(\n AssertionError,\n match=r\"FusionExecutorCache already exists! Use execute\\(\\) to execute the fusion.\",\n ):\n fd.manual_execute(inputs)\n\n # Test fusion math representation after compilation\n prescheduled_fusion_definition = \"\"\"Inputs:\n T0_g_float[iS0{2}, iS1{4}, iS2{8}]\n T1_g_float[iS3{2}, iS4{4}, iS5{8}]\nOutputs:\n T2_g_float[iS6{2}, iS7{4}, iS8{8}]\n\n%kernel_math {\nT2_g_float[iS6{2}, iS7{4}, iS8{8}]\n = T0_g_float[iS0{2}, iS1{4}, iS2{8}]\n + T1_g_float[iS3{2}, iS4{4}, iS5{8}];\n} // %kernel_math \\n\\n\"\"\"\n assert fd.fusion.print_math() == prescheduled_fusion_definition\n\n # Test compilation status\n assert fd.fec.is_compiled(inputs)\n\n # Test scheduled IR representation\n scheduled_ir = \"\"\"Inputs:\n T0_g_float[iS58{1}, iS59{1}, iS57{128}]\n T1_g_float[iS46{1}, iS47{1}, iS45{128}]\nOutputs:\n T2_g_float[iblockIdx.x28{1}, iUS29{1}, ithreadIdx.x27{128}] ca_pos( 2 ) produce_pos( 3 )\n\n%kernel {\nT3_l_float[iblockIdx.x52{1}, iUS53{1}, ithreadIdx.x51{128}] ca_pos( 2 )\n = Set( T0_g_float[iS58{1}, iS59{1}, iS57{128}], cache_op=Streaming )\nT4_l_float[iblockIdx.x40{1}, iUS41{1}, ithreadIdx.x39{128}] ca_pos( 2 )\n = Set( T1_g_float[iS46{1}, iS47{1}, iS45{128}], cache_op=Streaming )\nT5_l_float[iblockIdx.x34{1}, iUS35{1}, ithreadIdx.x33{128}] ca_pos( 3 ) produce_pos( 2 )\n = T3_l_float[iblockIdx.x52{1}, iUS53{1}, ithreadIdx.x51{128}] ca_pos( 2 )\n + T4_l_float[iblockIdx.x40{1}, iUS41{1}, ithreadIdx.x39{128}] ca_pos( 2 );\nT2_g_float[iblockIdx.x28{1}, iUS29{1}, ithreadIdx.x27{128}] ca_pos( 2 ) produce_pos( 3 )\n = Set( T5_l_float[iblockIdx.x34{1}, iUS35{1}, ithreadIdx.x33{128}] ca_pos( 3 ) produce_pos( 2 ), cache_op=Streaming )\n} // %kernel\\n\"\"\"\n assert fd.fec.get_scheduled_ir(inputs) == scheduled_ir\n assert fd.fec.get_most_recent_scheduled_ir() == scheduled_ir\n\n # Test CUDA kernel representation\n cuda_kernel = \"\"\"// Codegen generated code\n__global__ void nvfuser_pointwise_f0_c1_r0_g0(Tensor T0, Tensor T1, Tensor T2) {\n nvfuser_index_t i0;\n i0 = ((nvfuser_index_t)threadIdx.x) % 32;\n nvfuser_index_t i1;\n i1 = ((nvfuser_index_t)threadIdx.x) / 32;\n nvfuser_index_t i2;\n i2 = i0 / 8;\n nvfuser_index_t i3;\n i3 = i0 % 8;\n if ((((nvfuser_index_t)threadIdx.x) < 64)) {\n Array T4;\n T4[0] = 0;\n T4[0]\n = T1[(((T1.alloc_stride[0LL] * i1) + (T1.alloc_stride[1LL] * i2)) + (T1.alloc_stride[2LL] * i3))];\n Array T3;\n T3[0] = 0;\n T3[0]\n = T0[(((T0.alloc_stride[0LL] * i1) + (T0.alloc_stride[1LL] * i2)) + (T0.alloc_stride[2LL] * i3))];\n Array T5;\n T5[0]\n = T3[0]\n + T4[0];\n T2[((nvfuser_index_t)threadIdx.x)]\n = T5[0];\n }\n}\\n\"\"\"\n assert fd.fec.get_cuda_kernel(inputs) == cuda_kernel\n\n\ndef test_kernel_executor():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv1 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n results = fd.manual_execute(inputs)\n torch.testing.assert_close(results[0], inputs[0] + inputs[1])","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_kernel_executor","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_kernel_executor#L257-L281","kind":"function","name":"test_kernel_executor","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":257,"end_line":281,"context_start_line":237,"context_end_line":301,"code":" if ((((nvfuser_index_t)threadIdx.x) < 64)) {\n Array T4;\n T4[0] = 0;\n T4[0]\n = T1[(((T1.alloc_stride[0LL] * i1) + (T1.alloc_stride[1LL] * i2)) + (T1.alloc_stride[2LL] * i3))];\n Array T3;\n T3[0] = 0;\n T3[0]\n = T0[(((T0.alloc_stride[0LL] * i1) + (T0.alloc_stride[1LL] * i2)) + (T0.alloc_stride[2LL] * i3))];\n Array T5;\n T5[0]\n = T3[0]\n + T4[0];\n T2[((nvfuser_index_t)threadIdx.x)]\n = T5[0];\n }\n}\\n\"\"\"\n assert fd.fec.get_cuda_kernel(inputs) == cuda_kernel\n\n\ndef test_kernel_executor():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv1 = fd.define_tensor(\n shape=[2, 4, 8],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n results = fd.manual_execute(inputs)\n torch.testing.assert_close(results[0], inputs[0] + inputs[1])\n assert fd.ke.is_compiled()\n\n with pytest.raises(\n AssertionError,\n match=r\"KernelExecutor already exists! Use manual_execute\\(\\) to execute the fusion.\",\n ):\n fd.execute(inputs)\n\n\ndef test_repro_script_for():\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\"),\n torch.ones(2, 4, 8, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [1], False, DataType.Float)\n\n fd.add_output(t4)\n\n expected_repro = \"\"\"","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_repro_script_for","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_repro_script_for#L284-L342","kind":"function","name":"test_repro_script_for","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":284,"end_line":342,"context_start_line":264,"context_end_line":362,"code":" )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n results = fd.manual_execute(inputs)\n torch.testing.assert_close(results[0], inputs[0] + inputs[1])\n assert fd.ke.is_compiled()\n\n with pytest.raises(\n AssertionError,\n match=r\"KernelExecutor already exists! Use manual_execute\\(\\) to execute the fusion.\",\n ):\n fd.execute(inputs)\n\n\ndef test_repro_script_for():\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda\"),\n torch.ones(2, 4, 8, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [1], False, DataType.Float)\n\n fd.add_output(t4)\n\n expected_repro = \"\"\"\nimport torch\nfrom nvfuser_direct import FusionDefinition, DataType\ndef nvfuser_fusion(fd : FusionDefinition) -> None :\n tv0 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv1 = fd.define_tensor(shape=[-1, -1, -1], contiguity=[True, True, True], dtype=DataType.Float, is_cpu=False)\n tv2 = fd.ops.add(tv0, tv1)\n tv3 = fd.ops.mul(tv2, 3.00000)\n tv4 = fd.ops.sum(tv3, dims=[1], dtype=DataType.Float)\n fd.add_output(tv4)\nwith FusionDefinition() as fd:\n nvfuser_fusion(fd)\n\"\"\"\n\n expected_inputs = \"\"\"\ninputs = [\n torch.testing.make_tensor((2, 4, 8), dtype=torch.float32, device='cuda:0'),\n torch.testing.make_tensor((2, 4, 8), dtype=torch.float32, device='cuda:0'),\n]\nfd.execute(inputs)\\n\"\"\"\n\n # fd.repro_script_for(inputs) should have input arguments\n repro_with_inputs = fd.repro_script_for(inputs)\n assert expected_repro in repro_with_inputs\n assert expected_inputs in repro_with_inputs\n\n # fd.repro_script_for() should NOT have input arguments\n repro_without_inputs = fd.repro_script_for()\n assert expected_repro in repro_without_inputs\n assert expected_inputs not in repro_without_inputs\n\n # Check last_repro_script fails gracefully.\n with pytest.raises(\n AssertionError,\n match=r\"fd.last_repro_script\\(\\) cannot provide a repro because fd.execute\\(inputs, save_repro_inputs=True\\) was not executed!\",\n ):\n fd.last_repro_script()\n\n # Test fd.execute(inputs, save_repro_inputs=True) ; fd.last_repro_script()\n fd.execute(inputs, save_repro_inputs=True)\n last_repro = fd.last_repro_script()\n assert repro_with_inputs == last_repro\n\n\ndef test_define_tensor():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n tv1 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_define_tensor","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_define_tensor#L345-L370","kind":"function","name":"test_define_tensor","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":345,"end_line":370,"context_start_line":325,"context_end_line":390,"code":" assert expected_inputs in repro_with_inputs\n\n # fd.repro_script_for() should NOT have input arguments\n repro_without_inputs = fd.repro_script_for()\n assert expected_repro in repro_without_inputs\n assert expected_inputs not in repro_without_inputs\n\n # Check last_repro_script fails gracefully.\n with pytest.raises(\n AssertionError,\n match=r\"fd.last_repro_script\\(\\) cannot provide a repro because fd.execute\\(inputs, save_repro_inputs=True\\) was not executed!\",\n ):\n fd.last_repro_script()\n\n # Test fd.execute(inputs, save_repro_inputs=True) ; fd.last_repro_script()\n fd.execute(inputs, save_repro_inputs=True)\n last_repro = fd.last_repro_script()\n assert repro_with_inputs == last_repro\n\n\ndef test_define_tensor():\n with FusionDefinition() as fd:\n tv0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n tv1 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution with dynamic shapes\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n outputs = fd.execute(inputs)\n torch.testing.assert_close(outputs[0], inputs[0] + inputs[1])\n\n\n@pytest.mark.skipif(\n torch.cuda.device_count() < 2,\n reason=\"test_selected_device requires multiple GPUs\",\n)\ndef test_execute_with_different_device():\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda:1\"),\n torch.ones(2, 4, 8, device=\"cuda:1\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [1], False, DataType.Float)","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_execute_with_different_device","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_execute_with_different_device#L377-L396","kind":"function","name":"test_execute_with_different_device","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":377,"end_line":396,"context_start_line":357,"context_end_line":416,"code":" dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n tv2 = fd.ops.add(tv0, tv1)\n fd.add_output(tv2)\n\n # Test fusion execution with dynamic shapes\n inputs = [\n torch.randn(2, 4, 8, device=\"cuda\"),\n torch.randn(2, 4, 8, device=\"cuda\"),\n ]\n outputs = fd.execute(inputs)\n torch.testing.assert_close(outputs[0], inputs[0] + inputs[1])\n\n\n@pytest.mark.skipif(\n torch.cuda.device_count() < 2,\n reason=\"test_selected_device requires multiple GPUs\",\n)\ndef test_execute_with_different_device():\n inputs = [\n torch.ones(2, 4, 8, device=\"cuda:1\"),\n torch.ones(2, 4, 8, device=\"cuda:1\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [1], False, DataType.Float)\n\n fd.add_output(t4)\n\n outputs = fd.execute(inputs, device=\"cuda:1\")\n assert len(outputs) == 1\n assert outputs[0].device.index == 1\n\n\ndef test_enable_disable_options():\n m = 24\n n = 16\n k = 8\n inps = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.float),\n torch.randn(k, n, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition, inps) -> None:\n t0 = fd.from_pytorch(inps[0])\n t1 = fd.from_pytorch(inps[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n with FusionDefinition() as fd:\n fusion_func(fd, inps=inps)\n","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_enable_disable_options","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_enable_disable_options#L399-L430","kind":"function","name":"test_enable_disable_options","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":399,"end_line":430,"context_start_line":379,"context_end_line":450,"code":" torch.ones(2, 4, 8, device=\"cuda:1\"),\n torch.ones(2, 4, 8, device=\"cuda:1\"),\n ]\n\n with FusionDefinition() as fd:\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n c0 = fd.define_scalar(3.0)\n\n t2 = fd.ops.add(t0, t1)\n t3 = fd.ops.mul(t2, c0)\n t4 = fd.ops.sum(t3, [1], False, DataType.Float)\n\n fd.add_output(t4)\n\n outputs = fd.execute(inputs, device=\"cuda:1\")\n assert len(outputs) == 1\n assert outputs[0].device.index == 1\n\n\ndef test_enable_disable_options():\n m = 24\n n = 16\n k = 8\n inps = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.float),\n torch.randn(k, n, device=\"cuda\", dtype=torch.float),\n ]\n\n def fusion_func(fd: FusionDefinition, inps) -> None:\n t0 = fd.from_pytorch(inps[0])\n t1 = fd.from_pytorch(inps[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n with FusionDefinition() as fd:\n fusion_func(fd, inps=inps)\n\n # By default, matmul will be be run through expr_eval scheduler.\n # Through setting the enable and disable options as below,\n # we can execute it through matmul scheduler. The above fusion will not\n # be accepted by the matmul scheduler since the outputs are of type Float and raises a RuntimeError.\n # Note: We use this error-based test since for compatible dtypes (float16/bfloat16),\n # the matmul scheduler ran into a scheduling error on H100. This test might be more robust against\n # changes in matmul scheduler in the interim.\n\n with pytest.raises(\n RuntimeError, match=\"Can not find a scheduler to schedule fusion segment\"\n ):\n fd.execute(\n inps, _enable_options=[\"fuse_matmul\"], _disable_options=[\"matmul_expr_eval\"]\n )\n\n\n# Test that we properly raise an error when passing inputs with the wrong types\ndef test_mismatched_input_types():\n scalar_inp = 2.0\n tensor_inp = torch.rand((15,), dtype=torch.float32, device=\"cuda:0\")\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n s0 = fd.define_scalar()\n T1 = fd.ops.mul(T0, s0)\n fd.add_output(T1)\n\n with FusionDefinition() as fd:","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_mismatched_input_types","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_mismatched_input_types#L434-L480","kind":"function","name":"test_mismatched_input_types","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":434,"end_line":480,"context_start_line":414,"context_end_line":500,"code":" with FusionDefinition() as fd:\n fusion_func(fd, inps=inps)\n\n # By default, matmul will be be run through expr_eval scheduler.\n # Through setting the enable and disable options as below,\n # we can execute it through matmul scheduler. The above fusion will not\n # be accepted by the matmul scheduler since the outputs are of type Float and raises a RuntimeError.\n # Note: We use this error-based test since for compatible dtypes (float16/bfloat16),\n # the matmul scheduler ran into a scheduling error on H100. This test might be more robust against\n # changes in matmul scheduler in the interim.\n\n with pytest.raises(\n RuntimeError, match=\"Can not find a scheduler to schedule fusion segment\"\n ):\n fd.execute(\n inps, _enable_options=[\"fuse_matmul\"], _disable_options=[\"matmul_expr_eval\"]\n )\n\n\n# Test that we properly raise an error when passing inputs with the wrong types\ndef test_mismatched_input_types():\n scalar_inp = 2.0\n tensor_inp = torch.rand((15,), dtype=torch.float32, device=\"cuda:0\")\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1],\n contiguity=[True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[0],\n )\n s0 = fd.define_scalar()\n T1 = fd.ops.mul(T0, s0)\n fd.add_output(T1)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n with pytest.raises(\n Exception,\n match=\"Expected input 0, .*, to be an at::Tensor but got scalar 2\",\n ):\n nvf_out = fd.execute([scalar_inp, scalar_inp])\n\n with pytest.raises(\n Exception,\n match=re.escape(\n \"Expected input 1, d2, to be a scalar but got float tensor of rank 1\"\n ),\n ):\n nvf_out = fd.execute([tensor_inp, tensor_inp])\n\n with pytest.raises(\n Exception,\n match=\"Expected input 0, .*, to be bound to a tensor of dtype float, but got a tensor of dtype __half\",\n ):\n wrong_tensor_inp = torch.rand((15,), dtype=torch.float16, device=\"cuda:0\")\n nvf_out = fd.execute([wrong_tensor_inp, 2.0])\n\n with pytest.raises(\n Exception,\n match=re.escape(\n \"Scalar value (2,1) is not compatible with the expected data type: double.\"\n ),\n ):\n nvf_out = fd.execute([tensor_inp, 2.0 + 1.0j])\n\n\ndef test_fusion_profiler_auto_scheduled():\n inputs = [\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.add(T0, T1)\n T3 = fd.ops.sum(T2, dim=-1)\n T4 = fd.ops.sum(T3, dim=-1)\n fd.add_output(T4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n # Testing that the profile returns 2 segments","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_fusion_profiler_auto_scheduled","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_fusion_profiler_auto_scheduled#L483-L511","kind":"function","name":"test_fusion_profiler_auto_scheduled","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":483,"end_line":511,"context_start_line":463,"context_end_line":531,"code":" ),\n ):\n nvf_out = fd.execute([tensor_inp, tensor_inp])\n\n with pytest.raises(\n Exception,\n match=\"Expected input 0, .*, to be bound to a tensor of dtype float, but got a tensor of dtype __half\",\n ):\n wrong_tensor_inp = torch.rand((15,), dtype=torch.float16, device=\"cuda:0\")\n nvf_out = fd.execute([wrong_tensor_inp, 2.0])\n\n with pytest.raises(\n Exception,\n match=re.escape(\n \"Scalar value (2,1) is not compatible with the expected data type: double.\"\n ),\n ):\n nvf_out = fd.execute([tensor_inp, 2.0 + 1.0j])\n\n\ndef test_fusion_profiler_auto_scheduled():\n inputs = [\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.add(T0, T1)\n T3 = fd.ops.sum(T2, dim=-1)\n T4 = fd.ops.sum(T3, dim=-1)\n fd.add_output(T4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n # Testing that the profile returns 2 segments\n try:\n with PythonProfiler() as prof:\n fd.execute(inputs)\n assert prof.profile.segments == 2\n assert len(prof.profile.kernel_profiles) == 2\n except Exception as e:\n print(e)\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_fusion_profiler_user_scheduled():\n inputs = [\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.add(T0, T1)\n fd.add_output(T2)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n try:\n with PythonProfiler(auto_scheduled=False) as prof:\n fd.manual_execute(inputs)","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_fusion_profiler_user_scheduled","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_fusion_profiler_user_scheduled#L514-L538","kind":"function","name":"test_fusion_profiler_user_scheduled","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":514,"end_line":538,"context_start_line":494,"context_end_line":558,"code":" T4 = fd.ops.sum(T3, dim=-1)\n fd.add_output(T4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n # Testing that the profile returns 2 segments\n try:\n with PythonProfiler() as prof:\n fd.execute(inputs)\n assert prof.profile.segments == 2\n assert len(prof.profile.kernel_profiles) == 2\n except Exception as e:\n print(e)\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_fusion_profiler_user_scheduled():\n inputs = [\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n torch.randn((2, 5), dtype=torch.float, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.add(T0, T1)\n fd.add_output(T2)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n try:\n with PythonProfiler(auto_scheduled=False) as prof:\n fd.manual_execute(inputs)\n assert prof.profile.fusion_id >= 0\n assert prof.profile.kernel_profiles[0].scheduler == \"user\"\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_fusion_profiler_with_noncodegen_kernels():\n inputs = [\n torch.randn((2, 4, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((2, 4, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((16, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.from_pytorch(inputs[2])\n T3 = fd.ops.linear(T0, T2)\n T4 = fd.ops.add(T3, T1)\n fd.add_output(T4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_fusion_profiler_with_noncodegen_kernels","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_fusion_profiler_with_noncodegen_kernels#L541-L569","kind":"function","name":"test_fusion_profiler_with_noncodegen_kernels","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":541,"end_line":569,"context_start_line":521,"context_end_line":589,"code":" T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.ops.add(T0, T1)\n fd.add_output(T2)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n try:\n with PythonProfiler(auto_scheduled=False) as prof:\n fd.manual_execute(inputs)\n assert prof.profile.fusion_id >= 0\n assert prof.profile.kernel_profiles[0].scheduler == \"user\"\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_fusion_profiler_with_noncodegen_kernels():\n inputs = [\n torch.randn((2, 4, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((2, 4, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((16, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.from_pytorch(inputs[2])\n T3 = fd.ops.linear(T0, T2)\n T4 = fd.ops.add(T3, T1)\n fd.add_output(T4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n try:\n with PythonProfiler() as prof:\n fd.execute(inputs)\n assert len(prof.profile.kernel_profiles) == 2\n assert len(prof.profile.kernel_profiles[0].name) > 0\n assert len(prof.profile.kernel_profiles[1].name) > 0\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_lru_fusion_cache_decorator():\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(2, 4, device=\"cuda\"),\n ]\n\n def create_fd1(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n fd.add_output(t2)\n\n def create_fd2(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t1, t0)\n fd.add_output(t2)\n","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_lru_fusion_cache_decorator","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_lru_fusion_cache_decorator#L572-L622","kind":"function","name":"test_lru_fusion_cache_decorator","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":572,"end_line":622,"context_start_line":552,"context_end_line":642,"code":" T3 = fd.ops.linear(T0, T2)\n T4 = fd.ops.add(T3, T1)\n fd.add_output(T4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n try:\n with PythonProfiler() as prof:\n fd.execute(inputs)\n assert len(prof.profile.kernel_profiles) == 2\n assert len(prof.profile.kernel_profiles[0].name) > 0\n assert len(prof.profile.kernel_profiles[1].name) > 0\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_lru_fusion_cache_decorator():\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(2, 4, device=\"cuda\"),\n ]\n\n def create_fd1(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n fd.add_output(t2)\n\n def create_fd2(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t1, t0)\n fd.add_output(t2)\n\n @LruFusionCache(max_fusions=10)\n def create_fusion(create_fd: Callable):\n with FusionDefinition() as fd:\n create_fd(fd)\n return fd\n\n empty_stats = \"\"\"Max Fusions Allowed: 10\nThe fusion cache is empty.\\n\"\"\"\n assert create_fusion.stats() == empty_stats\n\n # Test LRU cache compilation\n for i in range(5):\n fd1 = create_fusion(create_fd1)\n outputs = fd1.execute(inputs)\n assert torch.allclose(outputs[0], inputs[0] / inputs[1])\n\n fd2 = create_fusion(create_fd2)\n outputs = fd2.execute(inputs)\n assert torch.allclose(outputs[0], inputs[1] / inputs[0])\n assert fd1.fusion == fd1.fusion\n assert fd2.fusion == fd2.fusion\n assert fd1.fusion != fd2.fusion\n\n expected_stats = \"\"\"Max Fusions Allowed: 10\nTotal Fusions in Cache: 2\nTotal Unique Fusions Compiled: 2\nCache Hits by LRU ordering:\n\\t0 -> 4 hits\n\\t1 -> 4 hits\nCache Lookups: 10\nCache Hits: 8\nHit Rate: 80%\\n\"\"\"\n assert create_fusion.stats() == expected_stats\n\n\ndef test_lru_cache():\n bcast_input = torch.randn(1, 4, device=\"cuda\")\n full_input = torch.randn(2, 4, device=\"cuda\")\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.test_lru_cache","uri":"program://Fuser/function/tests.python.direct.test_python_direct.test_lru_cache#L625-L691","kind":"function","name":"test_lru_cache","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":625,"end_line":691,"context_start_line":605,"context_end_line":691,"code":"\n fd2 = create_fusion(create_fd2)\n outputs = fd2.execute(inputs)\n assert torch.allclose(outputs[0], inputs[1] / inputs[0])\n assert fd1.fusion == fd1.fusion\n assert fd2.fusion == fd2.fusion\n assert fd1.fusion != fd2.fusion\n\n expected_stats = \"\"\"Max Fusions Allowed: 10\nTotal Fusions in Cache: 2\nTotal Unique Fusions Compiled: 2\nCache Hits by LRU ordering:\n\\t0 -> 4 hits\n\\t1 -> 4 hits\nCache Lookups: 10\nCache Hits: 8\nHit Rate: 80%\\n\"\"\"\n assert create_fusion.stats() == expected_stats\n\n\ndef test_lru_cache():\n bcast_input = torch.randn(1, 4, device=\"cuda\")\n full_input = torch.randn(2, 4, device=\"cuda\")\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.sub(T0, T1)\n fd.add_output(T2)\n\n # nvfuser_fusion_id1 reverses the input argument order of nvfuser_fusion_id0\n def nvfuser_fusion_id1(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.sub(T0, T1)\n fd.add_output(T2)\n\n cache = LRUCache(max_fusions=10)\n\n with FusionDefinition() as fd0:\n nvfuser_fusion_id0(fd0)\n\n assert cache.num_fusions() == 0\n fd0.fec = cache.cache_compile(fd0.fusion)\n del fd0._fusion\n # Check that LRUCache caches the first fusion\n assert cache.num_fusions() == 1\n\n with FusionDefinition() as fd1:\n nvfuser_fusion_id1(fd1)\n\n assert cache.num_fusions() == 1\n fd1.fec = cache.cache_compile(fd1.fusion)\n del fd1._fusion\n # Check that LRUCache creates a separate entry for second fusion\n assert cache.num_fusions() == 2\n\n assert torch.allclose(\n fd0.execute([bcast_input, full_input])[0], bcast_input - full_input\n )\n assert torch.allclose(\n fd1.execute([full_input, bcast_input])[0], bcast_input - full_input\n )","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.fusion_func","uri":"program://Fuser/function/tests.python.direct.test_python_direct.fusion_func#L548-L554","kind":"function","name":"fusion_func","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":548,"end_line":554,"context_start_line":528,"context_end_line":574,"code":"\n try:\n with PythonProfiler(auto_scheduled=False) as prof:\n fd.manual_execute(inputs)\n assert prof.profile.fusion_id >= 0\n assert prof.profile.kernel_profiles[0].scheduler == \"user\"\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_fusion_profiler_with_noncodegen_kernels():\n inputs = [\n torch.randn((2, 4, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((2, 4, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n torch.randn((16, 16), dtype=torch.bfloat16, device=\"cuda:0\"),\n ]\n\n def fusion_func(fd: FusionDefinition) -> None:\n T0 = fd.from_pytorch(inputs[0])\n T1 = fd.from_pytorch(inputs[1])\n T2 = fd.from_pytorch(inputs[2])\n T3 = fd.ops.linear(T0, T2)\n T4 = fd.ops.add(T3, T1)\n fd.add_output(T4)\n\n with FusionDefinition() as fd:\n fusion_func(fd)\n\n try:\n with PythonProfiler() as prof:\n fd.execute(inputs)\n assert len(prof.profile.kernel_profiles) == 2\n assert len(prof.profile.kernel_profiles[0].name) > 0\n assert len(prof.profile.kernel_profiles[1].name) > 0\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_lru_fusion_cache_decorator():\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.create_fd1","uri":"program://Fuser/function/tests.python.direct.test_python_direct.create_fd1#L578-L582","kind":"function","name":"create_fd1","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":578,"end_line":582,"context_start_line":558,"context_end_line":602,"code":"\n try:\n with PythonProfiler() as prof:\n fd.execute(inputs)\n assert len(prof.profile.kernel_profiles) == 2\n assert len(prof.profile.kernel_profiles[0].name) > 0\n assert len(prof.profile.kernel_profiles[1].name) > 0\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_lru_fusion_cache_decorator():\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(2, 4, device=\"cuda\"),\n ]\n\n def create_fd1(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n fd.add_output(t2)\n\n def create_fd2(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t1, t0)\n fd.add_output(t2)\n\n @LruFusionCache(max_fusions=10)\n def create_fusion(create_fd: Callable):\n with FusionDefinition() as fd:\n create_fd(fd)\n return fd\n\n empty_stats = \"\"\"Max Fusions Allowed: 10\nThe fusion cache is empty.\\n\"\"\"\n assert create_fusion.stats() == empty_stats\n\n # Test LRU cache compilation\n for i in range(5):\n fd1 = create_fusion(create_fd1)","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.create_fd2","uri":"program://Fuser/function/tests.python.direct.test_python_direct.create_fd2#L584-L588","kind":"function","name":"create_fd2","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":584,"end_line":588,"context_start_line":564,"context_end_line":608,"code":" assert len(prof.profile.kernel_profiles[1].name) > 0\n except Exception as e:\n raise RuntimeError(\n \"FusionDefinition did not run correctly with profile enabled! Error: \"\n + str(e)\n )\n\n\ndef test_lru_fusion_cache_decorator():\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(2, 4, device=\"cuda\"),\n ]\n\n def create_fd1(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n fd.add_output(t2)\n\n def create_fd2(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t1, t0)\n fd.add_output(t2)\n\n @LruFusionCache(max_fusions=10)\n def create_fusion(create_fd: Callable):\n with FusionDefinition() as fd:\n create_fd(fd)\n return fd\n\n empty_stats = \"\"\"Max Fusions Allowed: 10\nThe fusion cache is empty.\\n\"\"\"\n assert create_fusion.stats() == empty_stats\n\n # Test LRU cache compilation\n for i in range(5):\n fd1 = create_fusion(create_fd1)\n outputs = fd1.execute(inputs)\n assert torch.allclose(outputs[0], inputs[0] / inputs[1])\n\n fd2 = create_fusion(create_fd2)\n outputs = fd2.execute(inputs)\n assert torch.allclose(outputs[0], inputs[1] / inputs[0])","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.create_fusion","uri":"program://Fuser/function/tests.python.direct.test_python_direct.create_fusion#L591-L594","kind":"function","name":"create_fusion","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":591,"end_line":594,"context_start_line":571,"context_end_line":614,"code":"\ndef test_lru_fusion_cache_decorator():\n inputs = [\n torch.randn(2, 4, device=\"cuda\"),\n torch.randn(2, 4, device=\"cuda\"),\n ]\n\n def create_fd1(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t0, t1)\n fd.add_output(t2)\n\n def create_fd2(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.div(t1, t0)\n fd.add_output(t2)\n\n @LruFusionCache(max_fusions=10)\n def create_fusion(create_fd: Callable):\n with FusionDefinition() as fd:\n create_fd(fd)\n return fd\n\n empty_stats = \"\"\"Max Fusions Allowed: 10\nThe fusion cache is empty.\\n\"\"\"\n assert create_fusion.stats() == empty_stats\n\n # Test LRU cache compilation\n for i in range(5):\n fd1 = create_fusion(create_fd1)\n outputs = fd1.execute(inputs)\n assert torch.allclose(outputs[0], inputs[0] / inputs[1])\n\n fd2 = create_fusion(create_fd2)\n outputs = fd2.execute(inputs)\n assert torch.allclose(outputs[0], inputs[1] / inputs[0])\n assert fd1.fusion == fd1.fusion\n assert fd2.fusion == fd2.fusion\n assert fd1.fusion != fd2.fusion\n\n expected_stats = \"\"\"Max Fusions Allowed: 10\nTotal Fusions in Cache: 2","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.nvfuser_fusion_id0","uri":"program://Fuser/function/tests.python.direct.test_python_direct.nvfuser_fusion_id0#L629-L645","kind":"function","name":"nvfuser_fusion_id0","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":629,"end_line":645,"context_start_line":609,"context_end_line":665,"code":" assert fd1.fusion == fd1.fusion\n assert fd2.fusion == fd2.fusion\n assert fd1.fusion != fd2.fusion\n\n expected_stats = \"\"\"Max Fusions Allowed: 10\nTotal Fusions in Cache: 2\nTotal Unique Fusions Compiled: 2\nCache Hits by LRU ordering:\n\\t0 -> 4 hits\n\\t1 -> 4 hits\nCache Lookups: 10\nCache Hits: 8\nHit Rate: 80%\\n\"\"\"\n assert create_fusion.stats() == expected_stats\n\n\ndef test_lru_cache():\n bcast_input = torch.randn(1, 4, device=\"cuda\")\n full_input = torch.randn(2, 4, device=\"cuda\")\n\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.sub(T0, T1)\n fd.add_output(T2)\n\n # nvfuser_fusion_id1 reverses the input argument order of nvfuser_fusion_id0\n def nvfuser_fusion_id1(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.sub(T0, T1)\n fd.add_output(T2)\n","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct.test_python_direct.nvfuser_fusion_id1","uri":"program://Fuser/function/tests.python.direct.test_python_direct.nvfuser_fusion_id1#L648-L664","kind":"function","name":"nvfuser_fusion_id1","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":648,"end_line":664,"context_start_line":628,"context_end_line":684,"code":"\n def nvfuser_fusion_id0(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.sub(T0, T1)\n fd.add_output(T2)\n\n # nvfuser_fusion_id1 reverses the input argument order of nvfuser_fusion_id0\n def nvfuser_fusion_id1(fd: FusionDefinition) -> None:\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.sub(T0, T1)\n fd.add_output(T2)\n\n cache = LRUCache(max_fusions=10)\n\n with FusionDefinition() as fd0:\n nvfuser_fusion_id0(fd0)\n\n assert cache.num_fusions() == 0\n fd0.fec = cache.cache_compile(fd0.fusion)\n del fd0._fusion\n # Check that LRUCache caches the first fusion\n assert cache.num_fusions() == 1\n\n with FusionDefinition() as fd1:\n nvfuser_fusion_id1(fd1)\n\n assert cache.num_fusions() == 1\n fd1.fec = cache.cache_compile(fd1.fusion)\n del fd1._fusion\n # Check that LRUCache creates a separate entry for second fusion\n assert cache.num_fusions() == 2","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer_engine","uri":"program://Fuser/module/tests.python.multidevice.test_transformer_engine#L1-L153","kind":"module","name":"tests.python.multidevice.test_transformer_engine","path":"tests/python/multidevice/test_transformer_engine.py","language":"python","start_line":1,"end_line":153,"context_start_line":1,"context_end_line":153,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\nimport torch.distributed as dist\n\nimport transformer_engine.pytorch as te\n\nfrom . import Parallelism\nfrom .benchmark_utils import get_benchmark_fns\nfrom enum import auto, Enum\n\ncompute_cap = torch.cuda.get_device_capability()\n\n\nclass ComputeType(Enum):\n FORWARD = auto()\n BACKWARD = auto()\n\n\n# This benchmark is instrumented with cudaProfilerStart/Stop. Therefore, one\n# can collect stats of the first few non-warmup benchmark iterations using\n# ```bash\n# mpirun -np nsys profile --capture-range=cudaProfilerApi --capture-range-end=repeat: pytest tests/python/test_transformer_engine.py -k --only-mpi\n# ```\n# and then display the status using e.g. `nsys stats --report=cuda_gpu_kern_sum report1.nsys-rep`.\n@pytest.mark.skipif(\n compute_cap >= (10, 0) and compute_cap < (12, 0),\n reason=f\"TransformerEngine stalls this test on devices with compute capability {compute_cap}.\",\n)\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"compute_type\",\n [ComputeType.FORWARD, ComputeType.BACKWARD],\n ids=lambda t: t.name,\n)\n@pytest.mark.parametrize(\n \"parallelism\",\n [Parallelism.TENSOR_PARALLEL, Parallelism.SEQUENCE_PARALLEL],\n ids=lambda p: p.name,\n)\n@pytest.mark.parametrize(\n \"overlap\",\n [\n pytest.param(False, id=\"nonoverlap\"),\n pytest.param(\n True,\n id=\"overlap\",\n marks=pytest.mark.skip(\n reason=\"`RuntimeError: /workspace/TransformerEngine/transformer_engine/common/comm_gemm_overlap/userbuffers/userbuffers-host.cpp:321 in function create_communicator_grouped2: CUDA Error: invalid argument` in jit_python_distributed_tests_20_H100_TNVF\"\n ),\n ),\n ],\n)\ndef test_transformer_layer(\n setup_default_process_group,\n monkeypatch,\n benchmark,\n compute_type: ComputeType,\n parallelism: Parallelism,\n overlap: bool,\n):\n if overlap and parallelism == Parallelism.TENSOR_PARALLEL:\n pytest.skip(\"Tensor parallelism doesn't support overlapping.\")\n\n # Hyperparameters for GPT-3\n hidden_size = 12288\n num_heads = 96\n ffn_hidden_size = hidden_size * 4\n batch_size = 1\n sequence_length = 2048\n dtype = torch.bfloat16\n\n size = dist.get_world_size()\n\n transformer_layer = te.TransformerLayer(\n hidden_size,\n ffn_hidden_size,\n num_heads,\n # According to https://github.com/NVIDIA/TransformerEngine/issues/1350,\n # `attn_input_format` has to match the format of `transformer_layer`'s\n # input.\n attn_input_format=\"bshd\",\n set_parallel_mode=True,\n sequence_parallel=(parallelism == Parallelism.SEQUENCE_PARALLEL),\n ub_tp_comm_overlap=overlap,\n tp_group=dist.group.WORLD,\n )\n transformer_layer.to(dtype).to(\"cuda\")\n\n match parallelism:\n case Parallelism.TENSOR_PARALLEL:\n local_sequence_length = sequence_length\n case Parallelism.SEQUENCE_PARALLEL:\n assert sequence_length % size == 0\n local_sequence_length = sequence_length // size\n\n x = torch.randn(\n batch_size, local_sequence_length, hidden_size, dtype=dtype, device=\"cuda\"\n )\n\n if overlap:\n # Similar to https://github.com/NVIDIA/TransformerEngine/blob/e7bfc0c547d63332e4f8d65e606dc69f4c22ffbe/examples/pytorch/comm_gemm_overlap/te_layer_with_overlap.py#L27-L29\n monkeypatch.setenv(\"CUDA_DEVICE_MAX_CONNECTIONS\", \"1\")\n if not te.cpp_extensions.device_supports_multicast():\n monkeypatch.setenv(\"UB_SKIPMC\", \"1\")\n\n te.module.base.initialize_ub(\n # Instructed by https://github.com/NVIDIA/TransformerEngine/blob/e7bfc0c547d63332e4f8d65e606dc69f4c22ffbe/transformer_engine/pytorch/module/base.py#L96-L99\n [batch_size * sequence_length, hidden_size],\n size,\n dtype=dtype,\n bootstrap_backend=\"nccl\",\n )\n\n match compute_type:\n case ComputeType.FORWARD:\n warmup_fn, benchmark_fn = get_benchmark_fns(lambda: transformer_layer(x))\n y = warmup_fn()\n assert y.size() == torch.Size(\n [batch_size, local_sequence_length, hidden_size]\n )\n\n benchmark.pedantic(benchmark_fn, rounds=5)\n case ComputeType.BACKWARD:\n # Due to https://github.com/NVIDIA/TransformerEngine/issues/990, we can't repeatedly call\n # torch.autograd.backward to benchmark just backprop. As a\n # workaround, the code below runs forward before each backprop but\n # only measure the backprop time.\n def setup_fn():\n y = transformer_layer(x)\n dy = torch.rand_like(y)\n torch.cuda.synchronize()\n return (y, dy), {}\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda y, dy: torch.autograd.backward(y, dy)\n )\n\n args, kwargs = setup_fn()\n warmup_fn(*args, **kwargs)\n\n benchmark.pedantic(\n benchmark_fn,\n setup=setup_fn,\n rounds=5,\n )\n\n if overlap:\n te.module.base.destroy_ub()","source_hash":"baf4662712370a08ab2860526c8d7afa900f8c786166f9672547d388ed4cb7c2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer_engine.ComputeType","uri":"program://Fuser/class/tests.python.multidevice.test_transformer_engine.ComputeType#L19-L21","kind":"class","name":"ComputeType","path":"tests/python/multidevice/test_transformer_engine.py","language":"python","start_line":19,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\nimport torch.distributed as dist\n\nimport transformer_engine.pytorch as te\n\nfrom . import Parallelism\nfrom .benchmark_utils import get_benchmark_fns\nfrom enum import auto, Enum\n\ncompute_cap = torch.cuda.get_device_capability()\n\n\nclass ComputeType(Enum):\n FORWARD = auto()\n BACKWARD = auto()\n\n\n# This benchmark is instrumented with cudaProfilerStart/Stop. Therefore, one\n# can collect stats of the first few non-warmup benchmark iterations using\n# ```bash\n# mpirun -np nsys profile --capture-range=cudaProfilerApi --capture-range-end=repeat: pytest tests/python/test_transformer_engine.py -k --only-mpi\n# ```\n# and then display the status using e.g. `nsys stats --report=cuda_gpu_kern_sum report1.nsys-rep`.\n@pytest.mark.skipif(\n compute_cap >= (10, 0) and compute_cap < (12, 0),\n reason=f\"TransformerEngine stalls this test on devices with compute capability {compute_cap}.\",\n)\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"compute_type\",\n [ComputeType.FORWARD, ComputeType.BACKWARD],\n ids=lambda t: t.name,\n)\n@pytest.mark.parametrize(\n \"parallelism\",","source_hash":"baf4662712370a08ab2860526c8d7afa900f8c786166f9672547d388ed4cb7c2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer_engine.test_transformer_layer","uri":"program://Fuser/function/tests.python.multidevice.test_transformer_engine.test_transformer_layer#L58-L153","kind":"function","name":"test_transformer_layer","path":"tests/python/multidevice/test_transformer_engine.py","language":"python","start_line":58,"end_line":153,"context_start_line":38,"context_end_line":153,"code":" ids=lambda t: t.name,\n)\n@pytest.mark.parametrize(\n \"parallelism\",\n [Parallelism.TENSOR_PARALLEL, Parallelism.SEQUENCE_PARALLEL],\n ids=lambda p: p.name,\n)\n@pytest.mark.parametrize(\n \"overlap\",\n [\n pytest.param(False, id=\"nonoverlap\"),\n pytest.param(\n True,\n id=\"overlap\",\n marks=pytest.mark.skip(\n reason=\"`RuntimeError: /workspace/TransformerEngine/transformer_engine/common/comm_gemm_overlap/userbuffers/userbuffers-host.cpp:321 in function create_communicator_grouped2: CUDA Error: invalid argument` in jit_python_distributed_tests_20_H100_TNVF\"\n ),\n ),\n ],\n)\ndef test_transformer_layer(\n setup_default_process_group,\n monkeypatch,\n benchmark,\n compute_type: ComputeType,\n parallelism: Parallelism,\n overlap: bool,\n):\n if overlap and parallelism == Parallelism.TENSOR_PARALLEL:\n pytest.skip(\"Tensor parallelism doesn't support overlapping.\")\n\n # Hyperparameters for GPT-3\n hidden_size = 12288\n num_heads = 96\n ffn_hidden_size = hidden_size * 4\n batch_size = 1\n sequence_length = 2048\n dtype = torch.bfloat16\n\n size = dist.get_world_size()\n\n transformer_layer = te.TransformerLayer(\n hidden_size,\n ffn_hidden_size,\n num_heads,\n # According to https://github.com/NVIDIA/TransformerEngine/issues/1350,\n # `attn_input_format` has to match the format of `transformer_layer`'s\n # input.\n attn_input_format=\"bshd\",\n set_parallel_mode=True,\n sequence_parallel=(parallelism == Parallelism.SEQUENCE_PARALLEL),\n ub_tp_comm_overlap=overlap,\n tp_group=dist.group.WORLD,\n )\n transformer_layer.to(dtype).to(\"cuda\")\n\n match parallelism:\n case Parallelism.TENSOR_PARALLEL:\n local_sequence_length = sequence_length\n case Parallelism.SEQUENCE_PARALLEL:\n assert sequence_length % size == 0\n local_sequence_length = sequence_length // size\n\n x = torch.randn(\n batch_size, local_sequence_length, hidden_size, dtype=dtype, device=\"cuda\"\n )\n\n if overlap:\n # Similar to https://github.com/NVIDIA/TransformerEngine/blob/e7bfc0c547d63332e4f8d65e606dc69f4c22ffbe/examples/pytorch/comm_gemm_overlap/te_layer_with_overlap.py#L27-L29\n monkeypatch.setenv(\"CUDA_DEVICE_MAX_CONNECTIONS\", \"1\")\n if not te.cpp_extensions.device_supports_multicast():\n monkeypatch.setenv(\"UB_SKIPMC\", \"1\")\n\n te.module.base.initialize_ub(\n # Instructed by https://github.com/NVIDIA/TransformerEngine/blob/e7bfc0c547d63332e4f8d65e606dc69f4c22ffbe/transformer_engine/pytorch/module/base.py#L96-L99\n [batch_size * sequence_length, hidden_size],\n size,\n dtype=dtype,\n bootstrap_backend=\"nccl\",\n )\n\n match compute_type:\n case ComputeType.FORWARD:\n warmup_fn, benchmark_fn = get_benchmark_fns(lambda: transformer_layer(x))\n y = warmup_fn()\n assert y.size() == torch.Size(\n [batch_size, local_sequence_length, hidden_size]\n )\n\n benchmark.pedantic(benchmark_fn, rounds=5)\n case ComputeType.BACKWARD:\n # Due to https://github.com/NVIDIA/TransformerEngine/issues/990, we can't repeatedly call\n # torch.autograd.backward to benchmark just backprop. As a\n # workaround, the code below runs forward before each backprop but\n # only measure the backprop time.\n def setup_fn():\n y = transformer_layer(x)\n dy = torch.rand_like(y)\n torch.cuda.synchronize()\n return (y, dy), {}\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda y, dy: torch.autograd.backward(y, dy)\n )\n\n args, kwargs = setup_fn()\n warmup_fn(*args, **kwargs)\n\n benchmark.pedantic(\n benchmark_fn,\n setup=setup_fn,\n rounds=5,\n )\n\n if overlap:\n te.module.base.destroy_ub()","source_hash":"baf4662712370a08ab2860526c8d7afa900f8c786166f9672547d388ed4cb7c2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer_engine.setup_fn","uri":"program://Fuser/function/tests.python.multidevice.test_transformer_engine.setup_fn#L133-L137","kind":"function","name":"setup_fn","path":"tests/python/multidevice/test_transformer_engine.py","language":"python","start_line":133,"end_line":137,"context_start_line":113,"context_end_line":153,"code":" [batch_size * sequence_length, hidden_size],\n size,\n dtype=dtype,\n bootstrap_backend=\"nccl\",\n )\n\n match compute_type:\n case ComputeType.FORWARD:\n warmup_fn, benchmark_fn = get_benchmark_fns(lambda: transformer_layer(x))\n y = warmup_fn()\n assert y.size() == torch.Size(\n [batch_size, local_sequence_length, hidden_size]\n )\n\n benchmark.pedantic(benchmark_fn, rounds=5)\n case ComputeType.BACKWARD:\n # Due to https://github.com/NVIDIA/TransformerEngine/issues/990, we can't repeatedly call\n # torch.autograd.backward to benchmark just backprop. As a\n # workaround, the code below runs forward before each backprop but\n # only measure the backprop time.\n def setup_fn():\n y = transformer_layer(x)\n dy = torch.rand_like(y)\n torch.cuda.synchronize()\n return (y, dy), {}\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda y, dy: torch.autograd.backward(y, dy)\n )\n\n args, kwargs = setup_fn()\n warmup_fn(*args, **kwargs)\n\n benchmark.pedantic(\n benchmark_fn,\n setup=setup_fn,\n rounds=5,\n )\n\n if overlap:\n te.module.base.destroy_ub()","source_hash":"baf4662712370a08ab2860526c8d7afa900f8c786166f9672547d388ed4cb7c2","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.fusion_definition_wrapper","uri":"program://Fuser/module/tests.python.multidevice.fusion_definition_wrapper#L1-L70","kind":"module","name":"tests.python.multidevice.fusion_definition_wrapper","path":"tests/python/multidevice/fusion_definition_wrapper.py","language":"python","start_line":1,"end_line":70,"context_start_line":1,"context_end_line":70,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition\nfrom collections.abc import Iterable\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement, Shard\nfrom typing import Callable, cast, TypeAlias\n\n\nDTensorsKey: TypeAlias = tuple[tuple[str, str], ...]\n\n\ndef make_key_from_dtensors(dtensors: Iterable[DTensor]) -> DTensorsKey:\n key = tuple((repr(dt.device_mesh), repr(dt.placements)) for dt in dtensors)\n return key\n\n\nclass FusionDefinitionWrapper:\n def __init__(self, define_fusion: Callable):\n \"\"\"Wraps a function that defines a fusion without `multidevice_schedule`.\"\"\"\n # The complete FusionDefinition (w/ multidevice_scheduler) will have to\n # be created at \"call\" time according to the input DTensors.\n self._define_fusion = define_fusion\n\n # TODO: In theory, a FusionDefinitionWrapper can own multiple\n # `FusionDefinition`s, because different shardings lead to different\n # `multidevice_schedule`s. Currently, cache FusionDefinition based on input DTensors.\n self._fusion_definition_cache: dict[DTensorsKey, FusionDefinition] = {}\n\n def _create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n with FusionDefinition() as fd:\n self._define_fusion(fd)\n self._multidevice_schedule(fd, in_dtensors)\n return fd\n\n def _multidevice_schedule(\n self, fd: FusionDefinition, in_dtensors: Iterable[DTensor]\n ) -> None:\n for in_tv, in_dtensor in zip(fd.fusion.inputs(), in_dtensors):\n mesh = nvfuser.multidevice.DeviceMesh(in_dtensor.device_mesh.mesh)\n\n in_tv.set_device_mesh(mesh)\n\n assert len(in_dtensor.placements) == 1, \"Expect a 1D mesh\"\n\n # Split and parallelize.\n # When the mesh is multi-dimensional, iterate through the\n # placements in descending order of Placement.dim.\n placement: Placement = in_dtensor.placements[0]\n if placement.is_shard():\n dim = cast(Shard, placement).dim\n in_tv.outer_split(dim, mesh.size)\n in_tv.axis(dim).parallelize(nvfuser.ParallelType.mesh_x)\n\n def _get_or_create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n key = make_key_from_dtensors(in_dtensors)\n return self._fusion_definition_cache.setdefault(\n key, (lambda: self._create_fusion_definition(in_dtensors))()\n )\n\n def __call__(self, in_dtensors: Iterable[DTensor]) -> list[DTensor]:\n fusion_def = self._get_or_create_fusion_definition(in_dtensors)\n return nvfuser.execute_with_dtensors(fusion_def, in_dtensors)","source_hash":"61b827a798d6b0cf667f2c05d9d6e6be3722edd48ed5056cb6c7a3ed1ef68718","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.fusion_definition_wrapper.make_key_from_dtensors","uri":"program://Fuser/function/tests.python.multidevice.fusion_definition_wrapper.make_key_from_dtensors#L16-L18","kind":"function","name":"make_key_from_dtensors","path":"tests/python/multidevice/fusion_definition_wrapper.py","language":"python","start_line":16,"end_line":18,"context_start_line":1,"context_end_line":38,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition\nfrom collections.abc import Iterable\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement, Shard\nfrom typing import Callable, cast, TypeAlias\n\n\nDTensorsKey: TypeAlias = tuple[tuple[str, str], ...]\n\n\ndef make_key_from_dtensors(dtensors: Iterable[DTensor]) -> DTensorsKey:\n key = tuple((repr(dt.device_mesh), repr(dt.placements)) for dt in dtensors)\n return key\n\n\nclass FusionDefinitionWrapper:\n def __init__(self, define_fusion: Callable):\n \"\"\"Wraps a function that defines a fusion without `multidevice_schedule`.\"\"\"\n # The complete FusionDefinition (w/ multidevice_scheduler) will have to\n # be created at \"call\" time according to the input DTensors.\n self._define_fusion = define_fusion\n\n # TODO: In theory, a FusionDefinitionWrapper can own multiple\n # `FusionDefinition`s, because different shardings lead to different\n # `multidevice_schedule`s. Currently, cache FusionDefinition based on input DTensors.\n self._fusion_definition_cache: dict[DTensorsKey, FusionDefinition] = {}\n\n def _create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n with FusionDefinition() as fd:\n self._define_fusion(fd)\n self._multidevice_schedule(fd, in_dtensors)","source_hash":"61b827a798d6b0cf667f2c05d9d6e6be3722edd48ed5056cb6c7a3ed1ef68718","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.fusion_definition_wrapper.FusionDefinitionWrapper","uri":"program://Fuser/class/tests.python.multidevice.fusion_definition_wrapper.FusionDefinitionWrapper#L21-L70","kind":"class","name":"FusionDefinitionWrapper","path":"tests/python/multidevice/fusion_definition_wrapper.py","language":"python","start_line":21,"end_line":70,"context_start_line":1,"context_end_line":70,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition\nfrom collections.abc import Iterable\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement, Shard\nfrom typing import Callable, cast, TypeAlias\n\n\nDTensorsKey: TypeAlias = tuple[tuple[str, str], ...]\n\n\ndef make_key_from_dtensors(dtensors: Iterable[DTensor]) -> DTensorsKey:\n key = tuple((repr(dt.device_mesh), repr(dt.placements)) for dt in dtensors)\n return key\n\n\nclass FusionDefinitionWrapper:\n def __init__(self, define_fusion: Callable):\n \"\"\"Wraps a function that defines a fusion without `multidevice_schedule`.\"\"\"\n # The complete FusionDefinition (w/ multidevice_scheduler) will have to\n # be created at \"call\" time according to the input DTensors.\n self._define_fusion = define_fusion\n\n # TODO: In theory, a FusionDefinitionWrapper can own multiple\n # `FusionDefinition`s, because different shardings lead to different\n # `multidevice_schedule`s. Currently, cache FusionDefinition based on input DTensors.\n self._fusion_definition_cache: dict[DTensorsKey, FusionDefinition] = {}\n\n def _create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n with FusionDefinition() as fd:\n self._define_fusion(fd)\n self._multidevice_schedule(fd, in_dtensors)\n return fd\n\n def _multidevice_schedule(\n self, fd: FusionDefinition, in_dtensors: Iterable[DTensor]\n ) -> None:\n for in_tv, in_dtensor in zip(fd.fusion.inputs(), in_dtensors):\n mesh = nvfuser.multidevice.DeviceMesh(in_dtensor.device_mesh.mesh)\n\n in_tv.set_device_mesh(mesh)\n\n assert len(in_dtensor.placements) == 1, \"Expect a 1D mesh\"\n\n # Split and parallelize.\n # When the mesh is multi-dimensional, iterate through the\n # placements in descending order of Placement.dim.\n placement: Placement = in_dtensor.placements[0]\n if placement.is_shard():\n dim = cast(Shard, placement).dim\n in_tv.outer_split(dim, mesh.size)\n in_tv.axis(dim).parallelize(nvfuser.ParallelType.mesh_x)\n\n def _get_or_create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n key = make_key_from_dtensors(in_dtensors)\n return self._fusion_definition_cache.setdefault(\n key, (lambda: self._create_fusion_definition(in_dtensors))()\n )\n\n def __call__(self, in_dtensors: Iterable[DTensor]) -> list[DTensor]:\n fusion_def = self._get_or_create_fusion_definition(in_dtensors)\n return nvfuser.execute_with_dtensors(fusion_def, in_dtensors)","source_hash":"61b827a798d6b0cf667f2c05d9d6e6be3722edd48ed5056cb6c7a3ed1ef68718","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.fusion_definition_wrapper.__init__","uri":"program://Fuser/function/tests.python.multidevice.fusion_definition_wrapper.__init__#L22-L31","kind":"function","name":"__init__","path":"tests/python/multidevice/fusion_definition_wrapper.py","language":"python","start_line":22,"end_line":31,"context_start_line":2,"context_end_line":51,"code":"# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition\nfrom collections.abc import Iterable\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement, Shard\nfrom typing import Callable, cast, TypeAlias\n\n\nDTensorsKey: TypeAlias = tuple[tuple[str, str], ...]\n\n\ndef make_key_from_dtensors(dtensors: Iterable[DTensor]) -> DTensorsKey:\n key = tuple((repr(dt.device_mesh), repr(dt.placements)) for dt in dtensors)\n return key\n\n\nclass FusionDefinitionWrapper:\n def __init__(self, define_fusion: Callable):\n \"\"\"Wraps a function that defines a fusion without `multidevice_schedule`.\"\"\"\n # The complete FusionDefinition (w/ multidevice_scheduler) will have to\n # be created at \"call\" time according to the input DTensors.\n self._define_fusion = define_fusion\n\n # TODO: In theory, a FusionDefinitionWrapper can own multiple\n # `FusionDefinition`s, because different shardings lead to different\n # `multidevice_schedule`s. Currently, cache FusionDefinition based on input DTensors.\n self._fusion_definition_cache: dict[DTensorsKey, FusionDefinition] = {}\n\n def _create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n with FusionDefinition() as fd:\n self._define_fusion(fd)\n self._multidevice_schedule(fd, in_dtensors)\n return fd\n\n def _multidevice_schedule(\n self, fd: FusionDefinition, in_dtensors: Iterable[DTensor]\n ) -> None:\n for in_tv, in_dtensor in zip(fd.fusion.inputs(), in_dtensors):\n mesh = nvfuser.multidevice.DeviceMesh(in_dtensor.device_mesh.mesh)\n\n in_tv.set_device_mesh(mesh)\n\n assert len(in_dtensor.placements) == 1, \"Expect a 1D mesh\"\n\n # Split and parallelize.","source_hash":"61b827a798d6b0cf667f2c05d9d6e6be3722edd48ed5056cb6c7a3ed1ef68718","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.fusion_definition_wrapper._create_fusion_definition","uri":"program://Fuser/function/tests.python.multidevice.fusion_definition_wrapper._create_fusion_definition#L33-L39","kind":"function","name":"_create_fusion_definition","path":"tests/python/multidevice/fusion_definition_wrapper.py","language":"python","start_line":33,"end_line":39,"context_start_line":13,"context_end_line":59,"code":"DTensorsKey: TypeAlias = tuple[tuple[str, str], ...]\n\n\ndef make_key_from_dtensors(dtensors: Iterable[DTensor]) -> DTensorsKey:\n key = tuple((repr(dt.device_mesh), repr(dt.placements)) for dt in dtensors)\n return key\n\n\nclass FusionDefinitionWrapper:\n def __init__(self, define_fusion: Callable):\n \"\"\"Wraps a function that defines a fusion without `multidevice_schedule`.\"\"\"\n # The complete FusionDefinition (w/ multidevice_scheduler) will have to\n # be created at \"call\" time according to the input DTensors.\n self._define_fusion = define_fusion\n\n # TODO: In theory, a FusionDefinitionWrapper can own multiple\n # `FusionDefinition`s, because different shardings lead to different\n # `multidevice_schedule`s. Currently, cache FusionDefinition based on input DTensors.\n self._fusion_definition_cache: dict[DTensorsKey, FusionDefinition] = {}\n\n def _create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n with FusionDefinition() as fd:\n self._define_fusion(fd)\n self._multidevice_schedule(fd, in_dtensors)\n return fd\n\n def _multidevice_schedule(\n self, fd: FusionDefinition, in_dtensors: Iterable[DTensor]\n ) -> None:\n for in_tv, in_dtensor in zip(fd.fusion.inputs(), in_dtensors):\n mesh = nvfuser.multidevice.DeviceMesh(in_dtensor.device_mesh.mesh)\n\n in_tv.set_device_mesh(mesh)\n\n assert len(in_dtensor.placements) == 1, \"Expect a 1D mesh\"\n\n # Split and parallelize.\n # When the mesh is multi-dimensional, iterate through the\n # placements in descending order of Placement.dim.\n placement: Placement = in_dtensor.placements[0]\n if placement.is_shard():\n dim = cast(Shard, placement).dim\n in_tv.outer_split(dim, mesh.size)\n in_tv.axis(dim).parallelize(nvfuser.ParallelType.mesh_x)\n","source_hash":"61b827a798d6b0cf667f2c05d9d6e6be3722edd48ed5056cb6c7a3ed1ef68718","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.fusion_definition_wrapper._multidevice_schedule","uri":"program://Fuser/function/tests.python.multidevice.fusion_definition_wrapper._multidevice_schedule#L41-L58","kind":"function","name":"_multidevice_schedule","path":"tests/python/multidevice/fusion_definition_wrapper.py","language":"python","start_line":41,"end_line":58,"context_start_line":21,"context_end_line":70,"code":"class FusionDefinitionWrapper:\n def __init__(self, define_fusion: Callable):\n \"\"\"Wraps a function that defines a fusion without `multidevice_schedule`.\"\"\"\n # The complete FusionDefinition (w/ multidevice_scheduler) will have to\n # be created at \"call\" time according to the input DTensors.\n self._define_fusion = define_fusion\n\n # TODO: In theory, a FusionDefinitionWrapper can own multiple\n # `FusionDefinition`s, because different shardings lead to different\n # `multidevice_schedule`s. Currently, cache FusionDefinition based on input DTensors.\n self._fusion_definition_cache: dict[DTensorsKey, FusionDefinition] = {}\n\n def _create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n with FusionDefinition() as fd:\n self._define_fusion(fd)\n self._multidevice_schedule(fd, in_dtensors)\n return fd\n\n def _multidevice_schedule(\n self, fd: FusionDefinition, in_dtensors: Iterable[DTensor]\n ) -> None:\n for in_tv, in_dtensor in zip(fd.fusion.inputs(), in_dtensors):\n mesh = nvfuser.multidevice.DeviceMesh(in_dtensor.device_mesh.mesh)\n\n in_tv.set_device_mesh(mesh)\n\n assert len(in_dtensor.placements) == 1, \"Expect a 1D mesh\"\n\n # Split and parallelize.\n # When the mesh is multi-dimensional, iterate through the\n # placements in descending order of Placement.dim.\n placement: Placement = in_dtensor.placements[0]\n if placement.is_shard():\n dim = cast(Shard, placement).dim\n in_tv.outer_split(dim, mesh.size)\n in_tv.axis(dim).parallelize(nvfuser.ParallelType.mesh_x)\n\n def _get_or_create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n key = make_key_from_dtensors(in_dtensors)\n return self._fusion_definition_cache.setdefault(\n key, (lambda: self._create_fusion_definition(in_dtensors))()\n )\n\n def __call__(self, in_dtensors: Iterable[DTensor]) -> list[DTensor]:\n fusion_def = self._get_or_create_fusion_definition(in_dtensors)\n return nvfuser.execute_with_dtensors(fusion_def, in_dtensors)","source_hash":"61b827a798d6b0cf667f2c05d9d6e6be3722edd48ed5056cb6c7a3ed1ef68718","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.fusion_definition_wrapper._get_or_create_fusion_definition","uri":"program://Fuser/function/tests.python.multidevice.fusion_definition_wrapper._get_or_create_fusion_definition#L60-L66","kind":"function","name":"_get_or_create_fusion_definition","path":"tests/python/multidevice/fusion_definition_wrapper.py","language":"python","start_line":60,"end_line":66,"context_start_line":40,"context_end_line":70,"code":"\n def _multidevice_schedule(\n self, fd: FusionDefinition, in_dtensors: Iterable[DTensor]\n ) -> None:\n for in_tv, in_dtensor in zip(fd.fusion.inputs(), in_dtensors):\n mesh = nvfuser.multidevice.DeviceMesh(in_dtensor.device_mesh.mesh)\n\n in_tv.set_device_mesh(mesh)\n\n assert len(in_dtensor.placements) == 1, \"Expect a 1D mesh\"\n\n # Split and parallelize.\n # When the mesh is multi-dimensional, iterate through the\n # placements in descending order of Placement.dim.\n placement: Placement = in_dtensor.placements[0]\n if placement.is_shard():\n dim = cast(Shard, placement).dim\n in_tv.outer_split(dim, mesh.size)\n in_tv.axis(dim).parallelize(nvfuser.ParallelType.mesh_x)\n\n def _get_or_create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n key = make_key_from_dtensors(in_dtensors)\n return self._fusion_definition_cache.setdefault(\n key, (lambda: self._create_fusion_definition(in_dtensors))()\n )\n\n def __call__(self, in_dtensors: Iterable[DTensor]) -> list[DTensor]:\n fusion_def = self._get_or_create_fusion_definition(in_dtensors)\n return nvfuser.execute_with_dtensors(fusion_def, in_dtensors)","source_hash":"61b827a798d6b0cf667f2c05d9d6e6be3722edd48ed5056cb6c7a3ed1ef68718","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.fusion_definition_wrapper.__call__","uri":"program://Fuser/function/tests.python.multidevice.fusion_definition_wrapper.__call__#L68-L70","kind":"function","name":"__call__","path":"tests/python/multidevice/fusion_definition_wrapper.py","language":"python","start_line":68,"end_line":70,"context_start_line":48,"context_end_line":70,"code":"\n assert len(in_dtensor.placements) == 1, \"Expect a 1D mesh\"\n\n # Split and parallelize.\n # When the mesh is multi-dimensional, iterate through the\n # placements in descending order of Placement.dim.\n placement: Placement = in_dtensor.placements[0]\n if placement.is_shard():\n dim = cast(Shard, placement).dim\n in_tv.outer_split(dim, mesh.size)\n in_tv.axis(dim).parallelize(nvfuser.ParallelType.mesh_x)\n\n def _get_or_create_fusion_definition(\n self, in_dtensors: Iterable[DTensor]\n ) -> FusionDefinition:\n key = make_key_from_dtensors(in_dtensors)\n return self._fusion_definition_cache.setdefault(\n key, (lambda: self._create_fusion_definition(in_dtensors))()\n )\n\n def __call__(self, in_dtensors: Iterable[DTensor]) -> list[DTensor]:\n fusion_def = self._get_or_create_fusion_definition(in_dtensors)\n return nvfuser.execute_with_dtensors(fusion_def, in_dtensors)","source_hash":"61b827a798d6b0cf667f2c05d9d6e6be3722edd48ed5056cb6c7a3ed1ef68718","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_dtensor","uri":"program://Fuser/module/tests.python.multidevice.test_dtensor#L1-L117","kind":"module","name":"tests.python.multidevice.test_dtensor","path":"tests/python/multidevice/test_dtensor.py","language":"python","start_line":1,"end_line":117,"context_start_line":1,"context_end_line":117,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\nimport torch.distributed as dist\n\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Shard, Replicate\nfrom .fusion_definition_wrapper import FusionDefinitionWrapper\nfrom .linear import LinearFunction\nfrom nvfuser_direct import FusionDefinition, DataType\n\n\n@pytest.mark.mpi\ndef test_plus_one(setup_default_process_group, multidevice_test):\n def define_fusion(fd: FusionDefinition):\n inp = fd.define_tensor((-1, -1), contiguity=False, dtype=DataType.Float)\n one = fd.define_scalar(1.0, dtype=DataType.Float)\n out = fd.ops.add(inp, one)\n fd.add_output(out)\n\n op = FusionDefinitionWrapper(define_fusion)\n\n num_devices = dist.get_world_size()\n\n in_tensor = torch.randn(num_devices, 4)\n mesh = dist.device_mesh.init_device_mesh(\n \"cuda\", [num_devices], mesh_dim_names=[\"tp\"]\n )\n in_dtensor = dist.tensor.distribute_tensor(in_tensor, mesh, [Shard(0)])\n\n (out_dtensor,) = op([in_dtensor])\n torch.testing.assert_close(out_dtensor.to_local(), in_dtensor.to_local() + 1)\n assert out_dtensor.device_mesh == in_dtensor.device_mesh\n assert out_dtensor.placements == in_dtensor.placements\n assert (\n out_dtensor.device_mesh.mesh_dim_names == in_dtensor.device_mesh.mesh_dim_names\n )\n\n\n@pytest.mark.mpi\ndef test_column_parallel_linear(setup_default_process_group, multidevice_test):\n d, b, s, e = dist.get_world_size(), 2, 3, 5\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n inp_tensor = torch.randint(\n -4, 4, (b, s, e), dtype=torch.bfloat16, requires_grad=True\n )\n weight_tensor = torch.randint(\n -4, 4, (d * e, e), dtype=torch.bfloat16, requires_grad=True\n )\n\n inp_dtensor = dist.tensor.distribute_tensor(inp_tensor, mesh, [Replicate()])\n weight_dtensor = dist.tensor.distribute_tensor(weight_tensor, mesh, [Shard(0)])\n\n def assert_close(expected_tensor: torch.Tensor, dtensor: DTensor):\n torch.testing.assert_close(expected_tensor, dtensor.to_local().cpu())\n\n out_tensor = torch.nn.functional.linear(inp_tensor, weight_tensor)\n out_dtensor = LinearFunction.apply(inp_dtensor, weight_dtensor)\n rank = dist.get_rank()\n assert_close(out_tensor.split(e, dim=-1)[rank], out_dtensor)\n\n (expected_grad_x, expected_grad_w) = torch.autograd.grad(\n out_tensor,\n (inp_tensor, weight_tensor),\n torch.ones_like(out_tensor),\n )\n (grad_x, grad_w) = torch.autograd.grad(\n out_dtensor,\n (inp_dtensor, weight_dtensor),\n torch.ones_like(out_dtensor),\n )\n assert_close(expected_grad_x, grad_x)\n assert_close(expected_grad_w.split(e, dim=0)[rank], grad_w)\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear(setup_default_process_group, multidevice_test):\n d, b, s, e = dist.get_world_size(), 2, 3, 5\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n inp_tensor = torch.randint(\n -4, 4, (b, s, d * e), dtype=torch.bfloat16, requires_grad=True\n )\n weight_tensor = torch.randint(\n -4, 4, (e, d * e), dtype=torch.bfloat16, requires_grad=True\n )\n\n inp_dtensor = dist.tensor.distribute_tensor(inp_tensor, mesh, [Shard(-1)])\n weight_dtensor = dist.tensor.distribute_tensor(weight_tensor, mesh, [Shard(-1)])\n\n def assert_close(expected_tensor: torch.Tensor, dtensor: DTensor):\n torch.testing.assert_close(expected_tensor, dtensor.to_local().cpu())\n\n out_tensor = torch.nn.functional.linear(inp_tensor, weight_tensor)\n out_dtensor = LinearFunction.apply(inp_dtensor, weight_dtensor)\n assert_close(out_tensor, out_dtensor)\n\n (expected_grad_x, expected_grad_w) = torch.autograd.grad(\n out_tensor,\n (inp_tensor, weight_tensor),\n torch.ones_like(out_tensor),\n )\n (grad_x, grad_w) = torch.autograd.grad(\n out_dtensor,\n (inp_dtensor, weight_dtensor),\n torch.ones_like(out_dtensor),\n )\n rank = dist.get_rank()\n assert_close(expected_grad_x.split(e, dim=-1)[rank], grad_x)\n assert_close(expected_grad_w.split(e, dim=-1)[rank], grad_w)","source_hash":"77cb69829bfffaac4c646fcf958581e665e5cdcc48efe90791f4ba20d43efa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_dtensor.test_plus_one","uri":"program://Fuser/function/tests.python.multidevice.test_dtensor.test_plus_one#L18-L41","kind":"function","name":"test_plus_one","path":"tests/python/multidevice/test_dtensor.py","language":"python","start_line":18,"end_line":41,"context_start_line":1,"context_end_line":61,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\nimport torch.distributed as dist\n\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Shard, Replicate\nfrom .fusion_definition_wrapper import FusionDefinitionWrapper\nfrom .linear import LinearFunction\nfrom nvfuser_direct import FusionDefinition, DataType\n\n\n@pytest.mark.mpi\ndef test_plus_one(setup_default_process_group, multidevice_test):\n def define_fusion(fd: FusionDefinition):\n inp = fd.define_tensor((-1, -1), contiguity=False, dtype=DataType.Float)\n one = fd.define_scalar(1.0, dtype=DataType.Float)\n out = fd.ops.add(inp, one)\n fd.add_output(out)\n\n op = FusionDefinitionWrapper(define_fusion)\n\n num_devices = dist.get_world_size()\n\n in_tensor = torch.randn(num_devices, 4)\n mesh = dist.device_mesh.init_device_mesh(\n \"cuda\", [num_devices], mesh_dim_names=[\"tp\"]\n )\n in_dtensor = dist.tensor.distribute_tensor(in_tensor, mesh, [Shard(0)])\n\n (out_dtensor,) = op([in_dtensor])\n torch.testing.assert_close(out_dtensor.to_local(), in_dtensor.to_local() + 1)\n assert out_dtensor.device_mesh == in_dtensor.device_mesh\n assert out_dtensor.placements == in_dtensor.placements\n assert (\n out_dtensor.device_mesh.mesh_dim_names == in_dtensor.device_mesh.mesh_dim_names\n )\n\n\n@pytest.mark.mpi\ndef test_column_parallel_linear(setup_default_process_group, multidevice_test):\n d, b, s, e = dist.get_world_size(), 2, 3, 5\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n inp_tensor = torch.randint(\n -4, 4, (b, s, e), dtype=torch.bfloat16, requires_grad=True\n )\n weight_tensor = torch.randint(\n -4, 4, (d * e, e), dtype=torch.bfloat16, requires_grad=True\n )\n\n inp_dtensor = dist.tensor.distribute_tensor(inp_tensor, mesh, [Replicate()])\n weight_dtensor = dist.tensor.distribute_tensor(weight_tensor, mesh, [Shard(0)])\n\n def assert_close(expected_tensor: torch.Tensor, dtensor: DTensor):\n torch.testing.assert_close(expected_tensor, dtensor.to_local().cpu())","source_hash":"77cb69829bfffaac4c646fcf958581e665e5cdcc48efe90791f4ba20d43efa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_dtensor.test_column_parallel_linear","uri":"program://Fuser/function/tests.python.multidevice.test_dtensor.test_column_parallel_linear#L45-L79","kind":"function","name":"test_column_parallel_linear","path":"tests/python/multidevice/test_dtensor.py","language":"python","start_line":45,"end_line":79,"context_start_line":25,"context_end_line":99,"code":" op = FusionDefinitionWrapper(define_fusion)\n\n num_devices = dist.get_world_size()\n\n in_tensor = torch.randn(num_devices, 4)\n mesh = dist.device_mesh.init_device_mesh(\n \"cuda\", [num_devices], mesh_dim_names=[\"tp\"]\n )\n in_dtensor = dist.tensor.distribute_tensor(in_tensor, mesh, [Shard(0)])\n\n (out_dtensor,) = op([in_dtensor])\n torch.testing.assert_close(out_dtensor.to_local(), in_dtensor.to_local() + 1)\n assert out_dtensor.device_mesh == in_dtensor.device_mesh\n assert out_dtensor.placements == in_dtensor.placements\n assert (\n out_dtensor.device_mesh.mesh_dim_names == in_dtensor.device_mesh.mesh_dim_names\n )\n\n\n@pytest.mark.mpi\ndef test_column_parallel_linear(setup_default_process_group, multidevice_test):\n d, b, s, e = dist.get_world_size(), 2, 3, 5\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n inp_tensor = torch.randint(\n -4, 4, (b, s, e), dtype=torch.bfloat16, requires_grad=True\n )\n weight_tensor = torch.randint(\n -4, 4, (d * e, e), dtype=torch.bfloat16, requires_grad=True\n )\n\n inp_dtensor = dist.tensor.distribute_tensor(inp_tensor, mesh, [Replicate()])\n weight_dtensor = dist.tensor.distribute_tensor(weight_tensor, mesh, [Shard(0)])\n\n def assert_close(expected_tensor: torch.Tensor, dtensor: DTensor):\n torch.testing.assert_close(expected_tensor, dtensor.to_local().cpu())\n\n out_tensor = torch.nn.functional.linear(inp_tensor, weight_tensor)\n out_dtensor = LinearFunction.apply(inp_dtensor, weight_dtensor)\n rank = dist.get_rank()\n assert_close(out_tensor.split(e, dim=-1)[rank], out_dtensor)\n\n (expected_grad_x, expected_grad_w) = torch.autograd.grad(\n out_tensor,\n (inp_tensor, weight_tensor),\n torch.ones_like(out_tensor),\n )\n (grad_x, grad_w) = torch.autograd.grad(\n out_dtensor,\n (inp_dtensor, weight_dtensor),\n torch.ones_like(out_dtensor),\n )\n assert_close(expected_grad_x, grad_x)\n assert_close(expected_grad_w.split(e, dim=0)[rank], grad_w)\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear(setup_default_process_group, multidevice_test):\n d, b, s, e = dist.get_world_size(), 2, 3, 5\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n inp_tensor = torch.randint(\n -4, 4, (b, s, d * e), dtype=torch.bfloat16, requires_grad=True\n )\n weight_tensor = torch.randint(\n -4, 4, (e, d * e), dtype=torch.bfloat16, requires_grad=True\n )\n\n inp_dtensor = dist.tensor.distribute_tensor(inp_tensor, mesh, [Shard(-1)])\n weight_dtensor = dist.tensor.distribute_tensor(weight_tensor, mesh, [Shard(-1)])\n\n def assert_close(expected_tensor: torch.Tensor, dtensor: DTensor):\n torch.testing.assert_close(expected_tensor, dtensor.to_local().cpu())","source_hash":"77cb69829bfffaac4c646fcf958581e665e5cdcc48efe90791f4ba20d43efa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_dtensor.test_row_parallel_linear","uri":"program://Fuser/function/tests.python.multidevice.test_dtensor.test_row_parallel_linear#L83-L117","kind":"function","name":"test_row_parallel_linear","path":"tests/python/multidevice/test_dtensor.py","language":"python","start_line":83,"end_line":117,"context_start_line":63,"context_end_line":117,"code":" out_tensor = torch.nn.functional.linear(inp_tensor, weight_tensor)\n out_dtensor = LinearFunction.apply(inp_dtensor, weight_dtensor)\n rank = dist.get_rank()\n assert_close(out_tensor.split(e, dim=-1)[rank], out_dtensor)\n\n (expected_grad_x, expected_grad_w) = torch.autograd.grad(\n out_tensor,\n (inp_tensor, weight_tensor),\n torch.ones_like(out_tensor),\n )\n (grad_x, grad_w) = torch.autograd.grad(\n out_dtensor,\n (inp_dtensor, weight_dtensor),\n torch.ones_like(out_dtensor),\n )\n assert_close(expected_grad_x, grad_x)\n assert_close(expected_grad_w.split(e, dim=0)[rank], grad_w)\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear(setup_default_process_group, multidevice_test):\n d, b, s, e = dist.get_world_size(), 2, 3, 5\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n inp_tensor = torch.randint(\n -4, 4, (b, s, d * e), dtype=torch.bfloat16, requires_grad=True\n )\n weight_tensor = torch.randint(\n -4, 4, (e, d * e), dtype=torch.bfloat16, requires_grad=True\n )\n\n inp_dtensor = dist.tensor.distribute_tensor(inp_tensor, mesh, [Shard(-1)])\n weight_dtensor = dist.tensor.distribute_tensor(weight_tensor, mesh, [Shard(-1)])\n\n def assert_close(expected_tensor: torch.Tensor, dtensor: DTensor):\n torch.testing.assert_close(expected_tensor, dtensor.to_local().cpu())\n\n out_tensor = torch.nn.functional.linear(inp_tensor, weight_tensor)\n out_dtensor = LinearFunction.apply(inp_dtensor, weight_dtensor)\n assert_close(out_tensor, out_dtensor)\n\n (expected_grad_x, expected_grad_w) = torch.autograd.grad(\n out_tensor,\n (inp_tensor, weight_tensor),\n torch.ones_like(out_tensor),\n )\n (grad_x, grad_w) = torch.autograd.grad(\n out_dtensor,\n (inp_dtensor, weight_dtensor),\n torch.ones_like(out_dtensor),\n )\n rank = dist.get_rank()\n assert_close(expected_grad_x.split(e, dim=-1)[rank], grad_x)\n assert_close(expected_grad_w.split(e, dim=-1)[rank], grad_w)","source_hash":"77cb69829bfffaac4c646fcf958581e665e5cdcc48efe90791f4ba20d43efa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_dtensor.define_fusion","uri":"program://Fuser/function/tests.python.multidevice.test_dtensor.define_fusion#L19-L23","kind":"function","name":"define_fusion","path":"tests/python/multidevice/test_dtensor.py","language":"python","start_line":19,"end_line":23,"context_start_line":1,"context_end_line":43,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\nimport torch.distributed as dist\n\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Shard, Replicate\nfrom .fusion_definition_wrapper import FusionDefinitionWrapper\nfrom .linear import LinearFunction\nfrom nvfuser_direct import FusionDefinition, DataType\n\n\n@pytest.mark.mpi\ndef test_plus_one(setup_default_process_group, multidevice_test):\n def define_fusion(fd: FusionDefinition):\n inp = fd.define_tensor((-1, -1), contiguity=False, dtype=DataType.Float)\n one = fd.define_scalar(1.0, dtype=DataType.Float)\n out = fd.ops.add(inp, one)\n fd.add_output(out)\n\n op = FusionDefinitionWrapper(define_fusion)\n\n num_devices = dist.get_world_size()\n\n in_tensor = torch.randn(num_devices, 4)\n mesh = dist.device_mesh.init_device_mesh(\n \"cuda\", [num_devices], mesh_dim_names=[\"tp\"]\n )\n in_dtensor = dist.tensor.distribute_tensor(in_tensor, mesh, [Shard(0)])\n\n (out_dtensor,) = op([in_dtensor])\n torch.testing.assert_close(out_dtensor.to_local(), in_dtensor.to_local() + 1)\n assert out_dtensor.device_mesh == in_dtensor.device_mesh\n assert out_dtensor.placements == in_dtensor.placements\n assert (\n out_dtensor.device_mesh.mesh_dim_names == in_dtensor.device_mesh.mesh_dim_names\n )\n\n","source_hash":"77cb69829bfffaac4c646fcf958581e665e5cdcc48efe90791f4ba20d43efa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_dtensor.assert_close","uri":"program://Fuser/function/tests.python.multidevice.test_dtensor.assert_close#L98-L99","kind":"function","name":"assert_close","path":"tests/python/multidevice/test_dtensor.py","language":"python","start_line":98,"end_line":99,"context_start_line":78,"context_end_line":117,"code":" assert_close(expected_grad_x, grad_x)\n assert_close(expected_grad_w.split(e, dim=0)[rank], grad_w)\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear(setup_default_process_group, multidevice_test):\n d, b, s, e = dist.get_world_size(), 2, 3, 5\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n inp_tensor = torch.randint(\n -4, 4, (b, s, d * e), dtype=torch.bfloat16, requires_grad=True\n )\n weight_tensor = torch.randint(\n -4, 4, (e, d * e), dtype=torch.bfloat16, requires_grad=True\n )\n\n inp_dtensor = dist.tensor.distribute_tensor(inp_tensor, mesh, [Shard(-1)])\n weight_dtensor = dist.tensor.distribute_tensor(weight_tensor, mesh, [Shard(-1)])\n\n def assert_close(expected_tensor: torch.Tensor, dtensor: DTensor):\n torch.testing.assert_close(expected_tensor, dtensor.to_local().cpu())\n\n out_tensor = torch.nn.functional.linear(inp_tensor, weight_tensor)\n out_dtensor = LinearFunction.apply(inp_dtensor, weight_dtensor)\n assert_close(out_tensor, out_dtensor)\n\n (expected_grad_x, expected_grad_w) = torch.autograd.grad(\n out_tensor,\n (inp_tensor, weight_tensor),\n torch.ones_like(out_tensor),\n )\n (grad_x, grad_w) = torch.autograd.grad(\n out_dtensor,\n (inp_dtensor, weight_dtensor),\n torch.ones_like(out_dtensor),\n )\n rank = dist.get_rank()\n assert_close(expected_grad_x.split(e, dim=-1)[rank], grad_x)\n assert_close(expected_grad_w.split(e, dim=-1)[rank], grad_w)","source_hash":"77cb69829bfffaac4c646fcf958581e665e5cdcc48efe90791f4ba20d43efa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest","uri":"program://Fuser/module/tests.python.multidevice.conftest#L1-L145","kind":"module","name":"tests.python.multidevice.conftest","path":"tests/python/multidevice/conftest.py","language":"python","start_line":1,"end_line":145,"context_start_line":1,"context_end_line":145,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n# Run command:\n# mpirun -np [num_devices] pytest tests/python/multidevice/[test_name].py --only-mpi -s\n\nimport os\nimport pytest\nfrom typing import Iterable\n\nimport torch\nimport torch.distributed as dist\n\nimport nvfuser_direct as nvfuser\n\n\nclass MultideviceTest:\n def __init__(self):\n os.environ[\"NVIDIA_TF32_OVERRIDE\"] = \"0\"\n\n self._communicator = nvfuser.multidevice.Communicator.instance()\n\n torch.cuda.set_device(self._communicator.local_rank())\n\n # This way, when individual tests create unsharded input, each rank\n # receives the same data.\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor_1d(self, t: torch.Tensor, dim: int, mesh) -> torch.Tensor:\n \"\"\"Shard tensor along a single dimension (1D sharding only).\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n dim: Dimension to shard along\n mesh: DeviceMesh to use for sharding\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor_1d(unsharded, 0, mesh)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim).cuda(self.local_rank)\n\n def shard_tensor(self, t: torch.Tensor, tv) -> torch.Tensor:\n \"\"\"Shard tensor using TensorView's parallelization and device mesh.\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n tv: TensorView with device mesh and parallelization information\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n with nvfuser.FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1])\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n # ... rest of fusion\n\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor(unsharded, inp_tv)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n\n sharded = nvfuser.multidevice.shard_tensor(t, tv)\n return sharded.cuda(self.local_rank)\n\n\n@pytest.fixture\ndef multidevice_test():\n fixture = MultideviceTest()\n yield fixture\n fixture.communicator.barrier()\n\n\ndef get_env(envs: Iterable[str], /, *, default: str) -> str:\n for env in envs:\n if value := os.environ.get(env):\n return value\n return default\n\n\n# Set up the default process group for torch APIs like\n# dist.device_mesh.init_device_mesh.\n#\n# This fixture is used by multi-GPU tests that use torch.distributed directly.\n#\n# I use \"session\" instead of \"module\" because\n# https://github.com/pytorch/pytorch/issues/119196 reported race conditions\n# when reinitializing process groups.\n@pytest.fixture(scope=\"session\")\ndef setup_default_process_group():\n # I avoided using nvfuser.Communicator to minimize fixture dependencies on\n # nvFuser. This makes the transition from legacy bindings to direct\n # bindings easier.\n rank = int(get_env([\"OMPI_COMM_WORLD_RANK\", \"RANK\"], default=\"0\"))\n world_size = int(get_env([\"OMPI_COMM_WORLD_SIZE\", \"WORLD_SIZE\"], default=\"1\"))\n local_rank = int(get_env([\"OMPI_COMM_WORLD_LOCAL_RANK\", \"LOCAL_RANK\"], default=\"0\"))\n\n torch.cuda.set_device(local_rank)\n\n # The default port as used by https://github.com/pytorch/pytorch/blob/45a8b5682eb69d865cbf68c7f2f689b56b4efd53/torch/csrc/distributed/c10d/TCPStore.hpp#L51.\n dist.init_process_group(\n backend=\"nccl\",\n init_method=\"tcp://localhost:29500\",\n world_size=world_size,\n rank=rank,\n device_id=torch.device(f\"cuda:{local_rank}\"),\n )\n yield\n dist.destroy_process_group()","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.MultideviceTest","uri":"program://Fuser/class/tests.python.multidevice.conftest.MultideviceTest#L18-L100","kind":"class","name":"MultideviceTest","path":"tests/python/multidevice/conftest.py","language":"python","start_line":18,"end_line":100,"context_start_line":1,"context_end_line":120,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n# Run command:\n# mpirun -np [num_devices] pytest tests/python/multidevice/[test_name].py --only-mpi -s\n\nimport os\nimport pytest\nfrom typing import Iterable\n\nimport torch\nimport torch.distributed as dist\n\nimport nvfuser_direct as nvfuser\n\n\nclass MultideviceTest:\n def __init__(self):\n os.environ[\"NVIDIA_TF32_OVERRIDE\"] = \"0\"\n\n self._communicator = nvfuser.multidevice.Communicator.instance()\n\n torch.cuda.set_device(self._communicator.local_rank())\n\n # This way, when individual tests create unsharded input, each rank\n # receives the same data.\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor_1d(self, t: torch.Tensor, dim: int, mesh) -> torch.Tensor:\n \"\"\"Shard tensor along a single dimension (1D sharding only).\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n dim: Dimension to shard along\n mesh: DeviceMesh to use for sharding\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor_1d(unsharded, 0, mesh)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim).cuda(self.local_rank)\n\n def shard_tensor(self, t: torch.Tensor, tv) -> torch.Tensor:\n \"\"\"Shard tensor using TensorView's parallelization and device mesh.\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n tv: TensorView with device mesh and parallelization information\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n with nvfuser.FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1])\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n # ... rest of fusion\n\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor(unsharded, inp_tv)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n\n sharded = nvfuser.multidevice.shard_tensor(t, tv)\n return sharded.cuda(self.local_rank)\n\n\n@pytest.fixture\ndef multidevice_test():\n fixture = MultideviceTest()\n yield fixture\n fixture.communicator.barrier()\n\n\ndef get_env(envs: Iterable[str], /, *, default: str) -> str:\n for env in envs:\n if value := os.environ.get(env):\n return value\n return default\n\n\n# Set up the default process group for torch APIs like\n# dist.device_mesh.init_device_mesh.\n#\n# This fixture is used by multi-GPU tests that use torch.distributed directly.","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.multidevice_test","uri":"program://Fuser/function/tests.python.multidevice.conftest.multidevice_test#L104-L107","kind":"function","name":"multidevice_test","path":"tests/python/multidevice/conftest.py","language":"python","start_line":104,"end_line":107,"context_start_line":84,"context_end_line":127,"code":" with nvfuser.FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1])\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n # ... rest of fusion\n\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor(unsharded, inp_tv)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n\n sharded = nvfuser.multidevice.shard_tensor(t, tv)\n return sharded.cuda(self.local_rank)\n\n\n@pytest.fixture\ndef multidevice_test():\n fixture = MultideviceTest()\n yield fixture\n fixture.communicator.barrier()\n\n\ndef get_env(envs: Iterable[str], /, *, default: str) -> str:\n for env in envs:\n if value := os.environ.get(env):\n return value\n return default\n\n\n# Set up the default process group for torch APIs like\n# dist.device_mesh.init_device_mesh.\n#\n# This fixture is used by multi-GPU tests that use torch.distributed directly.\n#\n# I use \"session\" instead of \"module\" because\n# https://github.com/pytorch/pytorch/issues/119196 reported race conditions\n# when reinitializing process groups.\n@pytest.fixture(scope=\"session\")\ndef setup_default_process_group():\n # I avoided using nvfuser.Communicator to minimize fixture dependencies on","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.get_env","uri":"program://Fuser/function/tests.python.multidevice.conftest.get_env#L110-L114","kind":"function","name":"get_env","path":"tests/python/multidevice/conftest.py","language":"python","start_line":110,"end_line":114,"context_start_line":90,"context_end_line":134,"code":" unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor(unsharded, inp_tv)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n\n sharded = nvfuser.multidevice.shard_tensor(t, tv)\n return sharded.cuda(self.local_rank)\n\n\n@pytest.fixture\ndef multidevice_test():\n fixture = MultideviceTest()\n yield fixture\n fixture.communicator.barrier()\n\n\ndef get_env(envs: Iterable[str], /, *, default: str) -> str:\n for env in envs:\n if value := os.environ.get(env):\n return value\n return default\n\n\n# Set up the default process group for torch APIs like\n# dist.device_mesh.init_device_mesh.\n#\n# This fixture is used by multi-GPU tests that use torch.distributed directly.\n#\n# I use \"session\" instead of \"module\" because\n# https://github.com/pytorch/pytorch/issues/119196 reported race conditions\n# when reinitializing process groups.\n@pytest.fixture(scope=\"session\")\ndef setup_default_process_group():\n # I avoided using nvfuser.Communicator to minimize fixture dependencies on\n # nvFuser. This makes the transition from legacy bindings to direct\n # bindings easier.\n rank = int(get_env([\"OMPI_COMM_WORLD_RANK\", \"RANK\"], default=\"0\"))\n world_size = int(get_env([\"OMPI_COMM_WORLD_SIZE\", \"WORLD_SIZE\"], default=\"1\"))\n local_rank = int(get_env([\"OMPI_COMM_WORLD_LOCAL_RANK\", \"LOCAL_RANK\"], default=\"0\"))\n\n torch.cuda.set_device(local_rank)","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.setup_default_process_group","uri":"program://Fuser/function/tests.python.multidevice.conftest.setup_default_process_group#L126-L145","kind":"function","name":"setup_default_process_group","path":"tests/python/multidevice/conftest.py","language":"python","start_line":126,"end_line":145,"context_start_line":106,"context_end_line":145,"code":" yield fixture\n fixture.communicator.barrier()\n\n\ndef get_env(envs: Iterable[str], /, *, default: str) -> str:\n for env in envs:\n if value := os.environ.get(env):\n return value\n return default\n\n\n# Set up the default process group for torch APIs like\n# dist.device_mesh.init_device_mesh.\n#\n# This fixture is used by multi-GPU tests that use torch.distributed directly.\n#\n# I use \"session\" instead of \"module\" because\n# https://github.com/pytorch/pytorch/issues/119196 reported race conditions\n# when reinitializing process groups.\n@pytest.fixture(scope=\"session\")\ndef setup_default_process_group():\n # I avoided using nvfuser.Communicator to minimize fixture dependencies on\n # nvFuser. This makes the transition from legacy bindings to direct\n # bindings easier.\n rank = int(get_env([\"OMPI_COMM_WORLD_RANK\", \"RANK\"], default=\"0\"))\n world_size = int(get_env([\"OMPI_COMM_WORLD_SIZE\", \"WORLD_SIZE\"], default=\"1\"))\n local_rank = int(get_env([\"OMPI_COMM_WORLD_LOCAL_RANK\", \"LOCAL_RANK\"], default=\"0\"))\n\n torch.cuda.set_device(local_rank)\n\n # The default port as used by https://github.com/pytorch/pytorch/blob/45a8b5682eb69d865cbf68c7f2f689b56b4efd53/torch/csrc/distributed/c10d/TCPStore.hpp#L51.\n dist.init_process_group(\n backend=\"nccl\",\n init_method=\"tcp://localhost:29500\",\n world_size=world_size,\n rank=rank,\n device_id=torch.device(f\"cuda:{local_rank}\"),\n )\n yield\n dist.destroy_process_group()","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.__init__","uri":"program://Fuser/function/tests.python.multidevice.conftest.__init__#L19-L28","kind":"function","name":"__init__","path":"tests/python/multidevice/conftest.py","language":"python","start_line":19,"end_line":28,"context_start_line":1,"context_end_line":48,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n# Run command:\n# mpirun -np [num_devices] pytest tests/python/multidevice/[test_name].py --only-mpi -s\n\nimport os\nimport pytest\nfrom typing import Iterable\n\nimport torch\nimport torch.distributed as dist\n\nimport nvfuser_direct as nvfuser\n\n\nclass MultideviceTest:\n def __init__(self):\n os.environ[\"NVIDIA_TF32_OVERRIDE\"] = \"0\"\n\n self._communicator = nvfuser.multidevice.Communicator.instance()\n\n torch.cuda.set_device(self._communicator.local_rank())\n\n # This way, when individual tests create unsharded input, each rank\n # receives the same data.\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.communicator","uri":"program://Fuser/function/tests.python.multidevice.conftest.communicator#L31-L32","kind":"function","name":"communicator","path":"tests/python/multidevice/conftest.py","language":"python","start_line":31,"end_line":32,"context_start_line":11,"context_end_line":52,"code":"\nimport torch\nimport torch.distributed as dist\n\nimport nvfuser_direct as nvfuser\n\n\nclass MultideviceTest:\n def __init__(self):\n os.environ[\"NVIDIA_TF32_OVERRIDE\"] = \"0\"\n\n self._communicator = nvfuser.multidevice.Communicator.instance()\n\n torch.cuda.set_device(self._communicator.local_rank())\n\n # This way, when individual tests create unsharded input, each rank\n # receives the same data.\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor_1d(self, t: torch.Tensor, dim: int, mesh) -> torch.Tensor:\n \"\"\"Shard tensor along a single dimension (1D sharding only).\n","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.size","uri":"program://Fuser/function/tests.python.multidevice.conftest.size#L35-L36","kind":"function","name":"size","path":"tests/python/multidevice/conftest.py","language":"python","start_line":35,"end_line":36,"context_start_line":15,"context_end_line":56,"code":"import nvfuser_direct as nvfuser\n\n\nclass MultideviceTest:\n def __init__(self):\n os.environ[\"NVIDIA_TF32_OVERRIDE\"] = \"0\"\n\n self._communicator = nvfuser.multidevice.Communicator.instance()\n\n torch.cuda.set_device(self._communicator.local_rank())\n\n # This way, when individual tests create unsharded input, each rank\n # receives the same data.\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor_1d(self, t: torch.Tensor, dim: int, mesh) -> torch.Tensor:\n \"\"\"Shard tensor along a single dimension (1D sharding only).\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n dim: Dimension to shard along\n mesh: DeviceMesh to use for sharding","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.rank","uri":"program://Fuser/function/tests.python.multidevice.conftest.rank#L39-L40","kind":"function","name":"rank","path":"tests/python/multidevice/conftest.py","language":"python","start_line":39,"end_line":40,"context_start_line":19,"context_end_line":60,"code":" def __init__(self):\n os.environ[\"NVIDIA_TF32_OVERRIDE\"] = \"0\"\n\n self._communicator = nvfuser.multidevice.Communicator.instance()\n\n torch.cuda.set_device(self._communicator.local_rank())\n\n # This way, when individual tests create unsharded input, each rank\n # receives the same data.\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor_1d(self, t: torch.Tensor, dim: int, mesh) -> torch.Tensor:\n \"\"\"Shard tensor along a single dimension (1D sharding only).\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n dim: Dimension to shard along\n mesh: DeviceMesh to use for sharding\n\n Returns:\n Sharded tensor on current GPU device\n","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.local_size","uri":"program://Fuser/function/tests.python.multidevice.conftest.local_size#L43-L44","kind":"function","name":"local_size","path":"tests/python/multidevice/conftest.py","language":"python","start_line":43,"end_line":44,"context_start_line":23,"context_end_line":64,"code":"\n torch.cuda.set_device(self._communicator.local_rank())\n\n # This way, when individual tests create unsharded input, each rank\n # receives the same data.\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor_1d(self, t: torch.Tensor, dim: int, mesh) -> torch.Tensor:\n \"\"\"Shard tensor along a single dimension (1D sharding only).\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n dim: Dimension to shard along\n mesh: DeviceMesh to use for sharding\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor_1d(unsharded, 0, mesh)","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.local_rank","uri":"program://Fuser/function/tests.python.multidevice.conftest.local_rank#L47-L48","kind":"function","name":"local_rank","path":"tests/python/multidevice/conftest.py","language":"python","start_line":47,"end_line":48,"context_start_line":27,"context_end_line":68,"code":" # receives the same data.\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor_1d(self, t: torch.Tensor, dim: int, mesh) -> torch.Tensor:\n \"\"\"Shard tensor along a single dimension (1D sharding only).\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n dim: Dimension to shard along\n mesh: DeviceMesh to use for sharding\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor_1d(unsharded, 0, mesh)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.shard_tensor_1d","uri":"program://Fuser/function/tests.python.multidevice.conftest.shard_tensor_1d#L50-L71","kind":"function","name":"shard_tensor_1d","path":"tests/python/multidevice/conftest.py","language":"python","start_line":50,"end_line":71,"context_start_line":30,"context_end_line":91,"code":" @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor_1d(self, t: torch.Tensor, dim: int, mesh) -> torch.Tensor:\n \"\"\"Shard tensor along a single dimension (1D sharding only).\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n dim: Dimension to shard along\n mesh: DeviceMesh to use for sharding\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor_1d(unsharded, 0, mesh)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim).cuda(self.local_rank)\n\n def shard_tensor(self, t: torch.Tensor, tv) -> torch.Tensor:\n \"\"\"Shard tensor using TensorView's parallelization and device mesh.\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n tv: TensorView with device mesh and parallelization information\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n with nvfuser.FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1])\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n # ... rest of fusion\n\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor(unsharded, inp_tv)","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.conftest.shard_tensor","uri":"program://Fuser/function/tests.python.multidevice.conftest.shard_tensor#L73-L100","kind":"function","name":"shard_tensor","path":"tests/python/multidevice/conftest.py","language":"python","start_line":73,"end_line":100,"context_start_line":53,"context_end_line":120,"code":" Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n dim: Dimension to shard along\n mesh: DeviceMesh to use for sharding\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor_1d(unsharded, 0, mesh)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim).cuda(self.local_rank)\n\n def shard_tensor(self, t: torch.Tensor, tv) -> torch.Tensor:\n \"\"\"Shard tensor using TensorView's parallelization and device mesh.\n\n Args:\n t: Tensor to shard (preferably on CPU for memory efficiency)\n tv: TensorView with device mesh and parallelization information\n\n Returns:\n Sharded tensor on current GPU device\n\n Example:\n with nvfuser.FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1])\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n # ... rest of fusion\n\n unsharded = torch.randn(num_devices, 4)\n sharded = self.shard_tensor(unsharded, inp_tv)\n \"\"\"\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n\n sharded = nvfuser.multidevice.shard_tensor(t, tv)\n return sharded.cuda(self.local_rank)\n\n\n@pytest.fixture\ndef multidevice_test():\n fixture = MultideviceTest()\n yield fixture\n fixture.communicator.barrier()\n\n\ndef get_env(envs: Iterable[str], /, *, default: str) -> str:\n for env in envs:\n if value := os.environ.get(env):\n return value\n return default\n\n\n# Set up the default process group for torch APIs like\n# dist.device_mesh.init_device_mesh.\n#\n# This fixture is used by multi-GPU tests that use torch.distributed directly.","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding","uri":"program://Fuser/module/tests.python.multidevice.test_sharding#L1-L234","kind":"module","name":"tests.python.multidevice.test_sharding","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":1,"end_line":234,"context_start_line":1,"context_end_line":234,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\n\nimport nvfuser_direct as nvfuser\n\n\n# Unit tests for multidevice_test.shard_tensor.\nclass TestShardTensor:\n @pytest.mark.mpi\n def test_inner_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.inner_split(0, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(3 * d, dtype=torch.float)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(3, d)[:, multidevice_test.rank]\n )\n\n @pytest.mark.mpi\n def test_nonoutermost_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(0, 2)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(2 * d * 3, dtype=torch.float)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(2, d, 3)[:, multidevice_test.rank, :].flatten()\n )\n\n @pytest.mark.mpi\n def test_parallel_reduction(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1])\n out_tv = fd.ops.sum(inp_tv, [1])\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.arange(2 * d * 3, dtype=torch.float).reshape(2, d * 3)\n out_ref = inp_ref.sum([1])\n\n rank = multidevice_test.rank\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n torch.testing.assert_close(inp.cpu(), inp_ref[:, rank * 3 : (rank + 1) * 3])\n out = multidevice_test.shard_tensor(out_ref, out_tv)\n torch.testing.assert_close(out.cpu(), out_ref)\n\n @pytest.mark.mpi\n def test_2d_sharded_matrix(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n dp_size = d // tp_size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n tv.outer_split(2, tp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n rows_per_rank = 2\n cols_per_rank = 3\n t_ref = torch.arange(\n dp_size * rows_per_rank * tp_size * cols_per_rank, dtype=torch.float\n ).reshape(dp_size * rows_per_rank, tp_size * cols_per_rank)\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n dp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(),\n t_ref[\n dp_rank * rows_per_rank : (dp_rank + 1) * rows_per_rank,\n tp_rank * cols_per_rank : (tp_rank + 1) * cols_per_rank,\n ],\n )\n\n @pytest.mark.mpi\n def test_2d_sharded_vector(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n dp_size = d // tp_size\n\n rows_per_rank = 2\n cols_per_rank = 3\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.inner_split(0, tp_size * cols_per_rank)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n tv.outer_split(2, tp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(\n dp_size * rows_per_rank * tp_size * cols_per_rank, dtype=torch.float\n )\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n dp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(),\n t_ref.reshape(dp_size, rows_per_rank, tp_size, cols_per_rank)[\n dp_rank, :, tp_rank, :\n ].flatten(),\n )\n\n @pytest.mark.mpi\n def test_context_and_tensor_parallel(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n cp_size = d // tp_size\n e = 5\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1, e]) # [b, s, e]\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(cp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.outer_split(1, tp_size)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n tv.outer_split(2, cp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_y)\n tv.reorder({2: 0, 1: 1})\n\n b, s = 2, tp_size * cp_size * 3\n t_ref = torch.arange(b * s * e, dtype=torch.float).reshape(b, s, e)\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n cp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(b, tp_size, cp_size, 3, e)[:, tp_rank, cp_rank, :, :]\n )\n\n @pytest.mark.mpi\n def test_expanded_broadcast(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1], contiguity=[True, None])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # When d=2, t_ref =\n # [[0, 0, 0, 0, 0, 0],\n # [1, 1, 1, 1, 1, 1]]\n #\n # GPU 0 gets the left half, and GPU 1 gets the right half. So t =\n # [[0, 0, 0],\n # [1, 1, 1]]\n # regardless of which GPU.\n t_ref = torch.arange(2, dtype=torch.float).unsqueeze(-1).expand(-1, d * 3)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), torch.arange(2, dtype=torch.float).unsqueeze(-1).expand(-1, 3)\n )\n\n @pytest.mark.mpi\n def test_broadcast(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([1, -1], contiguity=[None, True])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # When d=2, t_ref = [[0, 1, 2, 3, 4, 5]]. GPU 0 gets [[0, 1, 2]], and GPU 1 gets [[3, 4, 5]].\n t_ref = torch.arange(d * 3, dtype=torch.float).unsqueeze(0)\n t = multidevice_test.shard_tensor(t_ref, tv)\n rank = multidevice_test.rank\n torch.testing.assert_close(t.cpu(), t_ref[:, rank * 3 : (rank + 1) * 3])","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding.TestShardTensor","uri":"program://Fuser/class/tests.python.multidevice.test_sharding.TestShardTensor#L13-L234","kind":"class","name":"TestShardTensor","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":13,"end_line":234,"context_start_line":1,"context_end_line":234,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\n\nimport nvfuser_direct as nvfuser\n\n\n# Unit tests for multidevice_test.shard_tensor.\nclass TestShardTensor:\n @pytest.mark.mpi\n def test_inner_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.inner_split(0, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(3 * d, dtype=torch.float)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(3, d)[:, multidevice_test.rank]\n )\n\n @pytest.mark.mpi\n def test_nonoutermost_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(0, 2)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(2 * d * 3, dtype=torch.float)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(2, d, 3)[:, multidevice_test.rank, :].flatten()\n )\n\n @pytest.mark.mpi\n def test_parallel_reduction(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1])\n out_tv = fd.ops.sum(inp_tv, [1])\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.arange(2 * d * 3, dtype=torch.float).reshape(2, d * 3)\n out_ref = inp_ref.sum([1])\n\n rank = multidevice_test.rank\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n torch.testing.assert_close(inp.cpu(), inp_ref[:, rank * 3 : (rank + 1) * 3])\n out = multidevice_test.shard_tensor(out_ref, out_tv)\n torch.testing.assert_close(out.cpu(), out_ref)\n\n @pytest.mark.mpi\n def test_2d_sharded_matrix(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n dp_size = d // tp_size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n tv.outer_split(2, tp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n rows_per_rank = 2\n cols_per_rank = 3\n t_ref = torch.arange(\n dp_size * rows_per_rank * tp_size * cols_per_rank, dtype=torch.float\n ).reshape(dp_size * rows_per_rank, tp_size * cols_per_rank)\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n dp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(),\n t_ref[\n dp_rank * rows_per_rank : (dp_rank + 1) * rows_per_rank,\n tp_rank * cols_per_rank : (tp_rank + 1) * cols_per_rank,\n ],\n )\n\n @pytest.mark.mpi\n def test_2d_sharded_vector(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n dp_size = d // tp_size\n\n rows_per_rank = 2\n cols_per_rank = 3\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.inner_split(0, tp_size * cols_per_rank)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n tv.outer_split(2, tp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(\n dp_size * rows_per_rank * tp_size * cols_per_rank, dtype=torch.float\n )\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n dp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(),\n t_ref.reshape(dp_size, rows_per_rank, tp_size, cols_per_rank)[\n dp_rank, :, tp_rank, :\n ].flatten(),\n )\n\n @pytest.mark.mpi\n def test_context_and_tensor_parallel(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n cp_size = d // tp_size\n e = 5\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1, e]) # [b, s, e]\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(cp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.outer_split(1, tp_size)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n tv.outer_split(2, cp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_y)\n tv.reorder({2: 0, 1: 1})\n\n b, s = 2, tp_size * cp_size * 3\n t_ref = torch.arange(b * s * e, dtype=torch.float).reshape(b, s, e)\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n cp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(b, tp_size, cp_size, 3, e)[:, tp_rank, cp_rank, :, :]\n )\n\n @pytest.mark.mpi\n def test_expanded_broadcast(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1], contiguity=[True, None])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # When d=2, t_ref =\n # [[0, 0, 0, 0, 0, 0],\n # [1, 1, 1, 1, 1, 1]]\n #\n # GPU 0 gets the left half, and GPU 1 gets the right half. So t =\n # [[0, 0, 0],\n # [1, 1, 1]]\n # regardless of which GPU.\n t_ref = torch.arange(2, dtype=torch.float).unsqueeze(-1).expand(-1, d * 3)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), torch.arange(2, dtype=torch.float).unsqueeze(-1).expand(-1, 3)\n )\n\n @pytest.mark.mpi\n def test_broadcast(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([1, -1], contiguity=[None, True])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # When d=2, t_ref = [[0, 1, 2, 3, 4, 5]]. GPU 0 gets [[0, 1, 2]], and GPU 1 gets [[3, 4, 5]].\n t_ref = torch.arange(d * 3, dtype=torch.float).unsqueeze(0)\n t = multidevice_test.shard_tensor(t_ref, tv)\n rank = multidevice_test.rank\n torch.testing.assert_close(t.cpu(), t_ref[:, rank * 3 : (rank + 1) * 3])","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding.test_inner_split","uri":"program://Fuser/function/tests.python.multidevice.test_sharding.test_inner_split#L15-L31","kind":"function","name":"test_inner_split","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":15,"end_line":31,"context_start_line":1,"context_end_line":51,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\n\nimport nvfuser_direct as nvfuser\n\n\n# Unit tests for multidevice_test.shard_tensor.\nclass TestShardTensor:\n @pytest.mark.mpi\n def test_inner_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.inner_split(0, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(3 * d, dtype=torch.float)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(3, d)[:, multidevice_test.rank]\n )\n\n @pytest.mark.mpi\n def test_nonoutermost_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(0, 2)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(2 * d * 3, dtype=torch.float)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(2, d, 3)[:, multidevice_test.rank, :].flatten()\n )","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding.test_nonoutermost_split","uri":"program://Fuser/function/tests.python.multidevice.test_sharding.test_nonoutermost_split#L34-L51","kind":"function","name":"test_nonoutermost_split","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":34,"end_line":51,"context_start_line":14,"context_end_line":71,"code":" @pytest.mark.mpi\n def test_inner_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.inner_split(0, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(3 * d, dtype=torch.float)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(3, d)[:, multidevice_test.rank]\n )\n\n @pytest.mark.mpi\n def test_nonoutermost_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(0, 2)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(2 * d * 3, dtype=torch.float)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(2, d, 3)[:, multidevice_test.rank, :].flatten()\n )\n\n @pytest.mark.mpi\n def test_parallel_reduction(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1])\n out_tv = fd.ops.sum(inp_tv, [1])\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.arange(2 * d * 3, dtype=torch.float).reshape(2, d * 3)\n out_ref = inp_ref.sum([1])\n\n rank = multidevice_test.rank\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding.test_parallel_reduction","uri":"program://Fuser/function/tests.python.multidevice.test_sharding.test_parallel_reduction#L54-L74","kind":"function","name":"test_parallel_reduction","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":54,"end_line":74,"context_start_line":34,"context_end_line":94,"code":" def test_nonoutermost_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(0, 2)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(2 * d * 3, dtype=torch.float)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(2, d, 3)[:, multidevice_test.rank, :].flatten()\n )\n\n @pytest.mark.mpi\n def test_parallel_reduction(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1])\n out_tv = fd.ops.sum(inp_tv, [1])\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.arange(2 * d * 3, dtype=torch.float).reshape(2, d * 3)\n out_ref = inp_ref.sum([1])\n\n rank = multidevice_test.rank\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n torch.testing.assert_close(inp.cpu(), inp_ref[:, rank * 3 : (rank + 1) * 3])\n out = multidevice_test.shard_tensor(out_ref, out_tv)\n torch.testing.assert_close(out.cpu(), out_ref)\n\n @pytest.mark.mpi\n def test_2d_sharded_matrix(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n dp_size = d // tp_size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.outer_split(0, dp_size)","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding.test_2d_sharded_matrix","uri":"program://Fuser/function/tests.python.multidevice.test_sharding.test_2d_sharded_matrix#L77-L114","kind":"function","name":"test_2d_sharded_matrix","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":77,"end_line":114,"context_start_line":57,"context_end_line":134,"code":" inp_tv = fd.define_tensor([-1, -1])\n out_tv = fd.ops.sum(inp_tv, [1])\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.arange(2 * d * 3, dtype=torch.float).reshape(2, d * 3)\n out_ref = inp_ref.sum([1])\n\n rank = multidevice_test.rank\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n torch.testing.assert_close(inp.cpu(), inp_ref[:, rank * 3 : (rank + 1) * 3])\n out = multidevice_test.shard_tensor(out_ref, out_tv)\n torch.testing.assert_close(out.cpu(), out_ref)\n\n @pytest.mark.mpi\n def test_2d_sharded_matrix(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n dp_size = d // tp_size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n tv.outer_split(2, tp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n rows_per_rank = 2\n cols_per_rank = 3\n t_ref = torch.arange(\n dp_size * rows_per_rank * tp_size * cols_per_rank, dtype=torch.float\n ).reshape(dp_size * rows_per_rank, tp_size * cols_per_rank)\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n dp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(),\n t_ref[\n dp_rank * rows_per_rank : (dp_rank + 1) * rows_per_rank,\n tp_rank * cols_per_rank : (tp_rank + 1) * cols_per_rank,\n ],\n )\n\n @pytest.mark.mpi\n def test_2d_sharded_vector(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n dp_size = d // tp_size\n\n rows_per_rank = 2\n cols_per_rank = 3\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, tp_size)","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding.test_2d_sharded_vector","uri":"program://Fuser/function/tests.python.multidevice.test_sharding.test_2d_sharded_vector#L117-L155","kind":"function","name":"test_2d_sharded_vector","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":117,"end_line":155,"context_start_line":97,"context_end_line":175,"code":" tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n rows_per_rank = 2\n cols_per_rank = 3\n t_ref = torch.arange(\n dp_size * rows_per_rank * tp_size * cols_per_rank, dtype=torch.float\n ).reshape(dp_size * rows_per_rank, tp_size * cols_per_rank)\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n dp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(),\n t_ref[\n dp_rank * rows_per_rank : (dp_rank + 1) * rows_per_rank,\n tp_rank * cols_per_rank : (tp_rank + 1) * cols_per_rank,\n ],\n )\n\n @pytest.mark.mpi\n def test_2d_sharded_vector(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n dp_size = d // tp_size\n\n rows_per_rank = 2\n cols_per_rank = 3\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.inner_split(0, tp_size * cols_per_rank)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n tv.outer_split(2, tp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(\n dp_size * rows_per_rank * tp_size * cols_per_rank, dtype=torch.float\n )\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n dp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(),\n t_ref.reshape(dp_size, rows_per_rank, tp_size, cols_per_rank)[\n dp_rank, :, tp_rank, :\n ].flatten(),\n )\n\n @pytest.mark.mpi\n def test_context_and_tensor_parallel(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n cp_size = d // tp_size\n e = 5\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1, e]) # [b, s, e]\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(cp_size, tp_size)\n )\n tv.set_device_mesh(mesh)","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding.test_context_and_tensor_parallel","uri":"program://Fuser/function/tests.python.multidevice.test_sharding.test_context_and_tensor_parallel#L158-L190","kind":"function","name":"test_context_and_tensor_parallel","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":158,"end_line":190,"context_start_line":138,"context_end_line":210,"code":" tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n tv.outer_split(2, tp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n t_ref = torch.arange(\n dp_size * rows_per_rank * tp_size * cols_per_rank, dtype=torch.float\n )\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n dp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(),\n t_ref.reshape(dp_size, rows_per_rank, tp_size, cols_per_rank)[\n dp_rank, :, tp_rank, :\n ].flatten(),\n )\n\n @pytest.mark.mpi\n def test_context_and_tensor_parallel(self, multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(\n f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\"\n )\n cp_size = d // tp_size\n e = 5\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1, e]) # [b, s, e]\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(cp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.outer_split(1, tp_size)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n tv.outer_split(2, cp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_y)\n tv.reorder({2: 0, 1: 1})\n\n b, s = 2, tp_size * cp_size * 3\n t_ref = torch.arange(b * s * e, dtype=torch.float).reshape(b, s, e)\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n cp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(b, tp_size, cp_size, 3, e)[:, tp_rank, cp_rank, :, :]\n )\n\n @pytest.mark.mpi\n def test_expanded_broadcast(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1], contiguity=[True, None])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # When d=2, t_ref =\n # [[0, 0, 0, 0, 0, 0],\n # [1, 1, 1, 1, 1, 1]]\n #\n # GPU 0 gets the left half, and GPU 1 gets the right half. So t =\n # [[0, 0, 0],\n # [1, 1, 1]]","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding.test_expanded_broadcast","uri":"program://Fuser/function/tests.python.multidevice.test_sharding.test_expanded_broadcast#L193-L216","kind":"function","name":"test_expanded_broadcast","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":193,"end_line":216,"context_start_line":173,"context_end_line":234,"code":" torch.arange(d).reshape(cp_size, tp_size)\n )\n tv.set_device_mesh(mesh)\n tv.outer_split(1, tp_size)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n tv.outer_split(2, cp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_y)\n tv.reorder({2: 0, 1: 1})\n\n b, s = 2, tp_size * cp_size * 3\n t_ref = torch.arange(b * s * e, dtype=torch.float).reshape(b, s, e)\n t = multidevice_test.shard_tensor(t_ref, tv)\n\n cp_rank = multidevice_test.rank // tp_size\n tp_rank = multidevice_test.rank % tp_size\n torch.testing.assert_close(\n t.cpu(), t_ref.reshape(b, tp_size, cp_size, 3, e)[:, tp_rank, cp_rank, :, :]\n )\n\n @pytest.mark.mpi\n def test_expanded_broadcast(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1, -1], contiguity=[True, None])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # When d=2, t_ref =\n # [[0, 0, 0, 0, 0, 0],\n # [1, 1, 1, 1, 1, 1]]\n #\n # GPU 0 gets the left half, and GPU 1 gets the right half. So t =\n # [[0, 0, 0],\n # [1, 1, 1]]\n # regardless of which GPU.\n t_ref = torch.arange(2, dtype=torch.float).unsqueeze(-1).expand(-1, d * 3)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), torch.arange(2, dtype=torch.float).unsqueeze(-1).expand(-1, 3)\n )\n\n @pytest.mark.mpi\n def test_broadcast(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([1, -1], contiguity=[None, True])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # When d=2, t_ref = [[0, 1, 2, 3, 4, 5]]. GPU 0 gets [[0, 1, 2]], and GPU 1 gets [[3, 4, 5]].\n t_ref = torch.arange(d * 3, dtype=torch.float).unsqueeze(0)\n t = multidevice_test.shard_tensor(t_ref, tv)\n rank = multidevice_test.rank\n torch.testing.assert_close(t.cpu(), t_ref[:, rank * 3 : (rank + 1) * 3])","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_sharding.test_broadcast","uri":"program://Fuser/function/tests.python.multidevice.test_sharding.test_broadcast#L219-L234","kind":"function","name":"test_broadcast","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":219,"end_line":234,"context_start_line":199,"context_end_line":234,"code":" mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # When d=2, t_ref =\n # [[0, 0, 0, 0, 0, 0],\n # [1, 1, 1, 1, 1, 1]]\n #\n # GPU 0 gets the left half, and GPU 1 gets the right half. So t =\n # [[0, 0, 0],\n # [1, 1, 1]]\n # regardless of which GPU.\n t_ref = torch.arange(2, dtype=torch.float).unsqueeze(-1).expand(-1, d * 3)\n t = multidevice_test.shard_tensor(t_ref, tv)\n torch.testing.assert_close(\n t.cpu(), torch.arange(2, dtype=torch.float).unsqueeze(-1).expand(-1, 3)\n )\n\n @pytest.mark.mpi\n def test_broadcast(self, multidevice_test):\n d = multidevice_test.size\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([1, -1], contiguity=[None, True])\n fd.add_output(tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n tv.set_device_mesh(mesh)\n tv.outer_split(1, d)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # When d=2, t_ref = [[0, 1, 2, 3, 4, 5]]. GPU 0 gets [[0, 1, 2]], and GPU 1 gets [[3, 4, 5]].\n t_ref = torch.arange(d * 3, dtype=torch.float).unsqueeze(0)\n t = multidevice_test.shard_tensor(t_ref, tv)\n rank = multidevice_test.rank\n torch.testing.assert_close(t.cpu(), t_ref[:, rank * 3 : (rank + 1) * 3])","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap","uri":"program://Fuser/module/tests.python.multidevice.test_overlap#L1-L749","kind":"module","name":"tests.python.multidevice.test_overlap","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":1,"end_line":749,"context_start_line":1,"context_end_line":749,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport os\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import distribute_tensor, Shard\n\nimport nvfuser_direct as nvfuser\nfrom .benchmark_utils import get_benchmark_fns\nfrom nvfuser_direct import DataType, FusionDefinition, CommunicatorBackend, TensorView\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\n\n\ndef row_parallel_linear_forward(\n h: int, num_devices: int, num_chunks: int\n) -> FusionDefinition:\n with FusionDefinition() as fd:\n inp = fd.define_tensor(\n shape=[-1, h * 4], contiguity=True, dtype=DataType.BFloat16\n )\n weight = fd.define_tensor(\n shape=[h, h * 4], contiguity=True, dtype=DataType.BFloat16\n )\n out = fd.ops.linear(inp, weight)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n for tv in (inp, weight):\n tv.set_device_mesh(mesh)\n\n inp.outer_split(0, num_chunks)\n inp.axis(0).parallelize(nvfuser.ParallelType.stream)\n inp.outer_split(2, mesh.size)\n inp.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n weight.outer_split(1, mesh.size)\n weight.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # Expected pre-segmentation IR:\n #\n # [t, 4h] [h, 4h]\n # /\\ /\\ /\\.\n # s* d d\n # |\n # | linear\n # |\n # r{4h}\n # / \\.\n # [t, h, d, r{4h/d}]\n # /\\.\n # s\n # |\n # | sum\n # |\n # [t, h, r{d}]\n # /\\.\n # s*\n\n # The host IR dumped with NVFUSER_DUMP=host_ir is similar to `row_parallel_linear_forward_reference`:\n #\n # %HostIrContainer { (T0_g___bfloat[istreamIdx7{3}, ideviceIdx.x9{2}, iS8{( ceilDiv(i0, 3) )}, iS10{4}] (DeviceMesh{0 1}), T1_g___bfloat[ideviceIdx.x11{2}, iS2{2}, iS12{4}] (DeviceMesh{0 1})) -> (T2_g___bfloat[istreamIdx27{3}, rdeviceIdx.x26{2}, iS28{( ceilDiv(i0, 3) )}, iS25{2}] (DeviceMesh{0 1})) :\n # T2_g___bfloat[istreamIdx27{3}, rdeviceIdx.x26{2}, iS28{( ceilDiv(i0, 3) )}, iS25{2}] (DeviceMesh{0 1}) = ALLOCATE(buffer=T2_g___bfloat[istreamIdx27{3}, rdeviceIdx.x26{2}, iS28{( ceilDiv(i0, 3) )}, iS25{2}] (DeviceMesh{0 1}), mem_type=global, size=( i0 * 2 ), zero_init=false, resets_to_zero=false)\n # Stream 0x174e5c80 = GetCurrentStream()\n # FOR i535 from 0 to 3:\n # SetCurrentStream(Stream i535)\n # Synchronize(Stream 0x174e5c80)\n # T4_l___bfloat[istreamIdx37{3}, iS38{( ceilDiv(i0, 3) )}, ideviceIdx.x35{2}, iS36{4}] (DeviceMesh{0 1}) = ShardByStream(T0_g___bfloat[istreamIdx7{3}, ideviceIdx.x9{2}, iS8{( ceilDiv(i0, 3) )}, iS10{4}] (DeviceMesh{0 1}), stream_index = i535)\n # T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1}) = ALLOCATE(buffer=T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1}), mem_type=global, size=( ( ceilDiv(i0, 3) ) * 12 ), zero_init=false, resets_to_zero=false)\n # T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1})\n # = linear(T4_l___bfloat[istreamIdx37{3}, iS38{( ceilDiv(i0, 3) )}, ideviceIdx.x35{2}, iS36{4}] (DeviceMesh{0 1}),\n # T1_g___bfloat[ideviceIdx.x11{2}, iS2{2}, iS12{4}] (DeviceMesh{0 1}) )\n # T5_l___bfloat[istreamIdx41{3}, iS42{( ceilDiv(i0, 3) )}, iS40{2}] (DeviceMesh{0 1}) = ShardByStream(T2_g___bfloat[istreamIdx27{3}, rdeviceIdx.x26{2}, iS28{( ceilDiv(i0, 3) )}, iS25{2}] (DeviceMesh{0 1}), stream_index = i535)\n # Communication 272 (type=Allreduce, team=(0 1), input=T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1}), output=T5_l___bfloat[istreamIdx41{3}, iS42{( ceilDiv(i0, 3) )}, iS40{2}] (DeviceMesh{0 1}), backend=NCCL)\n # Wait(Communication 272)\n # SetCurrentStream(Stream 0x174e5c80)\n # FOR i535 from 0 to 3:\n # Synchronize(Stream i535)\n # } // %HostIrContainer\n\n return fd\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear_forward(multidevice_test):\n # This is a port of CollectiveBasedOverlapTest.RowParallelLinear_Forward.\n h, s, t = 2, 3, 6\n d = multidevice_test.size\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n fd = row_parallel_linear_forward(h, d, s)\n\n inp_ref = torch.testing.make_tensor(t, h * 4, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n weight_ref = torch.testing.make_tensor(\n h, h * 4, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n # nvfuser_direct.PythonProfiler failed with host IR lowering. The main\n # reason is that HostIrContainer doesn't keep segments while SegmentProfiler\n # is still expecting data. It's unclear to me whether we should relax\n # SegmentProfiler's assumptions or stop creating them in the first place.\n with torch.profiler.profile(record_shapes=True) as prof:\n (out,) = fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n torch.testing.assert_close(out.cpu(), out_ref)\n\n matmul_events = [event for event in prof.events() if event.name == \"aten::mm\"]\n assert len(matmul_events) == s\n\n m = t // s\n n = h\n k = h * 4 // d\n for event in matmul_events:\n assert event.input_shapes == [[m, k], [k, n], [m, n]]\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\n@pytest.mark.parametrize(\"s\", [1, 2, 4])\ndef test_row_parallel_linear_forward_benchmark(multidevice_test, benchmark, s):\n # This is a port of CollectiveBasedOverlapTest.RowParallelLinear_Forward.\n h, t = 8192, 8192\n d = multidevice_test.size\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n fd = row_parallel_linear_forward(h, d, s)\n\n inp_ref = torch.randn(t, h * 4, dtype=torch.bfloat16, device=\"cpu\")\n weight_ref = torch.randn(h, h * 4, dtype=torch.bfloat16, device=\"cpu\")\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\n# The caching allocator in PyTorch can't cache buffers across streams, so we\n# have to reuse streams to avoid repeated cudaMalloc. torch.cuda.Stream() is\n# backed by a stream pool as well but I failed to find a way to set its size.\nclass StreamPool:\n def __init__(self):\n self._streams = {}\n\n def get(self, sid: int) -> torch.cuda.Stream:\n s = self._streams.get(sid)\n if s is None:\n s = torch.cuda.Stream()\n self._streams[sid] = s\n return s\n\n\ndef row_parallel_linear_forward_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n num_chunks: int,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n out = torch.empty(\n inp_shard.size(0),\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n inp_chunks = inp_shard.chunk(num_chunks)\n out_chunks = out.chunk(num_chunks)\n\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n for i, (inp_chunk, out_chunk) in enumerate(zip(inp_chunks, out_chunks)):\n worker_stream = stream_pool.get(i)\n worker_streams.append(worker_stream)\n worker_stream.wait_stream(main_stream)\n with torch.cuda.stream(worker_stream):\n torch.matmul(inp_chunk, weight_shard.T, out=out_chunk)\n work = dist.all_reduce(out_chunk, op=dist.ReduceOp.SUM, async_op=True)\n work.wait()\n\n for worker_stream in worker_streams:\n main_stream.wait_stream(worker_stream)\n\n return out\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear_forward_reference(setup_default_process_group):\n h, s, t = 2, 3, 6\n d = dist.get_world_size()\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n torch.manual_seed(0)\n inp_ref = torch.testing.make_tensor(t, h * 4, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n weight_ref = torch.testing.make_tensor(\n h, h * 4, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n out_ref = torch.nn.functional.linear(inp_ref.cuda(), weight_ref.cuda()).cpu()\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(-1)]).to_local()\n weight_shard = distribute_tensor(\n weight_ref, mesh, placements=[Shard(-1)]\n ).to_local()\n stream_pool = StreamPool()\n out = row_parallel_linear_forward_reference(inp_shard, weight_shard, s, stream_pool)\n\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\ndef test_row_parallel_linear_forward_reference_benchmark(\n setup_default_process_group, benchmark\n):\n h, s, t = 8192, 2, 8192\n d = dist.get_world_size()\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n torch.manual_seed(0)\n inp_ref = torch.randn(t, h * 4, dtype=torch.bfloat16)\n weight_ref = torch.randn(h, h * 4, dtype=torch.bfloat16)\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(-1)]).to_local()\n weight_shard = distribute_tensor(\n weight_ref, mesh, placements=[Shard(-1)]\n ).to_local()\n\n stream_pool = StreamPool()\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: row_parallel_linear_forward_reference(\n inp_shard, weight_shard, s, stream_pool\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\ndef column_parallel_linear_forward_cyclic_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n d = dist.get_world_size()\n my_rank = dist.get_rank()\n out = torch.empty(\n inp_shard.size(0) * d,\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n out_chunks = out.chunk(d)\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n buffers = [inp_shard] + [torch.empty_like(inp_shard) for _ in range(d - 1)]\n for i in range(d):\n worker_stream = stream_pool.get(i)\n worker_streams.append(worker_stream)\n worker_stream.wait_stream(main_stream)\n with torch.cuda.stream(worker_stream):\n if i > 0:\n send_op = dist.P2POp(dist.isend, buffers[i - 1], (my_rank + 1) % d)\n recv_op = dist.P2POp(dist.irecv, buffers[i], (my_rank - 1 + d) % d)\n reqs = dist.batch_isend_irecv([send_op, recv_op])\n for req in reqs:\n req.wait()\n torch.matmul(\n buffers[i],\n weight_shard.T,\n out=out_chunks[(my_rank - i + d) % d],\n )\n for worker_stream in worker_streams:\n main_stream.wait_stream(worker_stream)\n return out\n\n\ndef column_parallel_linear_forward_uncyclic_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n d = dist.get_world_size()\n my_rank = dist.get_rank()\n out = torch.empty(\n inp_shard.size(0) * d,\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n out_chunks = out.chunk(d)\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n for i in range(d):\n worker_stream = stream_pool.get(i)\n worker_streams.append(worker_stream)\n worker_stream.wait_stream(main_stream)\n with torch.cuda.stream(worker_stream):\n if i == 0:\n buffer = inp_shard\n else:\n buffer = torch.empty_like(inp_shard)\n send_op = dist.P2POp(dist.isend, inp_shard, (my_rank - i + d) % d)\n recv_op = dist.P2POp(dist.irecv, buffer, (my_rank + i) % d)\n reqs = dist.batch_isend_irecv([send_op, recv_op])\n for req in reqs:\n req.wait()\n torch.matmul(\n buffer,\n weight_shard.T,\n out=out_chunks[(my_rank + i) % d],\n )\n for worker_stream in worker_streams:\n main_stream.wait_stream(worker_stream)\n return out\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"column_parallel_linear_fn\",\n [\n column_parallel_linear_forward_cyclic_reference,\n column_parallel_linear_forward_uncyclic_reference,\n ],\n ids=[\"cyclic\", \"uncyclic\"],\n)\ndef test_column_parallel_linear_forward_reference(\n setup_default_process_group, column_parallel_linear_fn\n):\n h, t = 6, 24\n d = dist.get_world_size()\n torch.manual_seed(0)\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n if 4 * h % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {4 * h} to be divisible by world size {d}.\"\n )\n if t % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {t} to be divisible by world size {d}.\"\n )\n\n inp_ref = torch.testing.make_tensor(t, h, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(0)]).to_local()\n weight_ref = torch.testing.make_tensor(\n 4 * h, h, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n weight_shard = distribute_tensor(weight_ref, mesh, placements=[Shard(0)]).to_local()\n out_ref = torch.nn.functional.linear(inp_ref.cuda(), weight_shard)\n stream_pool = StreamPool()\n out = column_parallel_linear_fn(inp_shard, weight_shard, stream_pool)\n torch.testing.assert_close(out, out_ref)\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\n@pytest.mark.parametrize(\n \"column_parallel_linear_fn\",\n [\n column_parallel_linear_forward_cyclic_reference,\n column_parallel_linear_forward_uncyclic_reference,\n ],\n ids=[\"cyclic\", \"uncyclic\"],\n)\ndef test_column_parallel_linear_forward_reference_benchmark(\n benchmark, setup_default_process_group, column_parallel_linear_fn\n):\n h, t = 8192, 8192\n d = dist.get_world_size()\n torch.manual_seed(0)\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_ref = torch.randn(t, h, dtype=torch.bfloat16, device=\"cpu\")\n weight_ref = torch.randn(4 * h, h, dtype=torch.bfloat16, device=\"cpu\")\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(0)]).to_local()\n weight_shard = distribute_tensor(weight_ref, mesh, placements=[Shard(0)]).to_local()\n stream_pool = StreamPool()\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: column_parallel_linear_fn(inp_shard, weight_shard, stream_pool)\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\ndef column_parallel_linear_forward(h: int, d: int, parallelism: str):\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, h), contiguity=True, dtype=DataType.BFloat16)\n weight_tv = fd.define_tensor(\n (4 * h, h), contiguity=True, dtype=DataType.BFloat16\n )\n ag_out = fd.ops.set(inp_tv)\n out_tv = fd.ops.linear(ag_out, weight_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n for tv in [inp_tv, weight_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(0, d)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n ag_out.set_device_mesh(mesh)\n ag_out.outer_split(0, d)\n if parallelism == \"collective_permute\":\n ag_out.swizzle1d(0, nvfuser.ParallelType.mesh_x)\n ag_out.axis(0).parallelize(nvfuser.ParallelType.stream)\n\n # Fusion IR before segmentation will look like this:\n # [t, h]\n # /\\.\n # d\n # (deviceIdx.x)\n # |\n # | set (lowered to Broadcast/CollectivePermute. This decomposition is done\n # | manually in the definition above. It will later be done\n # | by preseg.)\n # |\n # [t, h] [4h, h]\n # /\\ /\\.\n # d d\n # | swizzle1d (if parallelism == \"collective_permute\")\n # s\n # (streamIdx)\n # |\n # | linear\n # |\n # [t, 4h, r{h}]\n # /\\ /\\.\n # s* d\n\n return fd\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\"parallelism\", [\"collective_permute\", \"broadcast\"])\ndef test_column_parallel_linear_forward(multidevice_test, parallelism: str):\n # This is a port of CollectiveBasedOverlapTest.ColumnAndSequenceParallelLinear_Forward.\n # The difference is we are using broadcast based overlapping instead of send/recv.\n h, t = 2, 24\n d = multidevice_test.size\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n if t % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {t} to be divisible by world size {d}.\"\n )\n\n fd = column_parallel_linear_forward(h, d, parallelism)\n\n inp_ref = torch.testing.make_tensor(t, h, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n weight_ref = torch.testing.make_tensor(\n 4 * h, h, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n\n out_ref = torch.nn.functional.linear(inp_ref.cuda(), weight)\n\n with torch.profiler.profile(record_shapes=True) as prof:\n (out,) = fd.execute([inp, weight], _enable_options=[\"host_ir_lowering\"])\n torch.testing.assert_close(out, out_ref)\n\n if parallelism == \"collective_permute\":\n collective_permute_events = [\n event for event in prof.events() if \"ncclDevKernel_SendRecv\" in event.name\n ]\n assert len(collective_permute_events) == (d - 1)\n else:\n broadcast_events = [\n event for event in prof.events() if \"ncclDevKernel_Broadcast\" in event.name\n ]\n assert len(broadcast_events) == (d if d > 1 else 0)\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\n@pytest.mark.parametrize(\"parallelism\", [\"collective_permute\", \"broadcast\"])\ndef test_column_parallel_linear_forward_benchmark(\n multidevice_test, benchmark, parallelism: str\n):\n # This is a port of CollectiveBasedOverlapTest.ColumnParall\n# ... truncated ...","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.row_parallel_linear_forward","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.row_parallel_linear_forward#L18-L83","kind":"function","name":"row_parallel_linear_forward","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":18,"end_line":83,"context_start_line":1,"context_end_line":103,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport os\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import distribute_tensor, Shard\n\nimport nvfuser_direct as nvfuser\nfrom .benchmark_utils import get_benchmark_fns\nfrom nvfuser_direct import DataType, FusionDefinition, CommunicatorBackend, TensorView\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\n\n\ndef row_parallel_linear_forward(\n h: int, num_devices: int, num_chunks: int\n) -> FusionDefinition:\n with FusionDefinition() as fd:\n inp = fd.define_tensor(\n shape=[-1, h * 4], contiguity=True, dtype=DataType.BFloat16\n )\n weight = fd.define_tensor(\n shape=[h, h * 4], contiguity=True, dtype=DataType.BFloat16\n )\n out = fd.ops.linear(inp, weight)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n for tv in (inp, weight):\n tv.set_device_mesh(mesh)\n\n inp.outer_split(0, num_chunks)\n inp.axis(0).parallelize(nvfuser.ParallelType.stream)\n inp.outer_split(2, mesh.size)\n inp.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n weight.outer_split(1, mesh.size)\n weight.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # Expected pre-segmentation IR:\n #\n # [t, 4h] [h, 4h]\n # /\\ /\\ /\\.\n # s* d d\n # |\n # | linear\n # |\n # r{4h}\n # / \\.\n # [t, h, d, r{4h/d}]\n # /\\.\n # s\n # |\n # | sum\n # |\n # [t, h, r{d}]\n # /\\.\n # s*\n\n # The host IR dumped with NVFUSER_DUMP=host_ir is similar to `row_parallel_linear_forward_reference`:\n #\n # %HostIrContainer { (T0_g___bfloat[istreamIdx7{3}, ideviceIdx.x9{2}, iS8{( ceilDiv(i0, 3) )}, iS10{4}] (DeviceMesh{0 1}), T1_g___bfloat[ideviceIdx.x11{2}, iS2{2}, iS12{4}] (DeviceMesh{0 1})) -> (T2_g___bfloat[istreamIdx27{3}, rdeviceIdx.x26{2}, iS28{( ceilDiv(i0, 3) )}, iS25{2}] (DeviceMesh{0 1})) :\n # T2_g___bfloat[istreamIdx27{3}, rdeviceIdx.x26{2}, iS28{( ceilDiv(i0, 3) )}, iS25{2}] (DeviceMesh{0 1}) = ALLOCATE(buffer=T2_g___bfloat[istreamIdx27{3}, rdeviceIdx.x26{2}, iS28{( ceilDiv(i0, 3) )}, iS25{2}] (DeviceMesh{0 1}), mem_type=global, size=( i0 * 2 ), zero_init=false, resets_to_zero=false)\n # Stream 0x174e5c80 = GetCurrentStream()\n # FOR i535 from 0 to 3:\n # SetCurrentStream(Stream i535)\n # Synchronize(Stream 0x174e5c80)\n # T4_l___bfloat[istreamIdx37{3}, iS38{( ceilDiv(i0, 3) )}, ideviceIdx.x35{2}, iS36{4}] (DeviceMesh{0 1}) = ShardByStream(T0_g___bfloat[istreamIdx7{3}, ideviceIdx.x9{2}, iS8{( ceilDiv(i0, 3) )}, iS10{4}] (DeviceMesh{0 1}), stream_index = i535)\n # T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1}) = ALLOCATE(buffer=T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1}), mem_type=global, size=( ( ceilDiv(i0, 3) ) * 12 ), zero_init=false, resets_to_zero=false)\n # T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1})\n # = linear(T4_l___bfloat[istreamIdx37{3}, iS38{( ceilDiv(i0, 3) )}, ideviceIdx.x35{2}, iS36{4}] (DeviceMesh{0 1}),\n # T1_g___bfloat[ideviceIdx.x11{2}, iS2{2}, iS12{4}] (DeviceMesh{0 1}) )\n # T5_l___bfloat[istreamIdx41{3}, iS42{( ceilDiv(i0, 3) )}, iS40{2}] (DeviceMesh{0 1}) = ShardByStream(T2_g___bfloat[istreamIdx27{3}, rdeviceIdx.x26{2}, iS28{( ceilDiv(i0, 3) )}, iS25{2}] (DeviceMesh{0 1}), stream_index = i535)\n # Communication 272 (type=Allreduce, team=(0 1), input=T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1}), output=T5_l___bfloat[istreamIdx41{3}, iS42{( ceilDiv(i0, 3) )}, iS40{2}] (DeviceMesh{0 1}), backend=NCCL)\n # Wait(Communication 272)\n # SetCurrentStream(Stream 0x174e5c80)\n # FOR i535 from 0 to 3:\n # Synchronize(Stream i535)\n # } // %HostIrContainer\n\n return fd\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear_forward(multidevice_test):\n # This is a port of CollectiveBasedOverlapTest.RowParallelLinear_Forward.\n h, s, t = 2, 3, 6\n d = multidevice_test.size\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n fd = row_parallel_linear_forward(h, d, s)\n\n inp_ref = torch.testing.make_tensor(t, h * 4, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n weight_ref = torch.testing.make_tensor(\n h, h * 4, dtype=torch.int32, device=\"cpu\"","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_row_parallel_linear_forward","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_row_parallel_linear_forward#L87-L128","kind":"function","name":"test_row_parallel_linear_forward","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":87,"end_line":128,"context_start_line":67,"context_end_line":148,"code":" # FOR i535 from 0 to 3:\n # SetCurrentStream(Stream i535)\n # Synchronize(Stream 0x174e5c80)\n # T4_l___bfloat[istreamIdx37{3}, iS38{( ceilDiv(i0, 3) )}, ideviceIdx.x35{2}, iS36{4}] (DeviceMesh{0 1}) = ShardByStream(T0_g___bfloat[istreamIdx7{3}, ideviceIdx.x9{2}, iS8{( ceilDiv(i0, 3) )}, iS10{4}] (DeviceMesh{0 1}), stream_index = i535)\n # T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1}) = ALLOCATE(buffer=T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1}), mem_type=global, size=( ( ceilDiv(i0, 3) ) * 12 ), zero_init=false, resets_to_zero=false)\n # T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1})\n # = linear(T4_l___bfloat[istreamIdx37{3}, iS38{( ceilDiv(i0, 3) )}, ideviceIdx.x35{2}, iS36{4}] (DeviceMesh{0 1}),\n # T1_g___bfloat[ideviceIdx.x11{2}, iS2{2}, iS12{4}] (DeviceMesh{0 1}) )\n # T5_l___bfloat[istreamIdx41{3}, iS42{( ceilDiv(i0, 3) )}, iS40{2}] (DeviceMesh{0 1}) = ShardByStream(T2_g___bfloat[istreamIdx27{3}, rdeviceIdx.x26{2}, iS28{( ceilDiv(i0, 3) )}, iS25{2}] (DeviceMesh{0 1}), stream_index = i535)\n # Communication 272 (type=Allreduce, team=(0 1), input=T3_g___bfloat[istreamIdx20{3}, ideviceIdx.x22{2}rf, iS21{( ceilDiv(i0, 3) )}, iS18{2}, rS23{4}rf] (DeviceMesh{0 1}), output=T5_l___bfloat[istreamIdx41{3}, iS42{( ceilDiv(i0, 3) )}, iS40{2}] (DeviceMesh{0 1}), backend=NCCL)\n # Wait(Communication 272)\n # SetCurrentStream(Stream 0x174e5c80)\n # FOR i535 from 0 to 3:\n # Synchronize(Stream i535)\n # } // %HostIrContainer\n\n return fd\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear_forward(multidevice_test):\n # This is a port of CollectiveBasedOverlapTest.RowParallelLinear_Forward.\n h, s, t = 2, 3, 6\n d = multidevice_test.size\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n fd = row_parallel_linear_forward(h, d, s)\n\n inp_ref = torch.testing.make_tensor(t, h * 4, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n weight_ref = torch.testing.make_tensor(\n h, h * 4, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n # nvfuser_direct.PythonProfiler failed with host IR lowering. The main\n # reason is that HostIrContainer doesn't keep segments while SegmentProfiler\n # is still expecting data. It's unclear to me whether we should relax\n # SegmentProfiler's assumptions or stop creating them in the first place.\n with torch.profiler.profile(record_shapes=True) as prof:\n (out,) = fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n torch.testing.assert_close(out.cpu(), out_ref)\n\n matmul_events = [event for event in prof.events() if event.name == \"aten::mm\"]\n assert len(matmul_events) == s\n\n m = t // s\n n = h\n k = h * 4 // d\n for event in matmul_events:\n assert event.input_shapes == [[m, k], [k, n], [m, n]]\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\n@pytest.mark.parametrize(\"s\", [1, 2, 4])\ndef test_row_parallel_linear_forward_benchmark(multidevice_test, benchmark, s):\n # This is a port of CollectiveBasedOverlapTest.RowParallelLinear_Forward.\n h, t = 8192, 8192\n d = multidevice_test.size\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n fd = row_parallel_linear_forward(h, d, s)\n\n inp_ref = torch.randn(t, h * 4, dtype=torch.bfloat16, device=\"cpu\")\n weight_ref = torch.randn(h, h * 4, dtype=torch.bfloat16, device=\"cpu\")\n","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_row_parallel_linear_forward_benchmark","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_row_parallel_linear_forward_benchmark#L134-L160","kind":"function","name":"test_row_parallel_linear_forward_benchmark","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":134,"end_line":160,"context_start_line":114,"context_end_line":180,"code":" (out,) = fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n torch.testing.assert_close(out.cpu(), out_ref)\n\n matmul_events = [event for event in prof.events() if event.name == \"aten::mm\"]\n assert len(matmul_events) == s\n\n m = t // s\n n = h\n k = h * 4 // d\n for event in matmul_events:\n assert event.input_shapes == [[m, k], [k, n], [m, n]]\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\n@pytest.mark.parametrize(\"s\", [1, 2, 4])\ndef test_row_parallel_linear_forward_benchmark(multidevice_test, benchmark, s):\n # This is a port of CollectiveBasedOverlapTest.RowParallelLinear_Forward.\n h, t = 8192, 8192\n d = multidevice_test.size\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n fd = row_parallel_linear_forward(h, d, s)\n\n inp_ref = torch.randn(t, h * 4, dtype=torch.bfloat16, device=\"cpu\")\n weight_ref = torch.randn(h, h * 4, dtype=torch.bfloat16, device=\"cpu\")\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\n# The caching allocator in PyTorch can't cache buffers across streams, so we\n# have to reuse streams to avoid repeated cudaMalloc. torch.cuda.Stream() is\n# backed by a stream pool as well but I failed to find a way to set its size.\nclass StreamPool:\n def __init__(self):\n self._streams = {}\n\n def get(self, sid: int) -> torch.cuda.Stream:\n s = self._streams.get(sid)\n if s is None:\n s = torch.cuda.Stream()\n self._streams[sid] = s\n return s\n\n\ndef row_parallel_linear_forward_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.StreamPool","uri":"program://Fuser/class/tests.python.multidevice.test_overlap.StreamPool#L166-L175","kind":"class","name":"StreamPool","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":166,"end_line":175,"context_start_line":146,"context_end_line":195,"code":" inp_ref = torch.randn(t, h * 4, dtype=torch.bfloat16, device=\"cpu\")\n weight_ref = torch.randn(h, h * 4, dtype=torch.bfloat16, device=\"cpu\")\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\n# The caching allocator in PyTorch can't cache buffers across streams, so we\n# have to reuse streams to avoid repeated cudaMalloc. torch.cuda.Stream() is\n# backed by a stream pool as well but I failed to find a way to set its size.\nclass StreamPool:\n def __init__(self):\n self._streams = {}\n\n def get(self, sid: int) -> torch.cuda.Stream:\n s = self._streams.get(sid)\n if s is None:\n s = torch.cuda.Stream()\n self._streams[sid] = s\n return s\n\n\ndef row_parallel_linear_forward_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n num_chunks: int,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n out = torch.empty(\n inp_shard.size(0),\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n inp_chunks = inp_shard.chunk(num_chunks)\n out_chunks = out.chunk(num_chunks)\n\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n for i, (inp_chunk, out_chunk) in enumerate(zip(inp_chunks, out_chunks)):","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.row_parallel_linear_forward_reference","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.row_parallel_linear_forward_reference#L178-L207","kind":"function","name":"row_parallel_linear_forward_reference","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":178,"end_line":207,"context_start_line":158,"context_end_line":227,"code":" )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\n# The caching allocator in PyTorch can't cache buffers across streams, so we\n# have to reuse streams to avoid repeated cudaMalloc. torch.cuda.Stream() is\n# backed by a stream pool as well but I failed to find a way to set its size.\nclass StreamPool:\n def __init__(self):\n self._streams = {}\n\n def get(self, sid: int) -> torch.cuda.Stream:\n s = self._streams.get(sid)\n if s is None:\n s = torch.cuda.Stream()\n self._streams[sid] = s\n return s\n\n\ndef row_parallel_linear_forward_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n num_chunks: int,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n out = torch.empty(\n inp_shard.size(0),\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n inp_chunks = inp_shard.chunk(num_chunks)\n out_chunks = out.chunk(num_chunks)\n\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n for i, (inp_chunk, out_chunk) in enumerate(zip(inp_chunks, out_chunks)):\n worker_stream = stream_pool.get(i)\n worker_streams.append(worker_stream)\n worker_stream.wait_stream(main_stream)\n with torch.cuda.stream(worker_stream):\n torch.matmul(inp_chunk, weight_shard.T, out=out_chunk)\n work = dist.all_reduce(out_chunk, op=dist.ReduceOp.SUM, async_op=True)\n work.wait()\n\n for worker_stream in worker_streams:\n main_stream.wait_stream(worker_stream)\n\n return out\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear_forward_reference(setup_default_process_group):\n h, s, t = 2, 3, 6\n d = dist.get_world_size()\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n torch.manual_seed(0)\n inp_ref = torch.testing.make_tensor(t, h * 4, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n weight_ref = torch.testing.make_tensor(\n h, h * 4, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n out_ref = torch.nn.functional.linear(inp_ref.cuda(), weight_ref.cuda()).cpu()","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_row_parallel_linear_forward_reference","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_row_parallel_linear_forward_reference#L211-L237","kind":"function","name":"test_row_parallel_linear_forward_reference","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":211,"end_line":237,"context_start_line":191,"context_end_line":257,"code":" out_chunks = out.chunk(num_chunks)\n\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n for i, (inp_chunk, out_chunk) in enumerate(zip(inp_chunks, out_chunks)):\n worker_stream = stream_pool.get(i)\n worker_streams.append(worker_stream)\n worker_stream.wait_stream(main_stream)\n with torch.cuda.stream(worker_stream):\n torch.matmul(inp_chunk, weight_shard.T, out=out_chunk)\n work = dist.all_reduce(out_chunk, op=dist.ReduceOp.SUM, async_op=True)\n work.wait()\n\n for worker_stream in worker_streams:\n main_stream.wait_stream(worker_stream)\n\n return out\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear_forward_reference(setup_default_process_group):\n h, s, t = 2, 3, 6\n d = dist.get_world_size()\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n torch.manual_seed(0)\n inp_ref = torch.testing.make_tensor(t, h * 4, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n weight_ref = torch.testing.make_tensor(\n h, h * 4, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n out_ref = torch.nn.functional.linear(inp_ref.cuda(), weight_ref.cuda()).cpu()\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(-1)]).to_local()\n weight_shard = distribute_tensor(\n weight_ref, mesh, placements=[Shard(-1)]\n ).to_local()\n stream_pool = StreamPool()\n out = row_parallel_linear_forward_reference(inp_shard, weight_shard, s, stream_pool)\n\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\ndef test_row_parallel_linear_forward_reference_benchmark(\n setup_default_process_group, benchmark\n):\n h, s, t = 8192, 2, 8192\n d = dist.get_world_size()\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n torch.manual_seed(0)\n inp_ref = torch.randn(t, h * 4, dtype=torch.bfloat16)\n weight_ref = torch.randn(h, h * 4, dtype=torch.bfloat16)\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_row_parallel_linear_forward_reference_benchmark","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_row_parallel_linear_forward_reference_benchmark#L242-L270","kind":"function","name":"test_row_parallel_linear_forward_reference_benchmark","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":242,"end_line":270,"context_start_line":222,"context_end_line":290,"code":" torch.bfloat16\n )\n weight_ref = torch.testing.make_tensor(\n h, h * 4, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n out_ref = torch.nn.functional.linear(inp_ref.cuda(), weight_ref.cuda()).cpu()\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(-1)]).to_local()\n weight_shard = distribute_tensor(\n weight_ref, mesh, placements=[Shard(-1)]\n ).to_local()\n stream_pool = StreamPool()\n out = row_parallel_linear_forward_reference(inp_shard, weight_shard, s, stream_pool)\n\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\ndef test_row_parallel_linear_forward_reference_benchmark(\n setup_default_process_group, benchmark\n):\n h, s, t = 8192, 2, 8192\n d = dist.get_world_size()\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Row-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n assert t % s == 0\n\n torch.manual_seed(0)\n inp_ref = torch.randn(t, h * 4, dtype=torch.bfloat16)\n weight_ref = torch.randn(h, h * 4, dtype=torch.bfloat16)\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(-1)]).to_local()\n weight_shard = distribute_tensor(\n weight_ref, mesh, placements=[Shard(-1)]\n ).to_local()\n\n stream_pool = StreamPool()\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: row_parallel_linear_forward_reference(\n inp_shard, weight_shard, s, stream_pool\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\ndef column_parallel_linear_forward_cyclic_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n d = dist.get_world_size()\n my_rank = dist.get_rank()\n out = torch.empty(\n inp_shard.size(0) * d,\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n out_chunks = out.chunk(d)\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n buffers = [inp_shard] + [torch.empty_like(inp_shard) for _ in range(d - 1)]\n for i in range(d):","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.column_parallel_linear_forward_cyclic_reference","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.column_parallel_linear_forward_cyclic_reference#L273-L308","kind":"function","name":"column_parallel_linear_forward_cyclic_reference","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":273,"end_line":308,"context_start_line":253,"context_end_line":328,"code":" torch.manual_seed(0)\n inp_ref = torch.randn(t, h * 4, dtype=torch.bfloat16)\n weight_ref = torch.randn(h, h * 4, dtype=torch.bfloat16)\n\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(-1)]).to_local()\n weight_shard = distribute_tensor(\n weight_ref, mesh, placements=[Shard(-1)]\n ).to_local()\n\n stream_pool = StreamPool()\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: row_parallel_linear_forward_reference(\n inp_shard, weight_shard, s, stream_pool\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\ndef column_parallel_linear_forward_cyclic_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n d = dist.get_world_size()\n my_rank = dist.get_rank()\n out = torch.empty(\n inp_shard.size(0) * d,\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n out_chunks = out.chunk(d)\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n buffers = [inp_shard] + [torch.empty_like(inp_shard) for _ in range(d - 1)]\n for i in range(d):\n worker_stream = stream_pool.get(i)\n worker_streams.append(worker_stream)\n worker_stream.wait_stream(main_stream)\n with torch.cuda.stream(worker_stream):\n if i > 0:\n send_op = dist.P2POp(dist.isend, buffers[i - 1], (my_rank + 1) % d)\n recv_op = dist.P2POp(dist.irecv, buffers[i], (my_rank - 1 + d) % d)\n reqs = dist.batch_isend_irecv([send_op, recv_op])\n for req in reqs:\n req.wait()\n torch.matmul(\n buffers[i],\n weight_shard.T,\n out=out_chunks[(my_rank - i + d) % d],\n )\n for worker_stream in worker_streams:\n main_stream.wait_stream(worker_stream)\n return out\n\n\ndef column_parallel_linear_forward_uncyclic_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n d = dist.get_world_size()\n my_rank = dist.get_rank()\n out = torch.empty(\n inp_shard.size(0) * d,\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n out_chunks = out.chunk(d)\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n for i in range(d):\n worker_stream = stream_pool.get(i)","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.column_parallel_linear_forward_uncyclic_reference","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.column_parallel_linear_forward_uncyclic_reference#L311-L348","kind":"function","name":"column_parallel_linear_forward_uncyclic_reference","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":311,"end_line":348,"context_start_line":291,"context_end_line":368,"code":" worker_stream = stream_pool.get(i)\n worker_streams.append(worker_stream)\n worker_stream.wait_stream(main_stream)\n with torch.cuda.stream(worker_stream):\n if i > 0:\n send_op = dist.P2POp(dist.isend, buffers[i - 1], (my_rank + 1) % d)\n recv_op = dist.P2POp(dist.irecv, buffers[i], (my_rank - 1 + d) % d)\n reqs = dist.batch_isend_irecv([send_op, recv_op])\n for req in reqs:\n req.wait()\n torch.matmul(\n buffers[i],\n weight_shard.T,\n out=out_chunks[(my_rank - i + d) % d],\n )\n for worker_stream in worker_streams:\n main_stream.wait_stream(worker_stream)\n return out\n\n\ndef column_parallel_linear_forward_uncyclic_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n d = dist.get_world_size()\n my_rank = dist.get_rank()\n out = torch.empty(\n inp_shard.size(0) * d,\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n out_chunks = out.chunk(d)\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n for i in range(d):\n worker_stream = stream_pool.get(i)\n worker_streams.append(worker_stream)\n worker_stream.wait_stream(main_stream)\n with torch.cuda.stream(worker_stream):\n if i == 0:\n buffer = inp_shard\n else:\n buffer = torch.empty_like(inp_shard)\n send_op = dist.P2POp(dist.isend, inp_shard, (my_rank - i + d) % d)\n recv_op = dist.P2POp(dist.irecv, buffer, (my_rank + i) % d)\n reqs = dist.batch_isend_irecv([send_op, recv_op])\n for req in reqs:\n req.wait()\n torch.matmul(\n buffer,\n weight_shard.T,\n out=out_chunks[(my_rank + i) % d],\n )\n for worker_stream in worker_streams:\n main_stream.wait_stream(worker_stream)\n return out\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"column_parallel_linear_fn\",\n [\n column_parallel_linear_forward_cyclic_reference,\n column_parallel_linear_forward_uncyclic_reference,\n ],\n ids=[\"cyclic\", \"uncyclic\"],\n)\ndef test_column_parallel_linear_forward_reference(\n setup_default_process_group, column_parallel_linear_fn\n):\n h, t = 6, 24\n d = dist.get_world_size()\n torch.manual_seed(0)\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n if 4 * h % d != 0:","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_column_parallel_linear_forward_reference","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_column_parallel_linear_forward_reference#L360-L388","kind":"function","name":"test_column_parallel_linear_forward_reference","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":360,"end_line":388,"context_start_line":340,"context_end_line":408,"code":" req.wait()\n torch.matmul(\n buffer,\n weight_shard.T,\n out=out_chunks[(my_rank + i) % d],\n )\n for worker_stream in worker_streams:\n main_stream.wait_stream(worker_stream)\n return out\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"column_parallel_linear_fn\",\n [\n column_parallel_linear_forward_cyclic_reference,\n column_parallel_linear_forward_uncyclic_reference,\n ],\n ids=[\"cyclic\", \"uncyclic\"],\n)\ndef test_column_parallel_linear_forward_reference(\n setup_default_process_group, column_parallel_linear_fn\n):\n h, t = 6, 24\n d = dist.get_world_size()\n torch.manual_seed(0)\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n if 4 * h % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {4 * h} to be divisible by world size {d}.\"\n )\n if t % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {t} to be divisible by world size {d}.\"\n )\n\n inp_ref = torch.testing.make_tensor(t, h, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(0)]).to_local()\n weight_ref = torch.testing.make_tensor(\n 4 * h, h, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n weight_shard = distribute_tensor(weight_ref, mesh, placements=[Shard(0)]).to_local()\n out_ref = torch.nn.functional.linear(inp_ref.cuda(), weight_shard)\n stream_pool = StreamPool()\n out = column_parallel_linear_fn(inp_shard, weight_shard, stream_pool)\n torch.testing.assert_close(out, out_ref)\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\n@pytest.mark.parametrize(\n \"column_parallel_linear_fn\",\n [\n column_parallel_linear_forward_cyclic_reference,\n column_parallel_linear_forward_uncyclic_reference,\n ],\n ids=[\"cyclic\", \"uncyclic\"],\n)\ndef test_column_parallel_linear_forward_reference_benchmark(\n benchmark, setup_default_process_group, column_parallel_linear_fn\n):\n h, t = 8192, 8192\n d = dist.get_world_size()\n torch.manual_seed(0)\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_ref = torch.randn(t, h, dtype=torch.bfloat16, device=\"cpu\")","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_column_parallel_linear_forward_reference_benchmark","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_column_parallel_linear_forward_reference_benchmark#L401-L417","kind":"function","name":"test_column_parallel_linear_forward_reference_benchmark","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":401,"end_line":417,"context_start_line":381,"context_end_line":437,"code":" weight_ref = torch.testing.make_tensor(\n 4 * h, h, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n weight_shard = distribute_tensor(weight_ref, mesh, placements=[Shard(0)]).to_local()\n out_ref = torch.nn.functional.linear(inp_ref.cuda(), weight_shard)\n stream_pool = StreamPool()\n out = column_parallel_linear_fn(inp_shard, weight_shard, stream_pool)\n torch.testing.assert_close(out, out_ref)\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\n@pytest.mark.parametrize(\n \"column_parallel_linear_fn\",\n [\n column_parallel_linear_forward_cyclic_reference,\n column_parallel_linear_forward_uncyclic_reference,\n ],\n ids=[\"cyclic\", \"uncyclic\"],\n)\ndef test_column_parallel_linear_forward_reference_benchmark(\n benchmark, setup_default_process_group, column_parallel_linear_fn\n):\n h, t = 8192, 8192\n d = dist.get_world_size()\n torch.manual_seed(0)\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_ref = torch.randn(t, h, dtype=torch.bfloat16, device=\"cpu\")\n weight_ref = torch.randn(4 * h, h, dtype=torch.bfloat16, device=\"cpu\")\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(0)]).to_local()\n weight_shard = distribute_tensor(weight_ref, mesh, placements=[Shard(0)]).to_local()\n stream_pool = StreamPool()\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: column_parallel_linear_fn(inp_shard, weight_shard, stream_pool)\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\ndef column_parallel_linear_forward(h: int, d: int, parallelism: str):\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, h), contiguity=True, dtype=DataType.BFloat16)\n weight_tv = fd.define_tensor(\n (4 * h, h), contiguity=True, dtype=DataType.BFloat16\n )\n ag_out = fd.ops.set(inp_tv)\n out_tv = fd.ops.linear(ag_out, weight_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n for tv in [inp_tv, weight_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(0, d)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n ag_out.set_device_mesh(mesh)","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.column_parallel_linear_forward","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.column_parallel_linear_forward#L420-L466","kind":"function","name":"column_parallel_linear_forward","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":420,"end_line":466,"context_start_line":400,"context_end_line":486,"code":")\ndef test_column_parallel_linear_forward_reference_benchmark(\n benchmark, setup_default_process_group, column_parallel_linear_fn\n):\n h, t = 8192, 8192\n d = dist.get_world_size()\n torch.manual_seed(0)\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n inp_ref = torch.randn(t, h, dtype=torch.bfloat16, device=\"cpu\")\n weight_ref = torch.randn(4 * h, h, dtype=torch.bfloat16, device=\"cpu\")\n inp_shard = distribute_tensor(inp_ref, mesh, placements=[Shard(0)]).to_local()\n weight_shard = distribute_tensor(weight_ref, mesh, placements=[Shard(0)]).to_local()\n stream_pool = StreamPool()\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: column_parallel_linear_fn(inp_shard, weight_shard, stream_pool)\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\ndef column_parallel_linear_forward(h: int, d: int, parallelism: str):\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, h), contiguity=True, dtype=DataType.BFloat16)\n weight_tv = fd.define_tensor(\n (4 * h, h), contiguity=True, dtype=DataType.BFloat16\n )\n ag_out = fd.ops.set(inp_tv)\n out_tv = fd.ops.linear(ag_out, weight_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n for tv in [inp_tv, weight_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(0, d)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n ag_out.set_device_mesh(mesh)\n ag_out.outer_split(0, d)\n if parallelism == \"collective_permute\":\n ag_out.swizzle1d(0, nvfuser.ParallelType.mesh_x)\n ag_out.axis(0).parallelize(nvfuser.ParallelType.stream)\n\n # Fusion IR before segmentation will look like this:\n # [t, h]\n # /\\.\n # d\n # (deviceIdx.x)\n # |\n # | set (lowered to Broadcast/CollectivePermute. This decomposition is done\n # | manually in the definition above. It will later be done\n # | by preseg.)\n # |\n # [t, h] [4h, h]\n # /\\ /\\.\n # d d\n # | swizzle1d (if parallelism == \"collective_permute\")\n # s\n # (streamIdx)\n # |\n # | linear\n # |\n # [t, 4h, r{h}]\n # /\\ /\\.\n # s* d\n\n return fd\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\"parallelism\", [\"collective_permute\", \"broadcast\"])\ndef test_column_parallel_linear_forward(multidevice_test, parallelism: str):\n # This is a port of CollectiveBasedOverlapTest.ColumnAndSequenceParallelLinear_Forward.\n # The difference is we are using broadcast based overlapping instead of send/recv.\n h, t = 2, 24\n d = multidevice_test.size\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n if t % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {t} to be divisible by world size {d}.\"\n )\n\n fd = column_parallel_linear_forward(h, d, parallelism)\n","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_column_parallel_linear_forward","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_column_parallel_linear_forward#L471-L512","kind":"function","name":"test_column_parallel_linear_forward","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":471,"end_line":512,"context_start_line":451,"context_end_line":532,"code":" # | by preseg.)\n # |\n # [t, h] [4h, h]\n # /\\ /\\.\n # d d\n # | swizzle1d (if parallelism == \"collective_permute\")\n # s\n # (streamIdx)\n # |\n # | linear\n # |\n # [t, 4h, r{h}]\n # /\\ /\\.\n # s* d\n\n return fd\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\"parallelism\", [\"collective_permute\", \"broadcast\"])\ndef test_column_parallel_linear_forward(multidevice_test, parallelism: str):\n # This is a port of CollectiveBasedOverlapTest.ColumnAndSequenceParallelLinear_Forward.\n # The difference is we are using broadcast based overlapping instead of send/recv.\n h, t = 2, 24\n d = multidevice_test.size\n if (h * 4) % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {h * 4} to be divisible by world size {d}.\"\n )\n if t % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {t} to be divisible by world size {d}.\"\n )\n\n fd = column_parallel_linear_forward(h, d, parallelism)\n\n inp_ref = torch.testing.make_tensor(t, h, dtype=torch.int32, device=\"cpu\").to(\n torch.bfloat16\n )\n weight_ref = torch.testing.make_tensor(\n 4 * h, h, dtype=torch.int32, device=\"cpu\"\n ).to(torch.bfloat16)\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n\n out_ref = torch.nn.functional.linear(inp_ref.cuda(), weight)\n\n with torch.profiler.profile(record_shapes=True) as prof:\n (out,) = fd.execute([inp, weight], _enable_options=[\"host_ir_lowering\"])\n torch.testing.assert_close(out, out_ref)\n\n if parallelism == \"collective_permute\":\n collective_permute_events = [\n event for event in prof.events() if \"ncclDevKernel_SendRecv\" in event.name\n ]\n assert len(collective_permute_events) == (d - 1)\n else:\n broadcast_events = [\n event for event in prof.events() if \"ncclDevKernel_Broadcast\" in event.name\n ]\n assert len(broadcast_events) == (d if d > 1 else 0)\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\n@pytest.mark.parametrize(\"parallelism\", [\"collective_permute\", \"broadcast\"])\ndef test_column_parallel_linear_forward_benchmark(\n multidevice_test, benchmark, parallelism: str\n):\n # This is a port of CollectiveBasedOverlapTest.ColumnParallelLinear_Forward.\n h, t = 8192, 8192\n d = multidevice_test.size\n if (4 * h) % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {4 * h} to be divisible by world size {d}.\"\n )\n if t % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {t} to be divisible by world size {d}.\"\n )\n","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_column_parallel_linear_forward_benchmark","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_column_parallel_linear_forward_benchmark#L518-L548","kind":"function","name":"test_column_parallel_linear_forward_benchmark","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":518,"end_line":548,"context_start_line":498,"context_end_line":568,"code":"\n with torch.profiler.profile(record_shapes=True) as prof:\n (out,) = fd.execute([inp, weight], _enable_options=[\"host_ir_lowering\"])\n torch.testing.assert_close(out, out_ref)\n\n if parallelism == \"collective_permute\":\n collective_permute_events = [\n event for event in prof.events() if \"ncclDevKernel_SendRecv\" in event.name\n ]\n assert len(collective_permute_events) == (d - 1)\n else:\n broadcast_events = [\n event for event in prof.events() if \"ncclDevKernel_Broadcast\" in event.name\n ]\n assert len(broadcast_events) == (d if d > 1 else 0)\n\n\n@pytest.mark.mpi\n@pytest.mark.benchmark\n@pytest.mark.parametrize(\"parallelism\", [\"collective_permute\", \"broadcast\"])\ndef test_column_parallel_linear_forward_benchmark(\n multidevice_test, benchmark, parallelism: str\n):\n # This is a port of CollectiveBasedOverlapTest.ColumnParallelLinear_Forward.\n h, t = 8192, 8192\n d = multidevice_test.size\n if (4 * h) % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {4 * h} to be divisible by world size {d}.\"\n )\n if t % d != 0:\n pytest.skip(\n f\"Column-parallel linear requires {t} to be divisible by world size {d}.\"\n )\n\n fd = column_parallel_linear_forward(h, d, parallelism)\n\n inp_ref = torch.randn(t, h, dtype=torch.bfloat16, device=\"cpu\")\n weight_ref = torch.randn(4 * h, h, dtype=torch.bfloat16, device=\"cpu\")\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\"backend_type\", [CommunicatorBackend.nccl])\n@pytest.mark.parametrize(\"s\", [1, 8])\ndef test_overlap_allgather_matmul_stream_outermost(\n multidevice_test, benchmark, backend_type, s\n):\n def fusion_definition(fd, m, k, n, s, d) -> list[TensorView]:\n x = fd.define_tensor(\n shape=[s, d, m // (s * d), k], contiguity=True, dtype=DataType.BFloat16\n )\n weight = fd.define_tensor(\n shape=[n, k], contiguity=True, dtype=DataType.BFloat16\n )\n bias = fd.define_tensor(shape=[n], contiguity=True, dtype=DataType.BFloat16)\n\n # [s, d, m//(s*d), n]\n out = fd.ops.linear(x, weight, bias)\n","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_overlap_allgather_matmul_stream_outermost","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_overlap_allgather_matmul_stream_outermost#L554-L616","kind":"function","name":"test_overlap_allgather_matmul_stream_outermost","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":554,"end_line":616,"context_start_line":534,"context_end_line":636,"code":"\n inp_ref = torch.randn(t, h, dtype=torch.bfloat16, device=\"cpu\")\n weight_ref = torch.randn(4 * h, h, dtype=torch.bfloat16, device=\"cpu\")\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\"backend_type\", [CommunicatorBackend.nccl])\n@pytest.mark.parametrize(\"s\", [1, 8])\ndef test_overlap_allgather_matmul_stream_outermost(\n multidevice_test, benchmark, backend_type, s\n):\n def fusion_definition(fd, m, k, n, s, d) -> list[TensorView]:\n x = fd.define_tensor(\n shape=[s, d, m // (s * d), k], contiguity=True, dtype=DataType.BFloat16\n )\n weight = fd.define_tensor(\n shape=[n, k], contiguity=True, dtype=DataType.BFloat16\n )\n bias = fd.define_tensor(shape=[n], contiguity=True, dtype=DataType.BFloat16)\n\n # [s, d, m//(s*d), n]\n out = fd.ops.linear(x, weight, bias)\n\n fd.add_output(out)\n return [x, weight, bias, out]\n\n def multidevice_schedule(fd, tensors, num_devices) -> None:\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n for tv in tensors:\n tv.set_device_mesh(mesh)\n\n x, weight, bias, out = tensors\n x.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n out.axis(0).parallelize(nvfuser.ParallelType.stream)\n\n N_WARMUPS, N_ITERATIONS = 5, 25\n m, k, n, d = 2**10, 2**10, 2**10, multidevice_test.size\n assert m % (s * d) == 0\n\n os.environ[\"UCC_CL_BASIC_TLS\"] = \"nccl\"\n x_unsharded = torch.testing.make_tensor(\n s, d, m // (s * d), k, dtype=torch.bfloat16, device=\"cpu\"\n )\n x = multidevice_test.shard_tensor_1d(\n x_unsharded,\n 1,\n nvfuser.multidevice.DeviceMesh(range(multidevice_test.size)),\n )\n weight = torch.testing.make_tensor(n, k, dtype=torch.bfloat16, device=\"cuda\")\n bias = torch.testing.make_tensor(n, dtype=torch.bfloat16, device=\"cuda\")\n ins = [x, weight, bias]\n out_ref = torch.nn.functional.linear(x_unsharded, weight.cpu(), bias.cpu())\n\n with FusionDefinition() as fd:\n tensors = fusion_definition(fd, m, k, n, s, d)\n multidevice_schedule(fd, tensors, d)\n\n params = nvfuser.multidevice.MultiDeviceExecutorParams()\n params.backend_type = backend_type\n multidevice_executor = nvfuser.multidevice.MultiDeviceExecutor(fd.fusion, params)\n\n # warmup\n for _ in range(N_WARMUPS):\n outputs = multidevice_executor.run(ins)\n out = outputs[0].cpu()\n assert out.dtype == torch.bfloat16\n assert out.shape == torch.Size([s, d, m // (s * d), n])\n torch.testing.assert_close(out, out_ref, rtol=1e-1, atol=1e-1)\n\n # benchmark\n benchmark.pedantic(lambda: multidevice_executor.run(ins), rounds=N_ITERATIONS)\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.nccl, CommunicatorBackend.cuda]\n)\ndef test_overlap_allgather_matmul_shard_outermost(\n multidevice_test, benchmark, backend_type\n):\n def fusion_definition(fd, m, k, n, d) -> list[TensorView]:\n x = fd.define_tensor(\n shape=[d, m // d, k], contiguity=True, dtype=DataType.BFloat16\n )\n weight = fd.define_tensor(\n shape=[n, k], contiguity=True, dtype=DataType.BFloat16\n )\n bias = fd.define_tensor(shape=[n], contiguity=True, dtype=DataType.BFloat16)\n\n # [d, m//d, n]\n out = fd.ops.linear(x, weight, bias)","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_overlap_allgather_matmul_shard_outermost","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_overlap_allgather_matmul_shard_outermost#L623-L687","kind":"function","name":"test_overlap_allgather_matmul_shard_outermost","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":623,"end_line":687,"context_start_line":603,"context_end_line":707,"code":" params = nvfuser.multidevice.MultiDeviceExecutorParams()\n params.backend_type = backend_type\n multidevice_executor = nvfuser.multidevice.MultiDeviceExecutor(fd.fusion, params)\n\n # warmup\n for _ in range(N_WARMUPS):\n outputs = multidevice_executor.run(ins)\n out = outputs[0].cpu()\n assert out.dtype == torch.bfloat16\n assert out.shape == torch.Size([s, d, m // (s * d), n])\n torch.testing.assert_close(out, out_ref, rtol=1e-1, atol=1e-1)\n\n # benchmark\n benchmark.pedantic(lambda: multidevice_executor.run(ins), rounds=N_ITERATIONS)\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.nccl, CommunicatorBackend.cuda]\n)\ndef test_overlap_allgather_matmul_shard_outermost(\n multidevice_test, benchmark, backend_type\n):\n def fusion_definition(fd, m, k, n, d) -> list[TensorView]:\n x = fd.define_tensor(\n shape=[d, m // d, k], contiguity=True, dtype=DataType.BFloat16\n )\n weight = fd.define_tensor(\n shape=[n, k], contiguity=True, dtype=DataType.BFloat16\n )\n bias = fd.define_tensor(shape=[n], contiguity=True, dtype=DataType.BFloat16)\n\n # [d, m//d, n]\n out = fd.ops.linear(x, weight, bias)\n\n fd.add_output(out)\n return [x, weight, bias, out]\n\n def multidevice_schedule(fd, tensors, num_devices) -> None:\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n for tv in tensors:\n tv.set_device_mesh(mesh)\n\n x, weight, bias, out = tensors\n x.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n out.axis(0).parallelize(nvfuser.ParallelType.stream)\n\n N_WARMUPS, N_ITERATIONS = 5, 25\n m, k, n, d = 2**10, 2**10, 2**10, multidevice_test.size\n assert m % d == 0\n\n os.environ[\"UCC_CL_BASIC_TLS\"] = \"nccl\"\n x_unsharded = torch.testing.make_tensor(\n d, m // d, k, dtype=torch.bfloat16, device=\"cpu\"\n )\n x = multidevice_test.shard_tensor_1d(\n x_unsharded,\n 0,\n nvfuser.multidevice.DeviceMesh(range(multidevice_test.size)),\n )\n weight = torch.testing.make_tensor(n, k, dtype=torch.bfloat16, device=\"cuda\")\n bias = torch.testing.make_tensor(n, dtype=torch.bfloat16, device=\"cuda\")\n ins = [x, weight, bias]\n out_ref = torch.nn.functional.linear(x_unsharded, weight.cpu(), bias.cpu())\n\n with FusionDefinition() as fd:\n tensors = fusion_definition(fd, m, k, n, d)\n multidevice_schedule(fd, tensors, d)\n\n params = nvfuser.multidevice.MultiDeviceExecutorParams()\n params.backend_type = backend_type\n params.use_allocation_cache = True\n params.offset_stream_indexing_by_rank = True\n multidevice_executor = nvfuser.multidevice.MultiDeviceExecutor(fd.fusion, params)\n\n # warmup\n for _ in range(N_WARMUPS):\n outputs = multidevice_executor.run(ins)\n out = outputs[0].cpu()\n assert out.dtype == torch.bfloat16\n assert out.shape == torch.Size([d, m // d, n])\n torch.testing.assert_close(out, out_ref, rtol=1e-1, atol=1e-1)\n\n # benchmark\n benchmark.pedantic(lambda: multidevice_executor.run(ins), rounds=N_ITERATIONS)\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.nccl, CommunicatorBackend.cuda]\n)\ndef test_allgather_matmul_no_overlap(multidevice_test, backend_type):\n def fusion_definition(\n fd: FusionDefinition, m: int, k: int, n: int, d: int\n ) -> list[TensorView]:\n a = fd.define_tensor(\n shape=[d, m // d, k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n b = fd.define_tensor(\n shape=[k, n],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.test_allgather_matmul_no_overlap","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.test_allgather_matmul_no_overlap#L694-L749","kind":"function","name":"test_allgather_matmul_no_overlap","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":694,"end_line":749,"context_start_line":674,"context_end_line":749,"code":" params.use_allocation_cache = True\n params.offset_stream_indexing_by_rank = True\n multidevice_executor = nvfuser.multidevice.MultiDeviceExecutor(fd.fusion, params)\n\n # warmup\n for _ in range(N_WARMUPS):\n outputs = multidevice_executor.run(ins)\n out = outputs[0].cpu()\n assert out.dtype == torch.bfloat16\n assert out.shape == torch.Size([d, m // d, n])\n torch.testing.assert_close(out, out_ref, rtol=1e-1, atol=1e-1)\n\n # benchmark\n benchmark.pedantic(lambda: multidevice_executor.run(ins), rounds=N_ITERATIONS)\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.nccl, CommunicatorBackend.cuda]\n)\ndef test_allgather_matmul_no_overlap(multidevice_test, backend_type):\n def fusion_definition(\n fd: FusionDefinition, m: int, k: int, n: int, d: int\n ) -> list[TensorView]:\n a = fd.define_tensor(\n shape=[d, m // d, k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n b = fd.define_tensor(\n shape=[k, n],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n\n c = fd.ops.matmul(a, b)\n if backend_type == CommunicatorBackend.cuda:\n c.set_memory_type(nvfuser.MemoryType.symmetric)\n fd.add_output(c)\n return [a, b, c]\n\n def multidevice_schedule(tensors: list[TensorView], num_devices: int) -> None:\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n for tv in tensors:\n tv.set_device_mesh(mesh)\n\n a, _, _ = tensors\n a.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n d = multidevice_test.size\n m, k, n = 128, 64, 96\n if m % d != 0:\n pytest.skip(f\"m ({m}) must be divisible by world size ({d}).\")\n\n dtype = torch.bfloat16\n with FusionDefinition() as fd:\n tensors = fusion_definition(fd, m, k, n, d)\n multidevice_schedule(tensors, d)\n\n a_ref = torch.testing.make_tensor(d, m // d, k, dtype=torch.int32, device=\"cpu\").to(\n dtype\n )\n b_ref = torch.testing.make_tensor(k, n, dtype=torch.int32, device=\"cpu\").to(dtype)\n\n a = multidevice_test.shard_tensor(a_ref, fd.fusion.inputs()[0])\n b = b_ref.cuda(multidevice_test.local_rank)\n\n params = nvfuser.multidevice.MultiDeviceExecutorParams()\n params.backend_type = backend_type\n multidevice_executor = nvfuser.multidevice.MultiDeviceExecutor(fd.fusion, params)\n\n # Set a new CUDA stream because cudaMemcpyBatchAsync does not support default stream\n with torch.cuda.Stream(device=multidevice_test.local_rank):\n (out,) = multidevice_executor.run([a, b])\n out_ref = torch.matmul(a_ref, b_ref)\n torch.testing.assert_close(out.cpu(), out_ref)","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.__init__","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.__init__#L167-L168","kind":"function","name":"__init__","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":167,"end_line":168,"context_start_line":147,"context_end_line":188,"code":" weight_ref = torch.randn(h, h * 4, dtype=torch.bfloat16, device=\"cpu\")\n\n inp = multidevice_test.shard_tensor(inp_ref, fd.fusion.inputs()[0])\n weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\n# The caching allocator in PyTorch can't cache buffers across streams, so we\n# have to reuse streams to avoid repeated cudaMalloc. torch.cuda.Stream() is\n# backed by a stream pool as well but I failed to find a way to set its size.\nclass StreamPool:\n def __init__(self):\n self._streams = {}\n\n def get(self, sid: int) -> torch.cuda.Stream:\n s = self._streams.get(sid)\n if s is None:\n s = torch.cuda.Stream()\n self._streams[sid] = s\n return s\n\n\ndef row_parallel_linear_forward_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n num_chunks: int,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n out = torch.empty(\n inp_shard.size(0),\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.get","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.get#L170-L175","kind":"function","name":"get","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":170,"end_line":175,"context_start_line":150,"context_end_line":195,"code":" weight = multidevice_test.shard_tensor(weight_ref, fd.fusion.inputs()[1])\n\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: fd.execute(\n [inp, weight],\n _enable_options=[\"host_ir_lowering\"],\n _disable_options=[\"infer_contiguity\"],\n )\n )\n warmup_fn()\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\n# The caching allocator in PyTorch can't cache buffers across streams, so we\n# have to reuse streams to avoid repeated cudaMalloc. torch.cuda.Stream() is\n# backed by a stream pool as well but I failed to find a way to set its size.\nclass StreamPool:\n def __init__(self):\n self._streams = {}\n\n def get(self, sid: int) -> torch.cuda.Stream:\n s = self._streams.get(sid)\n if s is None:\n s = torch.cuda.Stream()\n self._streams[sid] = s\n return s\n\n\ndef row_parallel_linear_forward_reference(\n inp_shard: torch.Tensor,\n weight_shard: torch.Tensor,\n num_chunks: int,\n stream_pool: StreamPool,\n) -> torch.Tensor:\n out = torch.empty(\n inp_shard.size(0),\n weight_shard.size(0),\n device=\"cuda\",\n dtype=inp_shard.dtype,\n )\n inp_chunks = inp_shard.chunk(num_chunks)\n out_chunks = out.chunk(num_chunks)\n\n main_stream = torch.cuda.current_stream()\n worker_streams = []\n for i, (inp_chunk, out_chunk) in enumerate(zip(inp_chunks, out_chunks)):","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.fusion_definition","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.fusion_definition#L695-L713","kind":"function","name":"fusion_definition","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":695,"end_line":713,"context_start_line":675,"context_end_line":733,"code":" params.offset_stream_indexing_by_rank = True\n multidevice_executor = nvfuser.multidevice.MultiDeviceExecutor(fd.fusion, params)\n\n # warmup\n for _ in range(N_WARMUPS):\n outputs = multidevice_executor.run(ins)\n out = outputs[0].cpu()\n assert out.dtype == torch.bfloat16\n assert out.shape == torch.Size([d, m // d, n])\n torch.testing.assert_close(out, out_ref, rtol=1e-1, atol=1e-1)\n\n # benchmark\n benchmark.pedantic(lambda: multidevice_executor.run(ins), rounds=N_ITERATIONS)\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.nccl, CommunicatorBackend.cuda]\n)\ndef test_allgather_matmul_no_overlap(multidevice_test, backend_type):\n def fusion_definition(\n fd: FusionDefinition, m: int, k: int, n: int, d: int\n ) -> list[TensorView]:\n a = fd.define_tensor(\n shape=[d, m // d, k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n b = fd.define_tensor(\n shape=[k, n],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n\n c = fd.ops.matmul(a, b)\n if backend_type == CommunicatorBackend.cuda:\n c.set_memory_type(nvfuser.MemoryType.symmetric)\n fd.add_output(c)\n return [a, b, c]\n\n def multidevice_schedule(tensors: list[TensorView], num_devices: int) -> None:\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n for tv in tensors:\n tv.set_device_mesh(mesh)\n\n a, _, _ = tensors\n a.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n d = multidevice_test.size\n m, k, n = 128, 64, 96\n if m % d != 0:\n pytest.skip(f\"m ({m}) must be divisible by world size ({d}).\")\n\n dtype = torch.bfloat16\n with FusionDefinition() as fd:\n tensors = fusion_definition(fd, m, k, n, d)\n multidevice_schedule(tensors, d)\n\n a_ref = torch.testing.make_tensor(d, m // d, k, dtype=torch.int32, device=\"cpu\").to(","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_overlap.multidevice_schedule","uri":"program://Fuser/function/tests.python.multidevice.test_overlap.multidevice_schedule#L715-L721","kind":"function","name":"multidevice_schedule","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":715,"end_line":721,"context_start_line":695,"context_end_line":741,"code":" def fusion_definition(\n fd: FusionDefinition, m: int, k: int, n: int, d: int\n ) -> list[TensorView]:\n a = fd.define_tensor(\n shape=[d, m // d, k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n b = fd.define_tensor(\n shape=[k, n],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n\n c = fd.ops.matmul(a, b)\n if backend_type == CommunicatorBackend.cuda:\n c.set_memory_type(nvfuser.MemoryType.symmetric)\n fd.add_output(c)\n return [a, b, c]\n\n def multidevice_schedule(tensors: list[TensorView], num_devices: int) -> None:\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n for tv in tensors:\n tv.set_device_mesh(mesh)\n\n a, _, _ = tensors\n a.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n d = multidevice_test.size\n m, k, n = 128, 64, 96\n if m % d != 0:\n pytest.skip(f\"m ({m}) must be divisible by world size ({d}).\")\n\n dtype = torch.bfloat16\n with FusionDefinition() as fd:\n tensors = fusion_definition(fd, m, k, n, d)\n multidevice_schedule(tensors, d)\n\n a_ref = torch.testing.make_tensor(d, m // d, k, dtype=torch.int32, device=\"cpu\").to(\n dtype\n )\n b_ref = torch.testing.make_tensor(k, n, dtype=torch.int32, device=\"cpu\").to(dtype)\n\n a = multidevice_test.shard_tensor(a_ref, fd.fusion.inputs()[0])\n b = b_ref.cuda(multidevice_test.local_rank)\n\n params = nvfuser.multidevice.MultiDeviceExecutorParams()","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear","uri":"program://Fuser/module/tests.python.multidevice.linear#L1-L151","kind":"module","name":"tests.python.multidevice.linear","path":"tests/python/multidevice/linear.py","language":"python","start_line":1,"end_line":151,"context_start_line":1,"context_end_line":151,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom dataclasses import dataclass\nfrom enum import auto, Enum\nfrom functools import lru_cache\nfrom typing import Iterable\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement\n\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom .fusion_definition_wrapper import FusionDefinitionWrapper\n\n\n@dataclass(frozen=True)\nclass LinearConfig:\n in_features: int\n out_features: int\n # Whether the input/output tensors have a leading batch dimension. This is\n # typically true for MLA and false for MoE.\n has_batch: bool\n\n\n# I omitted biases because DeepSeek V3 uses non-biased linear layers in MLA and\n# MoE.\ndef define_linear_forward(config: LinearConfig, fd: FusionDefinition) -> None:\n e_in, e_out = config.in_features, config.out_features\n\n inp_shape = [-1, -1, e_in] if config.has_batch else [-1, e_in]\n inp = fd.define_tensor(inp_shape, contiguity=True, dtype=DataType.BFloat16)\n weight = fd.define_tensor([e_out, e_in], contiguity=True, dtype=DataType.BFloat16)\n out = fd.ops.linear(inp, weight)\n fd.add_output(out)\n\n\ndef define_linear_backward(config: LinearConfig, fd: FusionDefinition) -> None:\n e_in, e_out = config.in_features, config.out_features\n\n x_shape = [-1, -1, e_in] if config.has_batch else [-1, e_in]\n x = fd.define_tensor(x_shape, contiguity=True, dtype=DataType.BFloat16)\n w = fd.define_tensor([e_out, e_in], contiguity=True, dtype=DataType.BFloat16)\n grad_shape = [-1, -1, e_out] if config.has_batch else [-1, e_out]\n grad = fd.define_tensor(grad_shape, contiguity=True, dtype=DataType.BFloat16)\n\n grad_x = fd.ops.matmul(grad, w)\n\n grad_flat = fd.ops.reshape(grad, [-1, e_out]) if config.has_batch else grad\n grad_flat_t = fd.ops.permute(grad_flat, [1, 0])\n\n x_flat = fd.ops.reshape(x, [-1, e_in]) if config.has_batch else x\n\n grad_w = fd.ops.matmul(grad_flat_t, x_flat)\n\n fd.add_output(grad_x)\n fd.add_output(grad_w)\n\n\nclass ComputeType(Enum):\n FORWARD = auto()\n BACKWARD = auto()\n\n\n# Cache based on forward and backward linear definition and its configuration.\n# FusionDefinitionWrapper caches based on input dtensors.\n@lru_cache\ndef get_fusion_definition_wrapper(\n compute_type: ComputeType,\n linear_config: LinearConfig,\n) -> FusionDefinition:\n match compute_type:\n case ComputeType.FORWARD:\n return FusionDefinitionWrapper(\n lambda fd: define_linear_forward(linear_config, fd)\n )\n case ComputeType.BACKWARD:\n return FusionDefinitionWrapper(\n lambda fd: define_linear_backward(linear_config, fd)\n )\n\n\nclass LinearFunction(torch.autograd.Function):\n @staticmethod\n def forward(\n ctx,\n input: DTensor,\n weight: DTensor,\n ):\n assert input.dim() in (2, 3)\n op = get_fusion_definition_wrapper(\n ComputeType.FORWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n (output,) = op([input, weight])\n ctx.save_for_backward(input, weight)\n return output\n\n @staticmethod\n def backward(ctx, grad_output: DTensor):\n input, weight = ctx.saved_tensors\n assert input.dim() in (2, 3)\n op = get_fusion_definition_wrapper(\n ComputeType.BACKWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n grad_x, grad_w = op([input, weight, grad_output])\n return (grad_x, grad_w)\n\n\nclass TensorParallelLinear(torch.nn.Linear):\n def __init__(\n self,\n in_features: int,\n out_features: int,\n in_placements: Iterable[Placement] = [],\n ):\n # Unlike normal layers whose `__init__` allocates the parameters,\n # `TensorParallelLinear` is expected to be created from a\n # non-distributed Linear layer via the `distribute` method. Therefore,\n # here, we construct super() with no memory allocated for weights. The\n # weights will be derived by the `distribute` method.\n super().__init__(in_features, out_features, bias=False, device=\"meta\")\n self.in_placements = in_placements\n\n def __repr__(self):\n base_repr = super().__repr__()\n return f\"{base_repr[:-1]}, in_placements={self.in_placements}, weight_placements={self.weight.data.placements})\"\n\n @classmethod\n def distribute(\n cls,\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n in_placements: Iterable[Placement] = [],\n weight_placements: Iterable[Placement] = [],\n ):\n tp_linear = cls(linear.in_features, linear.out_features, in_placements)\n tp_linear.weight = torch.nn.Parameter(\n dist.tensor.distribute_tensor(linear.weight, mesh, weight_placements)\n )\n return tp_linear\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n in_dtensor = DTensor.from_local(\n input, self.weight.device_mesh, self.in_placements\n )\n out_dtensor = LinearFunction.apply(in_dtensor, self.weight)\n return out_dtensor.to_local()","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.LinearConfig","uri":"program://Fuser/class/tests.python.multidevice.linear.LinearConfig#L20-L25","kind":"class","name":"LinearConfig","path":"tests/python/multidevice/linear.py","language":"python","start_line":20,"end_line":25,"context_start_line":1,"context_end_line":45,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom dataclasses import dataclass\nfrom enum import auto, Enum\nfrom functools import lru_cache\nfrom typing import Iterable\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement\n\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom .fusion_definition_wrapper import FusionDefinitionWrapper\n\n\n@dataclass(frozen=True)\nclass LinearConfig:\n in_features: int\n out_features: int\n # Whether the input/output tensors have a leading batch dimension. This is\n # typically true for MLA and false for MoE.\n has_batch: bool\n\n\n# I omitted biases because DeepSeek V3 uses non-biased linear layers in MLA and\n# MoE.\ndef define_linear_forward(config: LinearConfig, fd: FusionDefinition) -> None:\n e_in, e_out = config.in_features, config.out_features\n\n inp_shape = [-1, -1, e_in] if config.has_batch else [-1, e_in]\n inp = fd.define_tensor(inp_shape, contiguity=True, dtype=DataType.BFloat16)\n weight = fd.define_tensor([e_out, e_in], contiguity=True, dtype=DataType.BFloat16)\n out = fd.ops.linear(inp, weight)\n fd.add_output(out)\n\n\ndef define_linear_backward(config: LinearConfig, fd: FusionDefinition) -> None:\n e_in, e_out = config.in_features, config.out_features\n\n x_shape = [-1, -1, e_in] if config.has_batch else [-1, e_in]\n x = fd.define_tensor(x_shape, contiguity=True, dtype=DataType.BFloat16)\n w = fd.define_tensor([e_out, e_in], contiguity=True, dtype=DataType.BFloat16)","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.define_linear_forward","uri":"program://Fuser/function/tests.python.multidevice.linear.define_linear_forward#L30-L37","kind":"function","name":"define_linear_forward","path":"tests/python/multidevice/linear.py","language":"python","start_line":30,"end_line":37,"context_start_line":10,"context_end_line":57,"code":"import torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement\n\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom .fusion_definition_wrapper import FusionDefinitionWrapper\n\n\n@dataclass(frozen=True)\nclass LinearConfig:\n in_features: int\n out_features: int\n # Whether the input/output tensors have a leading batch dimension. This is\n # typically true for MLA and false for MoE.\n has_batch: bool\n\n\n# I omitted biases because DeepSeek V3 uses non-biased linear layers in MLA and\n# MoE.\ndef define_linear_forward(config: LinearConfig, fd: FusionDefinition) -> None:\n e_in, e_out = config.in_features, config.out_features\n\n inp_shape = [-1, -1, e_in] if config.has_batch else [-1, e_in]\n inp = fd.define_tensor(inp_shape, contiguity=True, dtype=DataType.BFloat16)\n weight = fd.define_tensor([e_out, e_in], contiguity=True, dtype=DataType.BFloat16)\n out = fd.ops.linear(inp, weight)\n fd.add_output(out)\n\n\ndef define_linear_backward(config: LinearConfig, fd: FusionDefinition) -> None:\n e_in, e_out = config.in_features, config.out_features\n\n x_shape = [-1, -1, e_in] if config.has_batch else [-1, e_in]\n x = fd.define_tensor(x_shape, contiguity=True, dtype=DataType.BFloat16)\n w = fd.define_tensor([e_out, e_in], contiguity=True, dtype=DataType.BFloat16)\n grad_shape = [-1, -1, e_out] if config.has_batch else [-1, e_out]\n grad = fd.define_tensor(grad_shape, contiguity=True, dtype=DataType.BFloat16)\n\n grad_x = fd.ops.matmul(grad, w)\n\n grad_flat = fd.ops.reshape(grad, [-1, e_out]) if config.has_batch else grad\n grad_flat_t = fd.ops.permute(grad_flat, [1, 0])\n\n x_flat = fd.ops.reshape(x, [-1, e_in]) if config.has_batch else x\n\n grad_w = fd.ops.matmul(grad_flat_t, x_flat)\n","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.define_linear_backward","uri":"program://Fuser/function/tests.python.multidevice.linear.define_linear_backward#L40-L59","kind":"function","name":"define_linear_backward","path":"tests/python/multidevice/linear.py","language":"python","start_line":40,"end_line":59,"context_start_line":20,"context_end_line":79,"code":"class LinearConfig:\n in_features: int\n out_features: int\n # Whether the input/output tensors have a leading batch dimension. This is\n # typically true for MLA and false for MoE.\n has_batch: bool\n\n\n# I omitted biases because DeepSeek V3 uses non-biased linear layers in MLA and\n# MoE.\ndef define_linear_forward(config: LinearConfig, fd: FusionDefinition) -> None:\n e_in, e_out = config.in_features, config.out_features\n\n inp_shape = [-1, -1, e_in] if config.has_batch else [-1, e_in]\n inp = fd.define_tensor(inp_shape, contiguity=True, dtype=DataType.BFloat16)\n weight = fd.define_tensor([e_out, e_in], contiguity=True, dtype=DataType.BFloat16)\n out = fd.ops.linear(inp, weight)\n fd.add_output(out)\n\n\ndef define_linear_backward(config: LinearConfig, fd: FusionDefinition) -> None:\n e_in, e_out = config.in_features, config.out_features\n\n x_shape = [-1, -1, e_in] if config.has_batch else [-1, e_in]\n x = fd.define_tensor(x_shape, contiguity=True, dtype=DataType.BFloat16)\n w = fd.define_tensor([e_out, e_in], contiguity=True, dtype=DataType.BFloat16)\n grad_shape = [-1, -1, e_out] if config.has_batch else [-1, e_out]\n grad = fd.define_tensor(grad_shape, contiguity=True, dtype=DataType.BFloat16)\n\n grad_x = fd.ops.matmul(grad, w)\n\n grad_flat = fd.ops.reshape(grad, [-1, e_out]) if config.has_batch else grad\n grad_flat_t = fd.ops.permute(grad_flat, [1, 0])\n\n x_flat = fd.ops.reshape(x, [-1, e_in]) if config.has_batch else x\n\n grad_w = fd.ops.matmul(grad_flat_t, x_flat)\n\n fd.add_output(grad_x)\n fd.add_output(grad_w)\n\n\nclass ComputeType(Enum):\n FORWARD = auto()\n BACKWARD = auto()\n\n\n# Cache based on forward and backward linear definition and its configuration.\n# FusionDefinitionWrapper caches based on input dtensors.\n@lru_cache\ndef get_fusion_definition_wrapper(\n compute_type: ComputeType,\n linear_config: LinearConfig,\n) -> FusionDefinition:\n match compute_type:\n case ComputeType.FORWARD:\n return FusionDefinitionWrapper(\n lambda fd: define_linear_forward(linear_config, fd)\n )\n case ComputeType.BACKWARD:","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.ComputeType","uri":"program://Fuser/class/tests.python.multidevice.linear.ComputeType#L62-L64","kind":"class","name":"ComputeType","path":"tests/python/multidevice/linear.py","language":"python","start_line":62,"end_line":64,"context_start_line":42,"context_end_line":84,"code":"\n x_shape = [-1, -1, e_in] if config.has_batch else [-1, e_in]\n x = fd.define_tensor(x_shape, contiguity=True, dtype=DataType.BFloat16)\n w = fd.define_tensor([e_out, e_in], contiguity=True, dtype=DataType.BFloat16)\n grad_shape = [-1, -1, e_out] if config.has_batch else [-1, e_out]\n grad = fd.define_tensor(grad_shape, contiguity=True, dtype=DataType.BFloat16)\n\n grad_x = fd.ops.matmul(grad, w)\n\n grad_flat = fd.ops.reshape(grad, [-1, e_out]) if config.has_batch else grad\n grad_flat_t = fd.ops.permute(grad_flat, [1, 0])\n\n x_flat = fd.ops.reshape(x, [-1, e_in]) if config.has_batch else x\n\n grad_w = fd.ops.matmul(grad_flat_t, x_flat)\n\n fd.add_output(grad_x)\n fd.add_output(grad_w)\n\n\nclass ComputeType(Enum):\n FORWARD = auto()\n BACKWARD = auto()\n\n\n# Cache based on forward and backward linear definition and its configuration.\n# FusionDefinitionWrapper caches based on input dtensors.\n@lru_cache\ndef get_fusion_definition_wrapper(\n compute_type: ComputeType,\n linear_config: LinearConfig,\n) -> FusionDefinition:\n match compute_type:\n case ComputeType.FORWARD:\n return FusionDefinitionWrapper(\n lambda fd: define_linear_forward(linear_config, fd)\n )\n case ComputeType.BACKWARD:\n return FusionDefinitionWrapper(\n lambda fd: define_linear_backward(linear_config, fd)\n )\n\n","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.get_fusion_definition_wrapper","uri":"program://Fuser/function/tests.python.multidevice.linear.get_fusion_definition_wrapper#L70-L82","kind":"function","name":"get_fusion_definition_wrapper","path":"tests/python/multidevice/linear.py","language":"python","start_line":70,"end_line":82,"context_start_line":50,"context_end_line":102,"code":"\n grad_flat = fd.ops.reshape(grad, [-1, e_out]) if config.has_batch else grad\n grad_flat_t = fd.ops.permute(grad_flat, [1, 0])\n\n x_flat = fd.ops.reshape(x, [-1, e_in]) if config.has_batch else x\n\n grad_w = fd.ops.matmul(grad_flat_t, x_flat)\n\n fd.add_output(grad_x)\n fd.add_output(grad_w)\n\n\nclass ComputeType(Enum):\n FORWARD = auto()\n BACKWARD = auto()\n\n\n# Cache based on forward and backward linear definition and its configuration.\n# FusionDefinitionWrapper caches based on input dtensors.\n@lru_cache\ndef get_fusion_definition_wrapper(\n compute_type: ComputeType,\n linear_config: LinearConfig,\n) -> FusionDefinition:\n match compute_type:\n case ComputeType.FORWARD:\n return FusionDefinitionWrapper(\n lambda fd: define_linear_forward(linear_config, fd)\n )\n case ComputeType.BACKWARD:\n return FusionDefinitionWrapper(\n lambda fd: define_linear_backward(linear_config, fd)\n )\n\n\nclass LinearFunction(torch.autograd.Function):\n @staticmethod\n def forward(\n ctx,\n input: DTensor,\n weight: DTensor,\n ):\n assert input.dim() in (2, 3)\n op = get_fusion_definition_wrapper(\n ComputeType.FORWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n (output,) = op([input, weight])\n ctx.save_for_backward(input, weight)\n return output\n\n @staticmethod\n def backward(ctx, grad_output: DTensor):","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.LinearFunction","uri":"program://Fuser/class/tests.python.multidevice.linear.LinearFunction#L85-L110","kind":"class","name":"LinearFunction","path":"tests/python/multidevice/linear.py","language":"python","start_line":85,"end_line":110,"context_start_line":65,"context_end_line":130,"code":"\n\n# Cache based on forward and backward linear definition and its configuration.\n# FusionDefinitionWrapper caches based on input dtensors.\n@lru_cache\ndef get_fusion_definition_wrapper(\n compute_type: ComputeType,\n linear_config: LinearConfig,\n) -> FusionDefinition:\n match compute_type:\n case ComputeType.FORWARD:\n return FusionDefinitionWrapper(\n lambda fd: define_linear_forward(linear_config, fd)\n )\n case ComputeType.BACKWARD:\n return FusionDefinitionWrapper(\n lambda fd: define_linear_backward(linear_config, fd)\n )\n\n\nclass LinearFunction(torch.autograd.Function):\n @staticmethod\n def forward(\n ctx,\n input: DTensor,\n weight: DTensor,\n ):\n assert input.dim() in (2, 3)\n op = get_fusion_definition_wrapper(\n ComputeType.FORWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n (output,) = op([input, weight])\n ctx.save_for_backward(input, weight)\n return output\n\n @staticmethod\n def backward(ctx, grad_output: DTensor):\n input, weight = ctx.saved_tensors\n assert input.dim() in (2, 3)\n op = get_fusion_definition_wrapper(\n ComputeType.BACKWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n grad_x, grad_w = op([input, weight, grad_output])\n return (grad_x, grad_w)\n\n\nclass TensorParallelLinear(torch.nn.Linear):\n def __init__(\n self,\n in_features: int,\n out_features: int,\n in_placements: Iterable[Placement] = [],\n ):\n # Unlike normal layers whose `__init__` allocates the parameters,\n # `TensorParallelLinear` is expected to be created from a\n # non-distributed Linear layer via the `distribute` method. Therefore,\n # here, we construct super() with no memory allocated for weights. The\n # weights will be derived by the `distribute` method.\n super().__init__(in_features, out_features, bias=False, device=\"meta\")\n self.in_placements = in_placements\n\n def __repr__(self):\n base_repr = super().__repr__()\n return f\"{base_repr[:-1]}, in_placements={self.in_placements}, weight_placements={self.weight.data.placements})\"","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.TensorParallelLinear","uri":"program://Fuser/class/tests.python.multidevice.linear.TensorParallelLinear#L113-L151","kind":"class","name":"TensorParallelLinear","path":"tests/python/multidevice/linear.py","language":"python","start_line":113,"end_line":151,"context_start_line":93,"context_end_line":151,"code":" op = get_fusion_definition_wrapper(\n ComputeType.FORWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n (output,) = op([input, weight])\n ctx.save_for_backward(input, weight)\n return output\n\n @staticmethod\n def backward(ctx, grad_output: DTensor):\n input, weight = ctx.saved_tensors\n assert input.dim() in (2, 3)\n op = get_fusion_definition_wrapper(\n ComputeType.BACKWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n grad_x, grad_w = op([input, weight, grad_output])\n return (grad_x, grad_w)\n\n\nclass TensorParallelLinear(torch.nn.Linear):\n def __init__(\n self,\n in_features: int,\n out_features: int,\n in_placements: Iterable[Placement] = [],\n ):\n # Unlike normal layers whose `__init__` allocates the parameters,\n # `TensorParallelLinear` is expected to be created from a\n # non-distributed Linear layer via the `distribute` method. Therefore,\n # here, we construct super() with no memory allocated for weights. The\n # weights will be derived by the `distribute` method.\n super().__init__(in_features, out_features, bias=False, device=\"meta\")\n self.in_placements = in_placements\n\n def __repr__(self):\n base_repr = super().__repr__()\n return f\"{base_repr[:-1]}, in_placements={self.in_placements}, weight_placements={self.weight.data.placements})\"\n\n @classmethod\n def distribute(\n cls,\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n in_placements: Iterable[Placement] = [],\n weight_placements: Iterable[Placement] = [],\n ):\n tp_linear = cls(linear.in_features, linear.out_features, in_placements)\n tp_linear.weight = torch.nn.Parameter(\n dist.tensor.distribute_tensor(linear.weight, mesh, weight_placements)\n )\n return tp_linear\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n in_dtensor = DTensor.from_local(\n input, self.weight.device_mesh, self.in_placements\n )\n out_dtensor = LinearFunction.apply(in_dtensor, self.weight)\n return out_dtensor.to_local()","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.forward","uri":"program://Fuser/function/tests.python.multidevice.linear.forward#L146-L151","kind":"function","name":"forward","path":"tests/python/multidevice/linear.py","language":"python","start_line":146,"end_line":151,"context_start_line":126,"context_end_line":151,"code":" self.in_placements = in_placements\n\n def __repr__(self):\n base_repr = super().__repr__()\n return f\"{base_repr[:-1]}, in_placements={self.in_placements}, weight_placements={self.weight.data.placements})\"\n\n @classmethod\n def distribute(\n cls,\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n in_placements: Iterable[Placement] = [],\n weight_placements: Iterable[Placement] = [],\n ):\n tp_linear = cls(linear.in_features, linear.out_features, in_placements)\n tp_linear.weight = torch.nn.Parameter(\n dist.tensor.distribute_tensor(linear.weight, mesh, weight_placements)\n )\n return tp_linear\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n in_dtensor = DTensor.from_local(\n input, self.weight.device_mesh, self.in_placements\n )\n out_dtensor = LinearFunction.apply(in_dtensor, self.weight)\n return out_dtensor.to_local()","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.backward","uri":"program://Fuser/function/tests.python.multidevice.linear.backward#L102-L110","kind":"function","name":"backward","path":"tests/python/multidevice/linear.py","language":"python","start_line":102,"end_line":110,"context_start_line":82,"context_end_line":130,"code":" )\n\n\nclass LinearFunction(torch.autograd.Function):\n @staticmethod\n def forward(\n ctx,\n input: DTensor,\n weight: DTensor,\n ):\n assert input.dim() in (2, 3)\n op = get_fusion_definition_wrapper(\n ComputeType.FORWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n (output,) = op([input, weight])\n ctx.save_for_backward(input, weight)\n return output\n\n @staticmethod\n def backward(ctx, grad_output: DTensor):\n input, weight = ctx.saved_tensors\n assert input.dim() in (2, 3)\n op = get_fusion_definition_wrapper(\n ComputeType.BACKWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n grad_x, grad_w = op([input, weight, grad_output])\n return (grad_x, grad_w)\n\n\nclass TensorParallelLinear(torch.nn.Linear):\n def __init__(\n self,\n in_features: int,\n out_features: int,\n in_placements: Iterable[Placement] = [],\n ):\n # Unlike normal layers whose `__init__` allocates the parameters,\n # `TensorParallelLinear` is expected to be created from a\n # non-distributed Linear layer via the `distribute` method. Therefore,\n # here, we construct super() with no memory allocated for weights. The\n # weights will be derived by the `distribute` method.\n super().__init__(in_features, out_features, bias=False, device=\"meta\")\n self.in_placements = in_placements\n\n def __repr__(self):\n base_repr = super().__repr__()\n return f\"{base_repr[:-1]}, in_placements={self.in_placements}, weight_placements={self.weight.data.placements})\"","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.__init__","uri":"program://Fuser/function/tests.python.multidevice.linear.__init__#L114-L126","kind":"function","name":"__init__","path":"tests/python/multidevice/linear.py","language":"python","start_line":114,"end_line":126,"context_start_line":94,"context_end_line":146,"code":" ComputeType.FORWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n (output,) = op([input, weight])\n ctx.save_for_backward(input, weight)\n return output\n\n @staticmethod\n def backward(ctx, grad_output: DTensor):\n input, weight = ctx.saved_tensors\n assert input.dim() in (2, 3)\n op = get_fusion_definition_wrapper(\n ComputeType.BACKWARD,\n LinearConfig(weight.size(1), weight.size(0), has_batch=(input.dim() == 3)),\n )\n grad_x, grad_w = op([input, weight, grad_output])\n return (grad_x, grad_w)\n\n\nclass TensorParallelLinear(torch.nn.Linear):\n def __init__(\n self,\n in_features: int,\n out_features: int,\n in_placements: Iterable[Placement] = [],\n ):\n # Unlike normal layers whose `__init__` allocates the parameters,\n # `TensorParallelLinear` is expected to be created from a\n # non-distributed Linear layer via the `distribute` method. Therefore,\n # here, we construct super() with no memory allocated for weights. The\n # weights will be derived by the `distribute` method.\n super().__init__(in_features, out_features, bias=False, device=\"meta\")\n self.in_placements = in_placements\n\n def __repr__(self):\n base_repr = super().__repr__()\n return f\"{base_repr[:-1]}, in_placements={self.in_placements}, weight_placements={self.weight.data.placements})\"\n\n @classmethod\n def distribute(\n cls,\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n in_placements: Iterable[Placement] = [],\n weight_placements: Iterable[Placement] = [],\n ):\n tp_linear = cls(linear.in_features, linear.out_features, in_placements)\n tp_linear.weight = torch.nn.Parameter(\n dist.tensor.distribute_tensor(linear.weight, mesh, weight_placements)\n )\n return tp_linear\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.__repr__","uri":"program://Fuser/function/tests.python.multidevice.linear.__repr__#L128-L130","kind":"function","name":"__repr__","path":"tests/python/multidevice/linear.py","language":"python","start_line":128,"end_line":130,"context_start_line":108,"context_end_line":150,"code":" )\n grad_x, grad_w = op([input, weight, grad_output])\n return (grad_x, grad_w)\n\n\nclass TensorParallelLinear(torch.nn.Linear):\n def __init__(\n self,\n in_features: int,\n out_features: int,\n in_placements: Iterable[Placement] = [],\n ):\n # Unlike normal layers whose `__init__` allocates the parameters,\n # `TensorParallelLinear` is expected to be created from a\n # non-distributed Linear layer via the `distribute` method. Therefore,\n # here, we construct super() with no memory allocated for weights. The\n # weights will be derived by the `distribute` method.\n super().__init__(in_features, out_features, bias=False, device=\"meta\")\n self.in_placements = in_placements\n\n def __repr__(self):\n base_repr = super().__repr__()\n return f\"{base_repr[:-1]}, in_placements={self.in_placements}, weight_placements={self.weight.data.placements})\"\n\n @classmethod\n def distribute(\n cls,\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n in_placements: Iterable[Placement] = [],\n weight_placements: Iterable[Placement] = [],\n ):\n tp_linear = cls(linear.in_features, linear.out_features, in_placements)\n tp_linear.weight = torch.nn.Parameter(\n dist.tensor.distribute_tensor(linear.weight, mesh, weight_placements)\n )\n return tp_linear\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n in_dtensor = DTensor.from_local(\n input, self.weight.device_mesh, self.in_placements\n )\n out_dtensor = LinearFunction.apply(in_dtensor, self.weight)","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.linear.distribute","uri":"program://Fuser/function/tests.python.multidevice.linear.distribute#L133-L144","kind":"function","name":"distribute","path":"tests/python/multidevice/linear.py","language":"python","start_line":133,"end_line":144,"context_start_line":113,"context_end_line":151,"code":"class TensorParallelLinear(torch.nn.Linear):\n def __init__(\n self,\n in_features: int,\n out_features: int,\n in_placements: Iterable[Placement] = [],\n ):\n # Unlike normal layers whose `__init__` allocates the parameters,\n # `TensorParallelLinear` is expected to be created from a\n # non-distributed Linear layer via the `distribute` method. Therefore,\n # here, we construct super() with no memory allocated for weights. The\n # weights will be derived by the `distribute` method.\n super().__init__(in_features, out_features, bias=False, device=\"meta\")\n self.in_placements = in_placements\n\n def __repr__(self):\n base_repr = super().__repr__()\n return f\"{base_repr[:-1]}, in_placements={self.in_placements}, weight_placements={self.weight.data.placements})\"\n\n @classmethod\n def distribute(\n cls,\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n in_placements: Iterable[Placement] = [],\n weight_placements: Iterable[Placement] = [],\n ):\n tp_linear = cls(linear.in_features, linear.out_features, in_placements)\n tp_linear.weight = torch.nn.Parameter(\n dist.tensor.distribute_tensor(linear.weight, mesh, weight_placements)\n )\n return tp_linear\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n in_dtensor = DTensor.from_local(\n input, self.weight.device_mesh, self.in_placements\n )\n out_dtensor = LinearFunction.apply(in_dtensor, self.weight)\n return out_dtensor.to_local()","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3","uri":"program://Fuser/module/tests.python.multidevice.test_deepseek_v3#L1-L256","kind":"module","name":"tests.python.multidevice.test_deepseek_v3","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":1,"end_line":256,"context_start_line":1,"context_end_line":256,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\n# Run command:\n# mpirun -np 1 pytest tests/python/multidevice/test_deepseek_v3.py --only-mpi -s\n\nfrom contextlib import contextmanager\nfrom enum import Enum, auto\nfrom functools import wraps\nfrom typing import Optional\n\nimport pytest\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.parallel import (\n parallelize_module,\n ParallelStyle,\n RowwiseParallel,\n ColwiseParallel,\n)\nfrom torch.distributed.tensor.placement_types import Shard\n\nimport transformers\n\nfrom .benchmark_utils import get_benchmark_fns\nfrom .linear import TensorParallelLinear\n\n\n@contextmanager\ndef default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore\n torch.set_default_dtype(prev_dtype)\n torch.set_default_device(prev_device)\n\n\n# This decorator ensures that the model/config is downloaded only once by rank\n# 0. Other ranks will load from the cache that's stored on the same machine.\ndef download_once(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n rank = dist.get_rank()\n if rank == 0:\n # Download only once.\n result = fn(*args, **kwargs)\n\n dist.barrier()\n\n if rank != 0:\n # Other ranks load from cache.\n result = fn(*args, **kwargs)\n\n return result\n\n return wrapper\n\n\n@download_once\ndef load_config(model_name: str) -> transformers.PretrainedConfig:\n return transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)\n\n\n@download_once\ndef load_model(config: transformers.PretrainedConfig) -> transformers.PreTrainedModel:\n return transformers.AutoModel.from_config(config, trust_remote_code=True)\n\n\nclass Executor(Enum):\n # https://docs.pytorch.org/docs/stable/distributed.tensor.parallel.html\n TORCH_TP = auto()\n NVFUSER = auto()\n\n\ndef parallelize_linear_with_nvfuser(\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n parallel_style: ParallelStyle,\n) -> torch.nn.Linear:\n assert isinstance(linear, torch.nn.Linear), f\"Unsupported layer: {linear}\"\n\n assert len(parallel_style.input_layouts) == 1, \"Expect 1D mesh\"\n input_layout = parallel_style.input_layouts[0]\n\n assert len(parallel_style.output_layouts) == 1, \"Expect 1D mesh\"\n output_layout = parallel_style.output_layouts[0]\n\n if isinstance(parallel_style, RowwiseParallel):\n # We only support TP at this moment. A row-wise parallel linear is\n # expected to have the input sharded on the contracting dimension and\n # the output replicated.\n assert input_layout.is_shard(-1), f\"Unsupported layout: {input_layout}\"\n assert output_layout.is_replicate(), f\"Unsupported layout: {output_layout}\"\n return TensorParallelLinear.distribute(\n linear, mesh, in_placements=[input_layout], weight_placements=[Shard(-1)]\n )\n\n if isinstance(parallel_style, ColwiseParallel):\n # We only support TP at this moment. A column-wise parallel linear is\n # expected to have the input replicated and the output sharded on the\n # feature dimension.\n assert input_layout.is_replicate(), f\"Unsupported layout: {input_layout}\"\n assert output_layout.is_shard(-1), f\"Unsupported layout: {output_layout}\"\n return TensorParallelLinear.distribute(\n linear, mesh, in_placements=[input_layout], weight_placements=[Shard(0)]\n )\n\n assert False, f\"Unsupported parallel style: {parallel_style}\"\n\n\n# Recursively finds all linear modules and replaces them with tensor-parallel\n# nvFuser definitions if a parallel plan is found.\ndef parallelize_module_with_nvfuser(\n module: torch.nn.Module,\n mesh: dist.device_mesh.DeviceMesh,\n parallel_plan: dict[str, ParallelStyle],\n fqn: str, # stands for fully qualified name\n parent_module: Optional[torch.nn.Module] = None,\n):\n for child_module_name, child_module in module.named_children():\n if fqn:\n child_fqn = f\"{fqn}.{child_module_name}\"\n else:\n child_fqn = child_module_name\n\n parallelize_module_with_nvfuser(\n child_module, mesh, parallel_plan, child_fqn, module\n )\n\n if (parallel_style := parallel_plan.get(fqn)) is None:\n return\n\n new_module = parallelize_linear_with_nvfuser(module, mesh, parallel_style)\n assert parent_module is not None\n module_name = fqn.split(\".\")[-1]\n setattr(parent_module, module_name, new_module)\n\n\n@pytest.mark.skip(\n reason=\"Flaky. The test occasionally failed for too many download requests. The test itself downloads the HuggingFace model only once. However, with CI runs triggered by other PRs and for other GPU architectures, it can easily exceed the limit.\"\n)\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"executor\",\n [Executor.TORCH_TP, Executor.NVFUSER],\n ids=lambda e: e.name,\n)\ndef test_transformer_layer(setup_default_process_group, benchmark, executor: Executor):\n config = load_config(\"deepseek-ai/deepseek-v3\")\n # Create only one layer which is sufficient for the test.\n config.num_hidden_layers = 1\n # Without this, the first and only layer will have a dense MLP instead of MoE.\n config.first_k_dense_replace = 0\n # Disable quantization so the test can run on A100 and is made easier for nvFuser.\n delattr(config, \"quantization_config\")\n\n # This ensures the input tokens are identically replicated on all ranks.\n # Otherwise, some ranks may skip an expert because they have no tokens to\n # send, while other ranks don't. This will cause a deadlock because a NCCL\n # collective is expected to be called by all ranks in the process group.\n torch.manual_seed(0)\n\n d = dist.get_world_size()\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n with default_tensor_type(dtype=config.torch_dtype, device=\"cuda\"):\n # Loading the model under `device=\"cuda\"` makes weight initialization\n # much faster but requires full GPU memory allocation.\n #\n # Alternatively, I think the following may work but haven't tried it:\n # 1. Load the model under torch.nn.utils.init_empty_weights. This skips weight initialization and allocates full weights on CPU not GPU.\n # 2. parallelize_module\n # 3. Load pre-trained parameters.\n # 4. Move the model to CUDA.\n model = load_model(config)\n # Training is unavailable (cf. https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L439)\n model.eval()\n\n transformer_layer = model.layers[0]\n\n # By default, RowwiseParallel and ColwiseParallel output a local tensor\n # and therefore num_heads needs to be adjusted to accomodate the local\n # size. Alternatively, I could RowwiseParallel(use_local_output=False)\n # so the linear layer outputs a DTensor, which can be viewed using the\n # original num_heads. This requires all activations, parameters, and\n # buffers to be DTensor; otherwise aten ops would complain \"got mixed\n # torch.Tensor and DTensor\". Doing so is challenging because\n # DeepseekV3RotaryEmbedding creates cos_cached and sin_cached during\n # the first forward call (cf.\n # https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L143-L144).\n transformer_layer.self_attn.num_heads //= d\n\n # Create the parallel plan\n parallel_plan = {\n \"self_attn.q_b_proj\": ColwiseParallel(),\n \"self_attn.kv_b_proj\": ColwiseParallel(),\n \"self_attn.o_proj\": RowwiseParallel(),\n }\n\n for expert in range(config.n_routed_experts):\n parallel_plan[f\"mlp.experts.{expert}.gate_proj\"] = ColwiseParallel()\n parallel_plan[f\"mlp.experts.{expert}.up_proj\"] = ColwiseParallel()\n parallel_plan[f\"mlp.experts.{expert}.down_proj\"] = RowwiseParallel()\n\n parallel_plan[\"mlp.shared_experts.gate_proj\"] = ColwiseParallel()\n parallel_plan[\"mlp.shared_experts.up_proj\"] = ColwiseParallel()\n parallel_plan[\"mlp.shared_experts.down_proj\"] = RowwiseParallel()\n\n match executor:\n case Executor.TORCH_TP:\n transformer_layer = parallelize_module(\n transformer_layer,\n mesh,\n parallel_plan,\n )\n\n # Sanity-check parameters are indeed distributed\n distributed_params: list[str] = [\n name\n for name, parameter in transformer_layer.named_parameters()\n if isinstance(parameter.data, DTensor)\n ]\n assert len(distributed_params) == 3 + (config.n_routed_experts + 1) * 3\n case Executor.NVFUSER:\n parallelize_module_with_nvfuser(\n transformer_layer, mesh, parallel_plan, fqn=\"\"\n )\n\n batch_size = 1\n seq_len = 1024\n inp = torch.randn(batch_size, seq_len, config.hidden_size)\n mask = transformers.modeling_attn_mask_utils._prepare_4d_causal_attention_mask(\n None, [batch_size, seq_len], inp, past_key_values_length=0\n )\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: transformer_layer(inp, attention_mask=mask)\n )\n\n (out,) = warmup_fn()\n assert out.size() == (batch_size, seq_len, config.hidden_size)\n assert out.dtype == config.torch_dtype\n assert out.is_cuda\n\n benchmark.pedantic(benchmark_fn, rounds=5)","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3.default_tensor_type","uri":"program://Fuser/function/tests.python.multidevice.test_deepseek_v3.default_tensor_type#L34-L47","kind":"function","name":"default_tensor_type","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":34,"end_line":47,"context_start_line":14,"context_end_line":67,"code":"import pytest\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.parallel import (\n parallelize_module,\n ParallelStyle,\n RowwiseParallel,\n ColwiseParallel,\n)\nfrom torch.distributed.tensor.placement_types import Shard\n\nimport transformers\n\nfrom .benchmark_utils import get_benchmark_fns\nfrom .linear import TensorParallelLinear\n\n\n@contextmanager\ndef default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore\n torch.set_default_dtype(prev_dtype)\n torch.set_default_device(prev_device)\n\n\n# This decorator ensures that the model/config is downloaded only once by rank\n# 0. Other ranks will load from the cache that's stored on the same machine.\ndef download_once(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n rank = dist.get_rank()\n if rank == 0:\n # Download only once.\n result = fn(*args, **kwargs)\n\n dist.barrier()\n\n if rank != 0:\n # Other ranks load from cache.\n result = fn(*args, **kwargs)\n\n return result\n","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3.download_once","uri":"program://Fuser/function/tests.python.multidevice.test_deepseek_v3.download_once#L52-L68","kind":"function","name":"download_once","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":52,"end_line":68,"context_start_line":32,"context_end_line":88,"code":"\n@contextmanager\ndef default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore\n torch.set_default_dtype(prev_dtype)\n torch.set_default_device(prev_device)\n\n\n# This decorator ensures that the model/config is downloaded only once by rank\n# 0. Other ranks will load from the cache that's stored on the same machine.\ndef download_once(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n rank = dist.get_rank()\n if rank == 0:\n # Download only once.\n result = fn(*args, **kwargs)\n\n dist.barrier()\n\n if rank != 0:\n # Other ranks load from cache.\n result = fn(*args, **kwargs)\n\n return result\n\n return wrapper\n\n\n@download_once\ndef load_config(model_name: str) -> transformers.PretrainedConfig:\n return transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)\n\n\n@download_once\ndef load_model(config: transformers.PretrainedConfig) -> transformers.PreTrainedModel:\n return transformers.AutoModel.from_config(config, trust_remote_code=True)\n\n\nclass Executor(Enum):\n # https://docs.pytorch.org/docs/stable/distributed.tensor.parallel.html\n TORCH_TP = auto()\n NVFUSER = auto()\n\n\ndef parallelize_linear_with_nvfuser(\n linear: torch.nn.Linear,","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3.load_config","uri":"program://Fuser/function/tests.python.multidevice.test_deepseek_v3.load_config#L72-L73","kind":"function","name":"load_config","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":72,"end_line":73,"context_start_line":52,"context_end_line":93,"code":"def download_once(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n rank = dist.get_rank()\n if rank == 0:\n # Download only once.\n result = fn(*args, **kwargs)\n\n dist.barrier()\n\n if rank != 0:\n # Other ranks load from cache.\n result = fn(*args, **kwargs)\n\n return result\n\n return wrapper\n\n\n@download_once\ndef load_config(model_name: str) -> transformers.PretrainedConfig:\n return transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)\n\n\n@download_once\ndef load_model(config: transformers.PretrainedConfig) -> transformers.PreTrainedModel:\n return transformers.AutoModel.from_config(config, trust_remote_code=True)\n\n\nclass Executor(Enum):\n # https://docs.pytorch.org/docs/stable/distributed.tensor.parallel.html\n TORCH_TP = auto()\n NVFUSER = auto()\n\n\ndef parallelize_linear_with_nvfuser(\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n parallel_style: ParallelStyle,\n) -> torch.nn.Linear:\n assert isinstance(linear, torch.nn.Linear), f\"Unsupported layer: {linear}\"\n","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3.load_model","uri":"program://Fuser/function/tests.python.multidevice.test_deepseek_v3.load_model#L77-L78","kind":"function","name":"load_model","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":77,"end_line":78,"context_start_line":57,"context_end_line":98,"code":" # Download only once.\n result = fn(*args, **kwargs)\n\n dist.barrier()\n\n if rank != 0:\n # Other ranks load from cache.\n result = fn(*args, **kwargs)\n\n return result\n\n return wrapper\n\n\n@download_once\ndef load_config(model_name: str) -> transformers.PretrainedConfig:\n return transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)\n\n\n@download_once\ndef load_model(config: transformers.PretrainedConfig) -> transformers.PreTrainedModel:\n return transformers.AutoModel.from_config(config, trust_remote_code=True)\n\n\nclass Executor(Enum):\n # https://docs.pytorch.org/docs/stable/distributed.tensor.parallel.html\n TORCH_TP = auto()\n NVFUSER = auto()\n\n\ndef parallelize_linear_with_nvfuser(\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n parallel_style: ParallelStyle,\n) -> torch.nn.Linear:\n assert isinstance(linear, torch.nn.Linear), f\"Unsupported layer: {linear}\"\n\n assert len(parallel_style.input_layouts) == 1, \"Expect 1D mesh\"\n input_layout = parallel_style.input_layouts[0]\n\n assert len(parallel_style.output_layouts) == 1, \"Expect 1D mesh\"\n output_layout = parallel_style.output_layouts[0]","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3.Executor","uri":"program://Fuser/class/tests.python.multidevice.test_deepseek_v3.Executor#L81-L84","kind":"class","name":"Executor","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":81,"end_line":84,"context_start_line":61,"context_end_line":104,"code":"\n if rank != 0:\n # Other ranks load from cache.\n result = fn(*args, **kwargs)\n\n return result\n\n return wrapper\n\n\n@download_once\ndef load_config(model_name: str) -> transformers.PretrainedConfig:\n return transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)\n\n\n@download_once\ndef load_model(config: transformers.PretrainedConfig) -> transformers.PreTrainedModel:\n return transformers.AutoModel.from_config(config, trust_remote_code=True)\n\n\nclass Executor(Enum):\n # https://docs.pytorch.org/docs/stable/distributed.tensor.parallel.html\n TORCH_TP = auto()\n NVFUSER = auto()\n\n\ndef parallelize_linear_with_nvfuser(\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n parallel_style: ParallelStyle,\n) -> torch.nn.Linear:\n assert isinstance(linear, torch.nn.Linear), f\"Unsupported layer: {linear}\"\n\n assert len(parallel_style.input_layouts) == 1, \"Expect 1D mesh\"\n input_layout = parallel_style.input_layouts[0]\n\n assert len(parallel_style.output_layouts) == 1, \"Expect 1D mesh\"\n output_layout = parallel_style.output_layouts[0]\n\n if isinstance(parallel_style, RowwiseParallel):\n # We only support TP at this moment. A row-wise parallel linear is\n # expected to have the input sharded on the contracting dimension and\n # the output replicated.\n assert input_layout.is_shard(-1), f\"Unsupported layout: {input_layout}\"","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3.parallelize_linear_with_nvfuser","uri":"program://Fuser/function/tests.python.multidevice.test_deepseek_v3.parallelize_linear_with_nvfuser#L87-L120","kind":"function","name":"parallelize_linear_with_nvfuser","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":87,"end_line":120,"context_start_line":67,"context_end_line":140,"code":"\n return wrapper\n\n\n@download_once\ndef load_config(model_name: str) -> transformers.PretrainedConfig:\n return transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)\n\n\n@download_once\ndef load_model(config: transformers.PretrainedConfig) -> transformers.PreTrainedModel:\n return transformers.AutoModel.from_config(config, trust_remote_code=True)\n\n\nclass Executor(Enum):\n # https://docs.pytorch.org/docs/stable/distributed.tensor.parallel.html\n TORCH_TP = auto()\n NVFUSER = auto()\n\n\ndef parallelize_linear_with_nvfuser(\n linear: torch.nn.Linear,\n mesh: dist.device_mesh.DeviceMesh,\n parallel_style: ParallelStyle,\n) -> torch.nn.Linear:\n assert isinstance(linear, torch.nn.Linear), f\"Unsupported layer: {linear}\"\n\n assert len(parallel_style.input_layouts) == 1, \"Expect 1D mesh\"\n input_layout = parallel_style.input_layouts[0]\n\n assert len(parallel_style.output_layouts) == 1, \"Expect 1D mesh\"\n output_layout = parallel_style.output_layouts[0]\n\n if isinstance(parallel_style, RowwiseParallel):\n # We only support TP at this moment. A row-wise parallel linear is\n # expected to have the input sharded on the contracting dimension and\n # the output replicated.\n assert input_layout.is_shard(-1), f\"Unsupported layout: {input_layout}\"\n assert output_layout.is_replicate(), f\"Unsupported layout: {output_layout}\"\n return TensorParallelLinear.distribute(\n linear, mesh, in_placements=[input_layout], weight_placements=[Shard(-1)]\n )\n\n if isinstance(parallel_style, ColwiseParallel):\n # We only support TP at this moment. A column-wise parallel linear is\n # expected to have the input replicated and the output sharded on the\n # feature dimension.\n assert input_layout.is_replicate(), f\"Unsupported layout: {input_layout}\"\n assert output_layout.is_shard(-1), f\"Unsupported layout: {output_layout}\"\n return TensorParallelLinear.distribute(\n linear, mesh, in_placements=[input_layout], weight_placements=[Shard(0)]\n )\n\n assert False, f\"Unsupported parallel style: {parallel_style}\"\n\n\n# Recursively finds all linear modules and replaces them with tensor-parallel\n# nvFuser definitions if a parallel plan is found.\ndef parallelize_module_with_nvfuser(\n module: torch.nn.Module,\n mesh: dist.device_mesh.DeviceMesh,\n parallel_plan: dict[str, ParallelStyle],\n fqn: str, # stands for fully qualified name\n parent_module: Optional[torch.nn.Module] = None,\n):\n for child_module_name, child_module in module.named_children():\n if fqn:\n child_fqn = f\"{fqn}.{child_module_name}\"\n else:\n child_fqn = child_module_name\n\n parallelize_module_with_nvfuser(\n child_module, mesh, parallel_plan, child_fqn, module\n )","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3.parallelize_module_with_nvfuser","uri":"program://Fuser/function/tests.python.multidevice.test_deepseek_v3.parallelize_module_with_nvfuser#L125-L148","kind":"function","name":"parallelize_module_with_nvfuser","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":125,"end_line":148,"context_start_line":105,"context_end_line":168,"code":" assert output_layout.is_replicate(), f\"Unsupported layout: {output_layout}\"\n return TensorParallelLinear.distribute(\n linear, mesh, in_placements=[input_layout], weight_placements=[Shard(-1)]\n )\n\n if isinstance(parallel_style, ColwiseParallel):\n # We only support TP at this moment. A column-wise parallel linear is\n # expected to have the input replicated and the output sharded on the\n # feature dimension.\n assert input_layout.is_replicate(), f\"Unsupported layout: {input_layout}\"\n assert output_layout.is_shard(-1), f\"Unsupported layout: {output_layout}\"\n return TensorParallelLinear.distribute(\n linear, mesh, in_placements=[input_layout], weight_placements=[Shard(0)]\n )\n\n assert False, f\"Unsupported parallel style: {parallel_style}\"\n\n\n# Recursively finds all linear modules and replaces them with tensor-parallel\n# nvFuser definitions if a parallel plan is found.\ndef parallelize_module_with_nvfuser(\n module: torch.nn.Module,\n mesh: dist.device_mesh.DeviceMesh,\n parallel_plan: dict[str, ParallelStyle],\n fqn: str, # stands for fully qualified name\n parent_module: Optional[torch.nn.Module] = None,\n):\n for child_module_name, child_module in module.named_children():\n if fqn:\n child_fqn = f\"{fqn}.{child_module_name}\"\n else:\n child_fqn = child_module_name\n\n parallelize_module_with_nvfuser(\n child_module, mesh, parallel_plan, child_fqn, module\n )\n\n if (parallel_style := parallel_plan.get(fqn)) is None:\n return\n\n new_module = parallelize_linear_with_nvfuser(module, mesh, parallel_style)\n assert parent_module is not None\n module_name = fqn.split(\".\")[-1]\n setattr(parent_module, module_name, new_module)\n\n\n@pytest.mark.skip(\n reason=\"Flaky. The test occasionally failed for too many download requests. The test itself downloads the HuggingFace model only once. However, with CI runs triggered by other PRs and for other GPU architectures, it can easily exceed the limit.\"\n)\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"executor\",\n [Executor.TORCH_TP, Executor.NVFUSER],\n ids=lambda e: e.name,\n)\ndef test_transformer_layer(setup_default_process_group, benchmark, executor: Executor):\n config = load_config(\"deepseek-ai/deepseek-v3\")\n # Create only one layer which is sufficient for the test.\n config.num_hidden_layers = 1\n # Without this, the first and only layer will have a dense MLP instead of MoE.\n config.first_k_dense_replace = 0\n # Disable quantization so the test can run on A100 and is made easier for nvFuser.\n delattr(config, \"quantization_config\")\n","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3.test_transformer_layer","uri":"program://Fuser/function/tests.python.multidevice.test_deepseek_v3.test_transformer_layer#L160-L256","kind":"function","name":"test_transformer_layer","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":160,"end_line":256,"context_start_line":140,"context_end_line":256,"code":" )\n\n if (parallel_style := parallel_plan.get(fqn)) is None:\n return\n\n new_module = parallelize_linear_with_nvfuser(module, mesh, parallel_style)\n assert parent_module is not None\n module_name = fqn.split(\".\")[-1]\n setattr(parent_module, module_name, new_module)\n\n\n@pytest.mark.skip(\n reason=\"Flaky. The test occasionally failed for too many download requests. The test itself downloads the HuggingFace model only once. However, with CI runs triggered by other PRs and for other GPU architectures, it can easily exceed the limit.\"\n)\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"executor\",\n [Executor.TORCH_TP, Executor.NVFUSER],\n ids=lambda e: e.name,\n)\ndef test_transformer_layer(setup_default_process_group, benchmark, executor: Executor):\n config = load_config(\"deepseek-ai/deepseek-v3\")\n # Create only one layer which is sufficient for the test.\n config.num_hidden_layers = 1\n # Without this, the first and only layer will have a dense MLP instead of MoE.\n config.first_k_dense_replace = 0\n # Disable quantization so the test can run on A100 and is made easier for nvFuser.\n delattr(config, \"quantization_config\")\n\n # This ensures the input tokens are identically replicated on all ranks.\n # Otherwise, some ranks may skip an expert because they have no tokens to\n # send, while other ranks don't. This will cause a deadlock because a NCCL\n # collective is expected to be called by all ranks in the process group.\n torch.manual_seed(0)\n\n d = dist.get_world_size()\n mesh = dist.device_mesh.init_device_mesh(\"cuda\", [d])\n\n with default_tensor_type(dtype=config.torch_dtype, device=\"cuda\"):\n # Loading the model under `device=\"cuda\"` makes weight initialization\n # much faster but requires full GPU memory allocation.\n #\n # Alternatively, I think the following may work but haven't tried it:\n # 1. Load the model under torch.nn.utils.init_empty_weights. This skips weight initialization and allocates full weights on CPU not GPU.\n # 2. parallelize_module\n # 3. Load pre-trained parameters.\n # 4. Move the model to CUDA.\n model = load_model(config)\n # Training is unavailable (cf. https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L439)\n model.eval()\n\n transformer_layer = model.layers[0]\n\n # By default, RowwiseParallel and ColwiseParallel output a local tensor\n # and therefore num_heads needs to be adjusted to accomodate the local\n # size. Alternatively, I could RowwiseParallel(use_local_output=False)\n # so the linear layer outputs a DTensor, which can be viewed using the\n # original num_heads. This requires all activations, parameters, and\n # buffers to be DTensor; otherwise aten ops would complain \"got mixed\n # torch.Tensor and DTensor\". Doing so is challenging because\n # DeepseekV3RotaryEmbedding creates cos_cached and sin_cached during\n # the first forward call (cf.\n # https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L143-L144).\n transformer_layer.self_attn.num_heads //= d\n\n # Create the parallel plan\n parallel_plan = {\n \"self_attn.q_b_proj\": ColwiseParallel(),\n \"self_attn.kv_b_proj\": ColwiseParallel(),\n \"self_attn.o_proj\": RowwiseParallel(),\n }\n\n for expert in range(config.n_routed_experts):\n parallel_plan[f\"mlp.experts.{expert}.gate_proj\"] = ColwiseParallel()\n parallel_plan[f\"mlp.experts.{expert}.up_proj\"] = ColwiseParallel()\n parallel_plan[f\"mlp.experts.{expert}.down_proj\"] = RowwiseParallel()\n\n parallel_plan[\"mlp.shared_experts.gate_proj\"] = ColwiseParallel()\n parallel_plan[\"mlp.shared_experts.up_proj\"] = ColwiseParallel()\n parallel_plan[\"mlp.shared_experts.down_proj\"] = RowwiseParallel()\n\n match executor:\n case Executor.TORCH_TP:\n transformer_layer = parallelize_module(\n transformer_layer,\n mesh,\n parallel_plan,\n )\n\n # Sanity-check parameters are indeed distributed\n distributed_params: list[str] = [\n name\n for name, parameter in transformer_layer.named_parameters()\n if isinstance(parameter.data, DTensor)\n ]\n assert len(distributed_params) == 3 + (config.n_routed_experts + 1) * 3\n case Executor.NVFUSER:\n parallelize_module_with_nvfuser(\n transformer_layer, mesh, parallel_plan, fqn=\"\"\n )\n\n batch_size = 1\n seq_len = 1024\n inp = torch.randn(batch_size, seq_len, config.hidden_size)\n mask = transformers.modeling_attn_mask_utils._prepare_4d_causal_attention_mask(\n None, [batch_size, seq_len], inp, past_key_values_length=0\n )\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: transformer_layer(inp, attention_mask=mask)\n )\n\n (out,) = warmup_fn()\n assert out.size() == (batch_size, seq_len, config.hidden_size)\n assert out.dtype == config.torch_dtype\n assert out.is_cuda\n\n benchmark.pedantic(benchmark_fn, rounds=5)","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_deepseek_v3.wrapper","uri":"program://Fuser/function/tests.python.multidevice.test_deepseek_v3.wrapper#L54-L66","kind":"function","name":"wrapper","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":54,"end_line":66,"context_start_line":34,"context_end_line":86,"code":"def default_tensor_type(dtype=torch.float32, device=\"cpu\"):\n # Save\n prev_dtype = torch.get_default_dtype()\n prev_device = torch.get_default_device()\n\n # Set\n torch.set_default_dtype(dtype)\n torch.set_default_device(device)\n\n yield\n\n # Restore\n torch.set_default_dtype(prev_dtype)\n torch.set_default_device(prev_device)\n\n\n# This decorator ensures that the model/config is downloaded only once by rank\n# 0. Other ranks will load from the cache that's stored on the same machine.\ndef download_once(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n rank = dist.get_rank()\n if rank == 0:\n # Download only once.\n result = fn(*args, **kwargs)\n\n dist.barrier()\n\n if rank != 0:\n # Other ranks load from cache.\n result = fn(*args, **kwargs)\n\n return result\n\n return wrapper\n\n\n@download_once\ndef load_config(model_name: str) -> transformers.PretrainedConfig:\n return transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)\n\n\n@download_once\ndef load_model(config: transformers.PretrainedConfig) -> transformers.PreTrainedModel:\n return transformers.AutoModel.from_config(config, trust_remote_code=True)\n\n\nclass Executor(Enum):\n # https://docs.pytorch.org/docs/stable/distributed.tensor.parallel.html\n TORCH_TP = auto()\n NVFUSER = auto()\n\n","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_alphafold3","uri":"program://Fuser/module/tests.python.multidevice.test_alphafold3#L1-L241","kind":"module","name":"tests.python.multidevice.test_alphafold3","path":"tests/python/multidevice/test_alphafold3.py","language":"python","start_line":1,"end_line":241,"context_start_line":1,"context_end_line":241,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\n# This file contains certain building blocks of the AlphaFold3 model.\n\nimport pytest\nimport torch\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\n\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4\n\n\n_DEFAULT_CONFIG = ModelConfig()\n\n\nclass Direction(Enum):\n INCOMING = auto() # aka ending node\n OUTGOING = auto() # aka starting node\n\n\ndef layer_norm(\n fd: FusionDefinition, x: TensorView, w: TensorView, b: TensorView\n) -> TensorView:\n io_dtype = x.dtype()\n x = fd.ops.cast(x, dtype=DataType.Float)\n var, mean = fd.ops.var_mean(x, dims=[-1], correction=0, keepdim=True)\n y = fd.ops.sub(x, mean)\n var = fd.ops.add(var, fd.define_scalar(1e-5))\n y = fd.ops.mul(y, fd.ops.rsqrt(var))\n shape = fd.ops.shape(x)\n w = fd.ops.broadcast_in_dim(w, shape=shape, broadcast_dims=[-1])\n y = fd.ops.mul(y, w)\n b = fd.ops.broadcast_in_dim(b, shape=shape, broadcast_dims=[-1])\n y = fd.ops.add(y, b)\n y = fd.ops.cast(y, dtype=io_dtype)\n return y\n\n\ndef gating(\n fd: FusionDefinition,\n z: TensorView,\n w_p: TensorView,\n z_in: TensorView,\n w_g: TensorView,\n) -> TensorView:\n io_dtype = z.dtype()\n p = fd.ops.linear(z, w_p)\n g = fd.ops.linear(z_in, w_g)\n g = fd.ops.sigmoid(g)\n z = fd.ops.mul(p, g)\n return fd.ops.cast(z, dtype=io_dtype)\n\n\n# https://elanapearl.github.io/blog/2024/the-illustrated-alphafold/#triangle-updates\n#\n# Jumper, J., Evans, R., Pritzel, A. et al. Highly accurate protein structure\n# prediction with AlphaFold. Nature 596, 583–589 (2021).\n# https://doi.org/10.1038/s41586-021-03819-2\n# (see Supplementary Methods 1.6.5 for details)\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"direction\", [Direction.OUTGOING, Direction.INCOMING], ids=lambda d: d.name.lower()\n)\ndef test_triangle_updates(direction, multidevice_test):\n d = multidevice_test.size\n cp_size = 2\n if d % (cp_size * cp_size) != 0:\n pytest.skip(\n f\"We only support even split, so {d} has to be divisible by {cp_size * cp_size} for {cp_size=}.\"\n )\n dp_size = d // (cp_size * cp_size)\n\n c_z = _DEFAULT_CONFIG.c_z\n\n with FusionDefinition() as fd:\n z_in_tv = fd.define_tensor(\n shape=[-1, -1, -1, c_z],\n dtype=DataType.BFloat16,\n contiguity=True,\n ) # [b, i, j, c_z]\n w_norm_in = fd.define_tensor(\n shape=[c_z], dtype=DataType.BFloat16, contiguity=True\n )\n b_norm_in = fd.define_tensor(\n shape=[c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_p_in = fd.define_tensor(\n shape=[c_z * 2, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_g_in = fd.define_tensor(\n shape=[c_z * 2, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_norm_out = fd.define_tensor(\n shape=[c_z], dtype=DataType.BFloat16, contiguity=True\n )\n b_norm_out = fd.define_tensor(\n shape=[c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_p_out = fd.define_tensor(\n shape=[c_z, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_g_out = fd.define_tensor(\n shape=[c_z, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n # Masking is used in an internal implementation: http://nv/e-4\n mask_tv = fd.define_tensor(\n shape=[-1, -1, -1], dtype=DataType.Bool, contiguity=True\n ) # [b, i, j]\n\n batch_size = fd.ops.size(z_in_tv, 0)\n n_tokens = fd.ops.size(z_in_tv, 1)\n\n z_in = layer_norm(fd, z_in_tv, w_norm_in, b_norm_in)\n z = gating(fd, z_in, w_p_in, z_in, w_g_in)\n mask = fd.ops.broadcast_in_dim(\n mask_tv,\n shape=[batch_size, n_tokens, n_tokens, c_z],\n broadcast_dims=[0, 1, 2],\n )\n z = fd.ops.where(mask, z, 0.0)\n a = fd.ops.slice(z, [0, 0, 0, 0], [batch_size, n_tokens, n_tokens, c_z])\n b = fd.ops.slice(z, [0, 0, 0, c_z], [batch_size, n_tokens, n_tokens, c_z * 2])\n\n match direction:\n case Direction.OUTGOING:\n # z_out = einsum(\"bikc,bjkc->bijc\", a, b)\n a = fd.ops.permute(a, [0, 3, 1, 2]) # [b, c, i, k]\n b = fd.ops.permute(b, [0, 3, 2, 1]) # [b, c, k, j]\n case Direction.INCOMING:\n # z_out = einsum(\"bkic,bkjc->bijc\", a, b)\n a = fd.ops.permute(a, [0, 3, 2, 1]) # [b, c, i, k]\n b = fd.ops.permute(b, [0, 3, 1, 2]) # [b, c, k, j]\n z = fd.ops.matmul(a, b) # [b, c, i, j]\n matmul_out = z\n z = fd.ops.permute(z, [0, 2, 3, 1]) # [b, i, j, c]\n\n z = layer_norm(fd, z, w_norm_out, b_norm_out)\n z = gating(fd, z, w_p_out, z_in, w_g_out)\n fd.add_output(z)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, cp_size, cp_size)\n )\n for tv in [\n z_in_tv,\n w_norm_in,\n b_norm_in,\n w_p_in,\n w_g_in,\n w_norm_out,\n b_norm_out,\n w_p_out,\n w_g_out,\n mask_tv,\n matmul_out,\n ]:\n tv.set_device_mesh(mesh)\n\n for tv in [z_in_tv, mask_tv]:\n tv.outer_split(2, cp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n tv.outer_split(1, cp_size)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_y)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_z)\n\n # TODO(#5901): this can be avoided with a better sharding propagation.\n #\n # matmul_out is of shape [b, c, i, j]. We shard `b` by `DIDz`, `i` by\n # `DIDy`, and `j` by `DIDx`.\n matmul_out.outer_split(-1, cp_size)\n match direction:\n case Direction.OUTGOING:\n matmul_out.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n case Direction.INCOMING:\n matmul_out.axis(-2).parallelize(nvfuser.ParallelType.mesh_y)\n matmul_out.outer_split(3, cp_size)\n matmul_out.axis(3).parallelize(nvfuser.ParallelType.mesh_x)\n matmul_out.outer_split(2, cp_size)\n matmul_out.axis(2).parallelize(nvfuser.ParallelType.mesh_y)\n matmul_out.outer_split(0, dp_size)\n matmul_out.axis(0).parallelize(nvfuser.ParallelType.mesh_z)\n\n batch_per_rank = 3\n n_tokens_per_rank = 5\n z_in_ref = torch.testing.make_tensor(\n batch_per_rank * dp_size,\n n_tokens_per_rank * cp_size,\n n_tokens_per_rank * cp_size,\n c_z,\n dtype=torch.bfloat16,\n device=\"cpu\",\n )\n mask_ref = torch.testing.make_tensor(\n batch_per_rank * dp_size,\n n_tokens_per_rank * cp_size,\n n_tokens_per_rank * cp_size,\n dtype=torch.bool,\n device=\"cpu\",\n )\n\n z_in = multidevice_test.shard_tensor(z_in_ref, z_in_tv)\n w_norm_in = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n b_norm_in = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n w_p_in = torch.testing.make_tensor(\n c_z * 2, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_g_in = torch.testing.make_tensor(\n c_z * 2, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_norm_out = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n b_norm_out = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n w_p_out = torch.testing.make_tensor(c_z, c_z, dtype=torch.bfloat16, device=\"cuda\")\n w_g_out = torch.testing.make_tensor(c_z, c_z, dtype=torch.bfloat16, device=\"cuda\")\n mask = multidevice_test.shard_tensor(mask_ref, mask_tv)\n (z_out,) = fd.execute(\n [\n z_in,\n w_norm_in,\n b_norm_in,\n w_p_in,\n w_g_in,\n w_norm_out,\n b_norm_out,\n w_p_out,\n w_g_out,\n mask,\n ]\n )\n assert z_out.shape == (batch_per_rank, n_tokens_per_rank, n_tokens_per_rank, c_z)","source_hash":"ce359eedb34ce2b0e73089cc2973e947c6fa1738111d19de95521144e7fbff16","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_alphafold3.ModelConfig","uri":"program://Fuser/class/tests.python.multidevice.test_alphafold3.ModelConfig#L18-L21","kind":"class","name":"ModelConfig","path":"tests/python/multidevice/test_alphafold3.py","language":"python","start_line":18,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\n# This file contains certain building blocks of the AlphaFold3 model.\n\nimport pytest\nimport torch\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\n\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4\n\n\n_DEFAULT_CONFIG = ModelConfig()\n\n\nclass Direction(Enum):\n INCOMING = auto() # aka ending node\n OUTGOING = auto() # aka starting node\n\n\ndef layer_norm(\n fd: FusionDefinition, x: TensorView, w: TensorView, b: TensorView\n) -> TensorView:\n io_dtype = x.dtype()\n x = fd.ops.cast(x, dtype=DataType.Float)\n var, mean = fd.ops.var_mean(x, dims=[-1], correction=0, keepdim=True)\n y = fd.ops.sub(x, mean)\n var = fd.ops.add(var, fd.define_scalar(1e-5))\n y = fd.ops.mul(y, fd.ops.rsqrt(var))\n shape = fd.ops.shape(x)","source_hash":"ce359eedb34ce2b0e73089cc2973e947c6fa1738111d19de95521144e7fbff16","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_alphafold3.Direction","uri":"program://Fuser/class/tests.python.multidevice.test_alphafold3.Direction#L27-L29","kind":"class","name":"Direction","path":"tests/python/multidevice/test_alphafold3.py","language":"python","start_line":27,"end_line":29,"context_start_line":7,"context_end_line":49,"code":"\nimport pytest\nimport torch\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\n\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4\n\n\n_DEFAULT_CONFIG = ModelConfig()\n\n\nclass Direction(Enum):\n INCOMING = auto() # aka ending node\n OUTGOING = auto() # aka starting node\n\n\ndef layer_norm(\n fd: FusionDefinition, x: TensorView, w: TensorView, b: TensorView\n) -> TensorView:\n io_dtype = x.dtype()\n x = fd.ops.cast(x, dtype=DataType.Float)\n var, mean = fd.ops.var_mean(x, dims=[-1], correction=0, keepdim=True)\n y = fd.ops.sub(x, mean)\n var = fd.ops.add(var, fd.define_scalar(1e-5))\n y = fd.ops.mul(y, fd.ops.rsqrt(var))\n shape = fd.ops.shape(x)\n w = fd.ops.broadcast_in_dim(w, shape=shape, broadcast_dims=[-1])\n y = fd.ops.mul(y, w)\n b = fd.ops.broadcast_in_dim(b, shape=shape, broadcast_dims=[-1])\n y = fd.ops.add(y, b)\n y = fd.ops.cast(y, dtype=io_dtype)\n return y\n\n","source_hash":"ce359eedb34ce2b0e73089cc2973e947c6fa1738111d19de95521144e7fbff16","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_alphafold3.layer_norm","uri":"program://Fuser/function/tests.python.multidevice.test_alphafold3.layer_norm#L32-L47","kind":"function","name":"layer_norm","path":"tests/python/multidevice/test_alphafold3.py","language":"python","start_line":32,"end_line":47,"context_start_line":12,"context_end_line":67,"code":"\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\n\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4\n\n\n_DEFAULT_CONFIG = ModelConfig()\n\n\nclass Direction(Enum):\n INCOMING = auto() # aka ending node\n OUTGOING = auto() # aka starting node\n\n\ndef layer_norm(\n fd: FusionDefinition, x: TensorView, w: TensorView, b: TensorView\n) -> TensorView:\n io_dtype = x.dtype()\n x = fd.ops.cast(x, dtype=DataType.Float)\n var, mean = fd.ops.var_mean(x, dims=[-1], correction=0, keepdim=True)\n y = fd.ops.sub(x, mean)\n var = fd.ops.add(var, fd.define_scalar(1e-5))\n y = fd.ops.mul(y, fd.ops.rsqrt(var))\n shape = fd.ops.shape(x)\n w = fd.ops.broadcast_in_dim(w, shape=shape, broadcast_dims=[-1])\n y = fd.ops.mul(y, w)\n b = fd.ops.broadcast_in_dim(b, shape=shape, broadcast_dims=[-1])\n y = fd.ops.add(y, b)\n y = fd.ops.cast(y, dtype=io_dtype)\n return y\n\n\ndef gating(\n fd: FusionDefinition,\n z: TensorView,\n w_p: TensorView,\n z_in: TensorView,\n w_g: TensorView,\n) -> TensorView:\n io_dtype = z.dtype()\n p = fd.ops.linear(z, w_p)\n g = fd.ops.linear(z_in, w_g)\n g = fd.ops.sigmoid(g)\n z = fd.ops.mul(p, g)\n return fd.ops.cast(z, dtype=io_dtype)\n\n\n# https://elanapearl.github.io/blog/2024/the-illustrated-alphafold/#triangle-updates\n#\n# Jumper, J., Evans, R., Pritzel, A. et al. Highly accurate protein structure","source_hash":"ce359eedb34ce2b0e73089cc2973e947c6fa1738111d19de95521144e7fbff16","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_alphafold3.gating","uri":"program://Fuser/function/tests.python.multidevice.test_alphafold3.gating#L50-L62","kind":"function","name":"gating","path":"tests/python/multidevice/test_alphafold3.py","language":"python","start_line":50,"end_line":62,"context_start_line":30,"context_end_line":82,"code":"\n\ndef layer_norm(\n fd: FusionDefinition, x: TensorView, w: TensorView, b: TensorView\n) -> TensorView:\n io_dtype = x.dtype()\n x = fd.ops.cast(x, dtype=DataType.Float)\n var, mean = fd.ops.var_mean(x, dims=[-1], correction=0, keepdim=True)\n y = fd.ops.sub(x, mean)\n var = fd.ops.add(var, fd.define_scalar(1e-5))\n y = fd.ops.mul(y, fd.ops.rsqrt(var))\n shape = fd.ops.shape(x)\n w = fd.ops.broadcast_in_dim(w, shape=shape, broadcast_dims=[-1])\n y = fd.ops.mul(y, w)\n b = fd.ops.broadcast_in_dim(b, shape=shape, broadcast_dims=[-1])\n y = fd.ops.add(y, b)\n y = fd.ops.cast(y, dtype=io_dtype)\n return y\n\n\ndef gating(\n fd: FusionDefinition,\n z: TensorView,\n w_p: TensorView,\n z_in: TensorView,\n w_g: TensorView,\n) -> TensorView:\n io_dtype = z.dtype()\n p = fd.ops.linear(z, w_p)\n g = fd.ops.linear(z_in, w_g)\n g = fd.ops.sigmoid(g)\n z = fd.ops.mul(p, g)\n return fd.ops.cast(z, dtype=io_dtype)\n\n\n# https://elanapearl.github.io/blog/2024/the-illustrated-alphafold/#triangle-updates\n#\n# Jumper, J., Evans, R., Pritzel, A. et al. Highly accurate protein structure\n# prediction with AlphaFold. Nature 596, 583–589 (2021).\n# https://doi.org/10.1038/s41586-021-03819-2\n# (see Supplementary Methods 1.6.5 for details)\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"direction\", [Direction.OUTGOING, Direction.INCOMING], ids=lambda d: d.name.lower()\n)\ndef test_triangle_updates(direction, multidevice_test):\n d = multidevice_test.size\n cp_size = 2\n if d % (cp_size * cp_size) != 0:\n pytest.skip(\n f\"We only support even split, so {d} has to be divisible by {cp_size * cp_size} for {cp_size=}.\"\n )\n dp_size = d // (cp_size * cp_size)","source_hash":"ce359eedb34ce2b0e73089cc2973e947c6fa1738111d19de95521144e7fbff16","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_alphafold3.test_triangle_updates","uri":"program://Fuser/function/tests.python.multidevice.test_alphafold3.test_triangle_updates#L75-L241","kind":"function","name":"test_triangle_updates","path":"tests/python/multidevice/test_alphafold3.py","language":"python","start_line":75,"end_line":241,"context_start_line":55,"context_end_line":241,"code":" w_g: TensorView,\n) -> TensorView:\n io_dtype = z.dtype()\n p = fd.ops.linear(z, w_p)\n g = fd.ops.linear(z_in, w_g)\n g = fd.ops.sigmoid(g)\n z = fd.ops.mul(p, g)\n return fd.ops.cast(z, dtype=io_dtype)\n\n\n# https://elanapearl.github.io/blog/2024/the-illustrated-alphafold/#triangle-updates\n#\n# Jumper, J., Evans, R., Pritzel, A. et al. Highly accurate protein structure\n# prediction with AlphaFold. Nature 596, 583–589 (2021).\n# https://doi.org/10.1038/s41586-021-03819-2\n# (see Supplementary Methods 1.6.5 for details)\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"direction\", [Direction.OUTGOING, Direction.INCOMING], ids=lambda d: d.name.lower()\n)\ndef test_triangle_updates(direction, multidevice_test):\n d = multidevice_test.size\n cp_size = 2\n if d % (cp_size * cp_size) != 0:\n pytest.skip(\n f\"We only support even split, so {d} has to be divisible by {cp_size * cp_size} for {cp_size=}.\"\n )\n dp_size = d // (cp_size * cp_size)\n\n c_z = _DEFAULT_CONFIG.c_z\n\n with FusionDefinition() as fd:\n z_in_tv = fd.define_tensor(\n shape=[-1, -1, -1, c_z],\n dtype=DataType.BFloat16,\n contiguity=True,\n ) # [b, i, j, c_z]\n w_norm_in = fd.define_tensor(\n shape=[c_z], dtype=DataType.BFloat16, contiguity=True\n )\n b_norm_in = fd.define_tensor(\n shape=[c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_p_in = fd.define_tensor(\n shape=[c_z * 2, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_g_in = fd.define_tensor(\n shape=[c_z * 2, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_norm_out = fd.define_tensor(\n shape=[c_z], dtype=DataType.BFloat16, contiguity=True\n )\n b_norm_out = fd.define_tensor(\n shape=[c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_p_out = fd.define_tensor(\n shape=[c_z, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n w_g_out = fd.define_tensor(\n shape=[c_z, c_z], dtype=DataType.BFloat16, contiguity=True\n )\n # Masking is used in an internal implementation: http://nv/e-4\n mask_tv = fd.define_tensor(\n shape=[-1, -1, -1], dtype=DataType.Bool, contiguity=True\n ) # [b, i, j]\n\n batch_size = fd.ops.size(z_in_tv, 0)\n n_tokens = fd.ops.size(z_in_tv, 1)\n\n z_in = layer_norm(fd, z_in_tv, w_norm_in, b_norm_in)\n z = gating(fd, z_in, w_p_in, z_in, w_g_in)\n mask = fd.ops.broadcast_in_dim(\n mask_tv,\n shape=[batch_size, n_tokens, n_tokens, c_z],\n broadcast_dims=[0, 1, 2],\n )\n z = fd.ops.where(mask, z, 0.0)\n a = fd.ops.slice(z, [0, 0, 0, 0], [batch_size, n_tokens, n_tokens, c_z])\n b = fd.ops.slice(z, [0, 0, 0, c_z], [batch_size, n_tokens, n_tokens, c_z * 2])\n\n match direction:\n case Direction.OUTGOING:\n # z_out = einsum(\"bikc,bjkc->bijc\", a, b)\n a = fd.ops.permute(a, [0, 3, 1, 2]) # [b, c, i, k]\n b = fd.ops.permute(b, [0, 3, 2, 1]) # [b, c, k, j]\n case Direction.INCOMING:\n # z_out = einsum(\"bkic,bkjc->bijc\", a, b)\n a = fd.ops.permute(a, [0, 3, 2, 1]) # [b, c, i, k]\n b = fd.ops.permute(b, [0, 3, 1, 2]) # [b, c, k, j]\n z = fd.ops.matmul(a, b) # [b, c, i, j]\n matmul_out = z\n z = fd.ops.permute(z, [0, 2, 3, 1]) # [b, i, j, c]\n\n z = layer_norm(fd, z, w_norm_out, b_norm_out)\n z = gating(fd, z, w_p_out, z_in, w_g_out)\n fd.add_output(z)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, cp_size, cp_size)\n )\n for tv in [\n z_in_tv,\n w_norm_in,\n b_norm_in,\n w_p_in,\n w_g_in,\n w_norm_out,\n b_norm_out,\n w_p_out,\n w_g_out,\n mask_tv,\n matmul_out,\n ]:\n tv.set_device_mesh(mesh)\n\n for tv in [z_in_tv, mask_tv]:\n tv.outer_split(2, cp_size)\n tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n tv.outer_split(1, cp_size)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_y)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_z)\n\n # TODO(#5901): this can be avoided with a better sharding propagation.\n #\n # matmul_out is of shape [b, c, i, j]. We shard `b` by `DIDz`, `i` by\n # `DIDy`, and `j` by `DIDx`.\n matmul_out.outer_split(-1, cp_size)\n match direction:\n case Direction.OUTGOING:\n matmul_out.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n case Direction.INCOMING:\n matmul_out.axis(-2).parallelize(nvfuser.ParallelType.mesh_y)\n matmul_out.outer_split(3, cp_size)\n matmul_out.axis(3).parallelize(nvfuser.ParallelType.mesh_x)\n matmul_out.outer_split(2, cp_size)\n matmul_out.axis(2).parallelize(nvfuser.ParallelType.mesh_y)\n matmul_out.outer_split(0, dp_size)\n matmul_out.axis(0).parallelize(nvfuser.ParallelType.mesh_z)\n\n batch_per_rank = 3\n n_tokens_per_rank = 5\n z_in_ref = torch.testing.make_tensor(\n batch_per_rank * dp_size,\n n_tokens_per_rank * cp_size,\n n_tokens_per_rank * cp_size,\n c_z,\n dtype=torch.bfloat16,\n device=\"cpu\",\n )\n mask_ref = torch.testing.make_tensor(\n batch_per_rank * dp_size,\n n_tokens_per_rank * cp_size,\n n_tokens_per_rank * cp_size,\n dtype=torch.bool,\n device=\"cpu\",\n )\n\n z_in = multidevice_test.shard_tensor(z_in_ref, z_in_tv)\n w_norm_in = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n b_norm_in = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n w_p_in = torch.testing.make_tensor(\n c_z * 2, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_g_in = torch.testing.make_tensor(\n c_z * 2, c_z, dtype=torch.bfloat16, device=\"cuda\"\n )\n w_norm_out = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n b_norm_out = torch.testing.make_tensor(c_z, dtype=torch.bfloat16, device=\"cuda\")\n w_p_out = torch.testing.make_tensor(c_z, c_z, dtype=torch.bfloat16, device=\"cuda\")\n w_g_out = torch.testing.make_tensor(c_z, c_z, dtype=torch.bfloat16, device=\"cuda\")\n mask = multidevice_test.shard_tensor(mask_ref, mask_tv)\n (z_out,) = fd.execute(\n [\n z_in,\n w_norm_in,\n b_norm_in,\n w_p_in,\n w_g_in,\n w_norm_out,\n b_norm_out,\n w_p_out,\n w_g_out,\n mask,\n ]\n )\n assert z_out.shape == (batch_per_rank, n_tokens_per_rank, n_tokens_per_rank, c_z)","source_hash":"ce359eedb34ce2b0e73089cc2973e947c6fa1738111d19de95521144e7fbff16","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_communication","uri":"program://Fuser/module/tests.python.multidevice.test_communication#L1-L204","kind":"module","name":"tests.python.multidevice.test_communication","path":"tests/python/multidevice/test_communication.py","language":"python","start_line":1,"end_line":204,"context_start_line":1,"context_end_line":204,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition\n\n\n@pytest.mark.mpi\ndef test_allgather(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d * 4,), contiguity=True, dtype=DataType.Float)\n out = fd.ops.set(inp_tv)\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out.set_device_mesh(mesh)\n\n inp_ref = torch.randn(d * 4)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_allgather_2d(multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(f\"Number of devices ({d=}) must be divisible by {tp_size=}\")\n dp_size = d // tp_size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d).reshape(dp_size, tp_size))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.set(inp_tv)\n fd.add_output(out_tv)\n\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n inp_tv.outer_split(2, tp_size)\n inp_tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n rows_per_rank, cols_per_rank = 2, 3\n rows, cols = dp_size * rows_per_rank, tp_size * cols_per_rank\n inp_ref = torch.randn(rows, cols)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\n@pytest.mark.mpi\ndef test_allgather_expanded_broadcast(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([d], contiguity=True, dtype=DataType.Float)\n expanded = fd.ops.broadcast_in_dim(inp_tv, [d, 3], [0])\n out = fd.ops.set(expanded)\n fd.add_output(out)\n\n for tv in [inp_tv, expanded, out]:\n tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n expanded.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d)\n out_ref = inp_ref.unsqueeze(-1).expand(-1, 3)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_allreduce(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1, -1), contiguity=True, dtype=DataType.Float)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 2\n k = d * 3\n n = 5\n inp_ref = torch.randn(m, k, n)\n out_ref = inp_ref.sum(1)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_reduce_scatter(multidevice_test):\n d = multidevice_test.size\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d, d * 4), contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.sum(inp_tv, [0])\n fd.add_output(out_tv)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.set_device_mesh(mesh)\n out_tv.outer_split(-1, d)\n out_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d, d * 4)\n out_ref = inp_ref.sum(0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\n@pytest.mark.mpi\ndef test_reduce_scatter_noncontiguous(multidevice_test):\n d = multidevice_test.size\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d, 3, d * 4), contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.sum(inp_tv, [0])\n fd.add_output(out_tv)\n\n # inp: [iDID{d}, i{3}, i{d*4}]\n # out: [r{d}, i{3}, i{d*4}]\n # / \\\n # iDID{d} i{4}\n #\n # Unlike test_reduce_scatter, this leads to extra data copy because\n # the scattered axis is not outermost in allocation.\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.set_device_mesh(mesh)\n out_tv.outer_split(-1, d)\n out_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d, 3, d * 4)\n out_ref = inp_ref.sum(0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\n# AllToAll patterns seen in expert parallelism\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"inp_axis,out_axis\", [(0, 1), (1, 0)], ids=[\"dispatch\", \"combine\"]\n)\ndef test_alltoall(multidevice_test, inp_axis, out_axis):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n n = 3\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d, d * n), contiguity=True, dtype=DataType.Half)\n out_tv = fd.ops.set(inp_tv)\n fd.add_output(out_tv)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(inp_axis, d)\n inp_tv.axis(inp_axis).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.set_device_mesh(mesh)\n out_tv.outer_split(out_axis, d)\n out_tv.axis(out_axis).parallelize(nvfuser.ParallelType.mesh_x)\n\n in_ref = torch.randn(d, d * n, dtype=torch.float16)\n out_ref = in_ref\n\n inp = multidevice_test.shard_tensor(in_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))","source_hash":"10c383202c5fd2724914155f92a73bd6d631a0f73db87432b5dcaddc4abb6db3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_communication.test_allgather","uri":"program://Fuser/function/tests.python.multidevice.test_communication.test_allgather#L13-L33","kind":"function","name":"test_allgather","path":"tests/python/multidevice/test_communication.py","language":"python","start_line":13,"end_line":33,"context_start_line":1,"context_end_line":53,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition\n\n\n@pytest.mark.mpi\ndef test_allgather(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d * 4,), contiguity=True, dtype=DataType.Float)\n out = fd.ops.set(inp_tv)\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out.set_device_mesh(mesh)\n\n inp_ref = torch.randn(d * 4)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_allgather_2d(multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(f\"Number of devices ({d=}) must be divisible by {tp_size=}\")\n dp_size = d // tp_size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d).reshape(dp_size, tp_size))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.set(inp_tv)\n fd.add_output(out_tv)\n\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)","source_hash":"10c383202c5fd2724914155f92a73bd6d631a0f73db87432b5dcaddc4abb6db3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_communication.test_allgather_2d","uri":"program://Fuser/function/tests.python.multidevice.test_communication.test_allgather_2d#L37-L64","kind":"function","name":"test_allgather_2d","path":"tests/python/multidevice/test_communication.py","language":"python","start_line":37,"end_line":64,"context_start_line":17,"context_end_line":84,"code":" with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d * 4,), contiguity=True, dtype=DataType.Float)\n out = fd.ops.set(inp_tv)\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out.set_device_mesh(mesh)\n\n inp_ref = torch.randn(d * 4)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_allgather_2d(multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n if d % tp_size != 0:\n pytest.skip(f\"Number of devices ({d=}) must be divisible by {tp_size=}\")\n dp_size = d // tp_size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d).reshape(dp_size, tp_size))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.set(inp_tv)\n fd.add_output(out_tv)\n\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n inp_tv.outer_split(2, tp_size)\n inp_tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n rows_per_rank, cols_per_rank = 2, 3\n rows, cols = dp_size * rows_per_rank, tp_size * cols_per_rank\n inp_ref = torch.randn(rows, cols)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\n@pytest.mark.mpi\ndef test_allgather_expanded_broadcast(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([d], contiguity=True, dtype=DataType.Float)\n expanded = fd.ops.broadcast_in_dim(inp_tv, [d, 3], [0])\n out = fd.ops.set(expanded)\n fd.add_output(out)\n\n for tv in [inp_tv, expanded, out]:\n tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n expanded.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d)\n out_ref = inp_ref.unsqueeze(-1).expand(-1, 3)","source_hash":"10c383202c5fd2724914155f92a73bd6d631a0f73db87432b5dcaddc4abb6db3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_communication.test_allgather_expanded_broadcast","uri":"program://Fuser/function/tests.python.multidevice.test_communication.test_allgather_expanded_broadcast#L68-L88","kind":"function","name":"test_allgather_expanded_broadcast","path":"tests/python/multidevice/test_communication.py","language":"python","start_line":68,"end_line":88,"context_start_line":48,"context_end_line":108,"code":" fd.add_output(out_tv)\n\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.outer_split(0, dp_size)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n inp_tv.outer_split(2, tp_size)\n inp_tv.axis(2).parallelize(nvfuser.ParallelType.mesh_x)\n\n rows_per_rank, cols_per_rank = 2, 3\n rows, cols = dp_size * rows_per_rank, tp_size * cols_per_rank\n inp_ref = torch.randn(rows, cols)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\n@pytest.mark.mpi\ndef test_allgather_expanded_broadcast(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([d], contiguity=True, dtype=DataType.Float)\n expanded = fd.ops.broadcast_in_dim(inp_tv, [d, 3], [0])\n out = fd.ops.set(expanded)\n fd.add_output(out)\n\n for tv in [inp_tv, expanded, out]:\n tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n expanded.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d)\n out_ref = inp_ref.unsqueeze(-1).expand(-1, 3)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_allreduce(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1, -1), contiguity=True, dtype=DataType.Float)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 2\n k = d * 3\n n = 5\n inp_ref = torch.randn(m, k, n)","source_hash":"10c383202c5fd2724914155f92a73bd6d631a0f73db87432b5dcaddc4abb6db3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_communication.test_allreduce","uri":"program://Fuser/function/tests.python.multidevice.test_communication.test_allreduce#L92-L114","kind":"function","name":"test_allreduce","path":"tests/python/multidevice/test_communication.py","language":"python","start_line":92,"end_line":114,"context_start_line":72,"context_end_line":134,"code":" with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([d], contiguity=True, dtype=DataType.Float)\n expanded = fd.ops.broadcast_in_dim(inp_tv, [d, 3], [0])\n out = fd.ops.set(expanded)\n fd.add_output(out)\n\n for tv in [inp_tv, expanded, out]:\n tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n expanded.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d)\n out_ref = inp_ref.unsqueeze(-1).expand(-1, 3)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_allreduce(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1, -1), contiguity=True, dtype=DataType.Float)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 2\n k = d * 3\n n = 5\n inp_ref = torch.randn(m, k, n)\n out_ref = inp_ref.sum(1)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_reduce_scatter(multidevice_test):\n d = multidevice_test.size\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d, d * 4), contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.sum(inp_tv, [0])\n fd.add_output(out_tv)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.set_device_mesh(mesh)\n out_tv.outer_split(-1, d)\n out_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n","source_hash":"10c383202c5fd2724914155f92a73bd6d631a0f73db87432b5dcaddc4abb6db3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_communication.test_reduce_scatter","uri":"program://Fuser/function/tests.python.multidevice.test_communication.test_reduce_scatter#L118-L140","kind":"function","name":"test_reduce_scatter","path":"tests/python/multidevice/test_communication.py","language":"python","start_line":118,"end_line":140,"context_start_line":98,"context_end_line":160,"code":" out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 2\n k = d * 3\n n = 5\n inp_ref = torch.randn(m, k, n)\n out_ref = inp_ref.sum(1)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_reduce_scatter(multidevice_test):\n d = multidevice_test.size\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d, d * 4), contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.sum(inp_tv, [0])\n fd.add_output(out_tv)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.set_device_mesh(mesh)\n out_tv.outer_split(-1, d)\n out_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d, d * 4)\n out_ref = inp_ref.sum(0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\n@pytest.mark.mpi\ndef test_reduce_scatter_noncontiguous(multidevice_test):\n d = multidevice_test.size\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d, 3, d * 4), contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.sum(inp_tv, [0])\n fd.add_output(out_tv)\n\n # inp: [iDID{d}, i{3}, i{d*4}]\n # out: [r{d}, i{3}, i{d*4}]\n # / \\\n # iDID{d} i{4}\n #\n # Unlike test_reduce_scatter, this leads to extra data copy because\n # the scattered axis is not outermost in allocation.","source_hash":"10c383202c5fd2724914155f92a73bd6d631a0f73db87432b5dcaddc4abb6db3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_communication.test_reduce_scatter_noncontiguous","uri":"program://Fuser/function/tests.python.multidevice.test_communication.test_reduce_scatter_noncontiguous#L144-L173","kind":"function","name":"test_reduce_scatter_noncontiguous","path":"tests/python/multidevice/test_communication.py","language":"python","start_line":144,"end_line":173,"context_start_line":124,"context_end_line":193,"code":" inp_tv = fd.define_tensor((d, d * 4), contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.sum(inp_tv, [0])\n fd.add_output(out_tv)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.set_device_mesh(mesh)\n out_tv.outer_split(-1, d)\n out_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d, d * 4)\n out_ref = inp_ref.sum(0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\n@pytest.mark.mpi\ndef test_reduce_scatter_noncontiguous(multidevice_test):\n d = multidevice_test.size\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d, 3, d * 4), contiguity=True, dtype=DataType.Float)\n out_tv = fd.ops.sum(inp_tv, [0])\n fd.add_output(out_tv)\n\n # inp: [iDID{d}, i{3}, i{d*4}]\n # out: [r{d}, i{3}, i{d*4}]\n # / \\\n # iDID{d} i{4}\n #\n # Unlike test_reduce_scatter, this leads to extra data copy because\n # the scattered axis is not outermost in allocation.\n inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.set_device_mesh(mesh)\n out_tv.outer_split(-1, d)\n out_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d, 3, d * 4)\n out_ref = inp_ref.sum(0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\n# AllToAll patterns seen in expert parallelism\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"inp_axis,out_axis\", [(0, 1), (1, 0)], ids=[\"dispatch\", \"combine\"]\n)\ndef test_alltoall(multidevice_test, inp_axis, out_axis):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n n = 3\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d, d * n), contiguity=True, dtype=DataType.Half)\n out_tv = fd.ops.set(inp_tv)\n fd.add_output(out_tv)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(inp_axis, d)\n inp_tv.axis(inp_axis).parallelize(nvfuser.ParallelType.mesh_x)","source_hash":"10c383202c5fd2724914155f92a73bd6d631a0f73db87432b5dcaddc4abb6db3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_communication.test_alltoall","uri":"program://Fuser/function/tests.python.multidevice.test_communication.test_alltoall#L181-L204","kind":"function","name":"test_alltoall","path":"tests/python/multidevice/test_communication.py","language":"python","start_line":181,"end_line":204,"context_start_line":161,"context_end_line":204,"code":" inp_tv.set_device_mesh(mesh)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.set_device_mesh(mesh)\n out_tv.outer_split(-1, d)\n out_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d, 3, d * 4)\n out_ref = inp_ref.sum(0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\n# AllToAll patterns seen in expert parallelism\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"inp_axis,out_axis\", [(0, 1), (1, 0)], ids=[\"dispatch\", \"combine\"]\n)\ndef test_alltoall(multidevice_test, inp_axis, out_axis):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n n = 3\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d, d * n), contiguity=True, dtype=DataType.Half)\n out_tv = fd.ops.set(inp_tv)\n fd.add_output(out_tv)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(inp_axis, d)\n inp_tv.axis(inp_axis).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.set_device_mesh(mesh)\n out_tv.outer_split(out_axis, d)\n out_tv.axis(out_axis).parallelize(nvfuser.ParallelType.mesh_x)\n\n in_ref = torch.randn(d, d * n, dtype=torch.float16)\n out_ref = in_ref\n\n inp = multidevice_test.shard_tensor(in_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))","source_hash":"10c383202c5fd2724914155f92a73bd6d631a0f73db87432b5dcaddc4abb6db3","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_expert_parallel","uri":"program://Fuser/module/tests.python.multidevice.test_expert_parallel#L1-L189","kind":"module","name":"tests.python.multidevice.test_expert_parallel","path":"tests/python/multidevice/test_expert_parallel.py","language":"python","start_line":1,"end_line":189,"context_start_line":1,"context_end_line":189,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\nimport torch.distributed as dist\n\n\n# Partitions n into k integers whose sum is n.\ndef random_partition(n: int, k: int) -> torch.Tensor:\n offsets = torch.randint(0, n + 1, [k - 1]).tolist()\n # The last partition ends at index n.\n offsets.append(n)\n offsets.sort()\n\n sizes = []\n prev = 0\n for offset in offsets:\n sizes.append(offset - prev)\n prev = offset\n assert sum(sizes) == n\n assert len(sizes) == k\n return torch.tensor(sizes, device=\"cuda\")\n\n\ndef list_to_matrix(l: list, rows: int, cols: int) -> list[list]:\n return [l[row * cols : (row + 1) * cols] for row in range(rows)]\n\n\ndef matrix_to_list(m: list[list]) -> list:\n return [item for row in m for item in row]\n\n\n# This can be fused into one kernel.\ndef rank_first_to_expert_first(\n tokens: torch.Tensor, n_tokens_for_expert_from_rank: torch.Tensor\n) -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Rank first, expert second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(\n tokens_for_expert_from_rank, d, num_experts_per_rank\n )\n # list(zip(*matrix)) transposes the matrix.\n # Expert first, rank second\n tokens_for_expert_from_rank = list(zip(*tokens_for_expert_from_rank))\n tokens_for_expert_from_rank = matrix_to_list(tokens_for_expert_from_rank)\n tokens = torch.cat(tokens_for_expert_from_rank, dim=0)\n return tokens\n\n\n# This can be fused into one kernel as well.\ndef expert_first_to_rank_first(\n tokens: torch.Tensor, n_tokens_for_expert_from_rank: torch.Tensor\n) -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Expert first, rank second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.t().flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(\n tokens_for_expert_from_rank, num_experts_per_rank, d\n )\n # Rank first, expert second\n tokens_for_expert_from_rank = list(zip(*tokens_for_expert_from_rank))\n tokens_for_expert_from_rank = matrix_to_list(tokens_for_expert_from_rank)\n tokens = torch.cat(tokens_for_expert_from_rank, dim=0)\n return tokens\n\n\n# This test serves as the reference implementation for the expert parallelism\n# dispatch and combine logic. The test is written in a way that is easy to\n# understand, but not efficient.\n@pytest.mark.mpi\ndef test_dispatch_and_combine(setup_default_process_group):\n rank = dist.get_rank()\n # So RNG generates different numbers for each rank.\n torch.manual_seed(rank)\n\n d = dist.get_world_size()\n num_experts_per_rank = 3\n n_experts = d * num_experts_per_rank\n\n # Input tokens are distributed among ranks, so the effective sequence length is `n_tokens * d`.\n n_tokens = 12\n # GPU 0: [n_tokens_for_expert_0_from_rank_0, n_tokens_for_expert_1_from_rank_0, ..., n_tokens_for_expert_5_from_rank_0]\n # GPU 1: [n_tokens_for_expert_0_from_rank_1, n_tokens_for_expert_1_from_rank_1, ..., n_tokens_for_expert_5_from_rank_1]\n # Both sum to `n_tokens`.\n n_tokens_for_expert = random_partition(n_tokens, n_experts)\n\n # For illustration, input tokens are complex numbers of value `token_id + expert_id * j`.\n expert_ids = []\n for expert, n in enumerate(n_tokens_for_expert.tolist()):\n expert_ids.extend([expert] * n)\n tokens = (\n torch.arange(\n rank * n_tokens, (rank + 1) * n_tokens, dtype=torch.float, device=\"cuda\"\n )\n + torch.tensor(expert_ids, dtype=torch.float, device=\"cuda\") * 1j\n )\n\n # --------------------------------------------------------------------------\n # An expert-parallel MoE layer dispatches, processes, and combines tokens\n # in the following steps:\n #\n # Step 1: Tokens are dispatched to the rank hosting the corresponding expert.\n # --------------------------------------------------------------------------\n n_tokens_for_expert_from_rank = torch.empty(\n d, num_experts_per_rank, dtype=torch.int64, device=\"cuda\"\n )\n # The following all_to_all_single communicates the number of tokens each\n # rank sends to each expert. This way, we can compute `output_split_sizes`\n # of the next all_to_all_single. In a more efficient implementation (e.g.\n # https://www.perplexity.ai/hub/blog/efficient-and-portable-mixture-of-experts-communication),\n # the two `all_to_all_single`s can be fused into one kernel.\n #\n # GPU 0: [[n_tokens_for_expert_0_from_rank_0, n_tokens_for_expert_1_from_rank_0, n_tokens_for_expert_2_from_rank_0],\n # [n_tokens_for_expert_0_from_rank_1, n_tokens_for_expert_1_from_rank_1, n_tokens_for_expert_2_from_rank_1]]\n # GPU 1: [[n_tokens_for_expert_3_from_rank_0, n_tokens_for_expert_4_from_rank_0, n_tokens_for_expert_5_from_rank_0],\n # [n_tokens_for_expert_3_from_rank_1, n_tokens_for_expert_4_from_rank_1, n_tokens_for_expert_5_from_rank_1]]\n dist.all_to_all_single(n_tokens_for_expert_from_rank, n_tokens_for_expert)\n\n # Number of tokens to receive from each rank\n # GPU 0: [n_tokens_for_expert_012_from_rank_0, n_tokens_for_expert_012_from_rank_1]\n # GPU 1: [n_tokens_for_expert_345_from_rank_0, n_tokens_for_expert_345_from_rank_1]\n n_tokens_from_rank = n_tokens_for_expert_from_rank.sum(-1)\n\n # Number of tokens to send to each rank\n # GPU 0: [n_tokens_for_expert_012_from_rank_0, n_tokens_for_expert_345_from_rank_0]\n # GPU 1: [n_tokens_for_expert_012_from_rank_1, n_tokens_for_expert_345_from_rank_1]\n n_tokens_to_rank = n_tokens_for_expert.view(d, -1).sum(-1)\n\n tokens_by_rank = torch.empty(\n n_tokens_from_rank.sum(), dtype=torch.complex64, device=\"cuda\"\n )\n # GPU 0: tokens_for_expert_0_from_rank_0 || tokens_for_expert_1_from_rank_0 || tokens_for_expert_2_from_rank_0 || tokens_for_expert_0_from_rank_1 || tokens_for_expert_1_from_rank_1 || tokens_for_expert_2_from_rank_1\n # GPU 1: tokens_for_expert_3_from_rank_0 || tokens_for_expert_4_from_rank_0 || tokens_for_expert_5_from_rank_0 || tokens_for_expert_3_from_rank_1 || tokens_for_expert_4_from_rank_1 || tokens_for_expert_5_from_rank_1\n dist.all_to_all_single(\n tokens_by_rank, tokens, n_tokens_from_rank.tolist(), n_tokens_to_rank.tolist()\n )\n\n # --------------------------------------------------------------------------\n # Step 2: Each rank sorts the received tokens by expert ID.\n # --------------------------------------------------------------------------\n # GPU 0: tokens_for_expert_0_from_rank_0 || tokens_for_expert_0_from_rank_1 || tokens_for_expert_1_from_rank_0 || tokens_for_expert_1_from_rank_1 || tokens_for_expert_2_from_rank_0 || tokens_for_expert_2_from_rank_1\n # GPU 1: tokens_for_expert_3_from_rank_0 || tokens_for_expert_3_from_rank_1 || tokens_for_expert_4_from_rank_0 || tokens_for_expert_4_from_rank_1 || tokens_for_expert_5_from_rank_0 || tokens_for_expert_5_from_rank_1\n tokens_by_expert = rank_first_to_expert_first(\n tokens_by_rank, n_tokens_for_expert_from_rank\n )\n\n imag = torch.imag(tokens_by_expert)\n assert (imag >= num_experts_per_rank * rank).all()\n assert (imag < num_experts_per_rank * (rank + 1)).all()\n assert (imag[:-1] <= imag[1:]).all()\n\n # --------------------------------------------------------------------------\n # Step 3: Each rank processes the received tokens with their corresponding\n # experts. This is skipped by the test for simplicity.\n # --------------------------------------------------------------------------\n processed_tokens_by_expert = tokens_by_expert\n\n # --------------------------------------------------------------------------\n # Step 4: Each rank sorts the processed tokens by rank ID.\n # --------------------------------------------------------------------------\n # GPU 0: tokens_for_expert_0_from_rank_0 || tokens_for_expert_1_from_rank_0 || tokens_for_expert_2_from_rank_0 || tokens_for_expert_0_from_rank_1 || tokens_for_expert_1_from_rank_1 || tokens_for_expert_2_from_rank_1\n # GPU 1: tokens_for_expert_3_from_rank_0 || tokens_for_expert_4_from_rank_0 || tokens_for_expert_5_from_rank_0 || tokens_for_expert_3_from_rank_1 || tokens_for_expert_4_from_rank_1 || tokens_for_expert_5_from_rank_1\n processed_tokens_by_rank = expert_first_to_rank_first(\n processed_tokens_by_expert, n_tokens_for_expert_from_rank\n )\n\n # --------------------------------------------------------------------------\n # Step 5: Processed tokens are sent back to the original ranks.\n # --------------------------------------------------------------------------\n processed_tokens = torch.empty(n_tokens, dtype=torch.complex64, device=\"cuda\")\n # GPU 0: tokens_for_expert_0_from_rank_0 || tokens_for_expert_1_from_rank_0 || tokens_for_expert_2_from_rank_0 || tokens_for_expert_3_from_rank_0 || tokens_for_expert_4_from_rank_0 || tokens_for_expert_5_from_rank_0\n # GPU 1: tokens_for_expert_0_from_rank_1 || tokens_for_expert_1_from_rank_1 || tokens_for_expert_2_from_rank_1 || tokens_for_expert_3_from_rank_1 || tokens_for_expert_4_from_rank_1 || tokens_for_expert_5_from_rank_1\n dist.all_to_all_single(\n processed_tokens,\n processed_tokens_by_rank,\n n_tokens_to_rank.tolist(),\n n_tokens_from_rank.tolist(),\n )\n\n # Because we skipped expert processing, the processed tokens should be the\n # same as the original tokens.\n torch.testing.assert_close(processed_tokens, tokens, rtol=0, atol=0)","source_hash":"97fd6e8149ba6a16db8522d1d90eb3c483930251d4a36cc20625e750e97f82ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_expert_parallel.random_partition","uri":"program://Fuser/function/tests.python.multidevice.test_expert_parallel.random_partition#L11-L24","kind":"function","name":"random_partition","path":"tests/python/multidevice/test_expert_parallel.py","language":"python","start_line":11,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\nimport torch.distributed as dist\n\n\n# Partitions n into k integers whose sum is n.\ndef random_partition(n: int, k: int) -> torch.Tensor:\n offsets = torch.randint(0, n + 1, [k - 1]).tolist()\n # The last partition ends at index n.\n offsets.append(n)\n offsets.sort()\n\n sizes = []\n prev = 0\n for offset in offsets:\n sizes.append(offset - prev)\n prev = offset\n assert sum(sizes) == n\n assert len(sizes) == k\n return torch.tensor(sizes, device=\"cuda\")\n\n\ndef list_to_matrix(l: list, rows: int, cols: int) -> list[list]:\n return [l[row * cols : (row + 1) * cols] for row in range(rows)]\n\n\ndef matrix_to_list(m: list[list]) -> list:\n return [item for row in m for item in row]\n\n\n# This can be fused into one kernel.\ndef rank_first_to_expert_first(\n tokens: torch.Tensor, n_tokens_for_expert_from_rank: torch.Tensor\n) -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Rank first, expert second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(","source_hash":"97fd6e8149ba6a16db8522d1d90eb3c483930251d4a36cc20625e750e97f82ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_expert_parallel.list_to_matrix","uri":"program://Fuser/function/tests.python.multidevice.test_expert_parallel.list_to_matrix#L27-L28","kind":"function","name":"list_to_matrix","path":"tests/python/multidevice/test_expert_parallel.py","language":"python","start_line":27,"end_line":28,"context_start_line":7,"context_end_line":48,"code":"import torch.distributed as dist\n\n\n# Partitions n into k integers whose sum is n.\ndef random_partition(n: int, k: int) -> torch.Tensor:\n offsets = torch.randint(0, n + 1, [k - 1]).tolist()\n # The last partition ends at index n.\n offsets.append(n)\n offsets.sort()\n\n sizes = []\n prev = 0\n for offset in offsets:\n sizes.append(offset - prev)\n prev = offset\n assert sum(sizes) == n\n assert len(sizes) == k\n return torch.tensor(sizes, device=\"cuda\")\n\n\ndef list_to_matrix(l: list, rows: int, cols: int) -> list[list]:\n return [l[row * cols : (row + 1) * cols] for row in range(rows)]\n\n\ndef matrix_to_list(m: list[list]) -> list:\n return [item for row in m for item in row]\n\n\n# This can be fused into one kernel.\ndef rank_first_to_expert_first(\n tokens: torch.Tensor, n_tokens_for_expert_from_rank: torch.Tensor\n) -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Rank first, expert second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(\n tokens_for_expert_from_rank, d, num_experts_per_rank\n )\n # list(zip(*matrix)) transposes the matrix.\n # Expert first, rank second","source_hash":"97fd6e8149ba6a16db8522d1d90eb3c483930251d4a36cc20625e750e97f82ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_expert_parallel.matrix_to_list","uri":"program://Fuser/function/tests.python.multidevice.test_expert_parallel.matrix_to_list#L31-L32","kind":"function","name":"matrix_to_list","path":"tests/python/multidevice/test_expert_parallel.py","language":"python","start_line":31,"end_line":32,"context_start_line":11,"context_end_line":52,"code":"def random_partition(n: int, k: int) -> torch.Tensor:\n offsets = torch.randint(0, n + 1, [k - 1]).tolist()\n # The last partition ends at index n.\n offsets.append(n)\n offsets.sort()\n\n sizes = []\n prev = 0\n for offset in offsets:\n sizes.append(offset - prev)\n prev = offset\n assert sum(sizes) == n\n assert len(sizes) == k\n return torch.tensor(sizes, device=\"cuda\")\n\n\ndef list_to_matrix(l: list, rows: int, cols: int) -> list[list]:\n return [l[row * cols : (row + 1) * cols] for row in range(rows)]\n\n\ndef matrix_to_list(m: list[list]) -> list:\n return [item for row in m for item in row]\n\n\n# This can be fused into one kernel.\ndef rank_first_to_expert_first(\n tokens: torch.Tensor, n_tokens_for_expert_from_rank: torch.Tensor\n) -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Rank first, expert second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(\n tokens_for_expert_from_rank, d, num_experts_per_rank\n )\n # list(zip(*matrix)) transposes the matrix.\n # Expert first, rank second\n tokens_for_expert_from_rank = list(zip(*tokens_for_expert_from_rank))\n tokens_for_expert_from_rank = matrix_to_list(tokens_for_expert_from_rank)\n tokens = torch.cat(tokens_for_expert_from_rank, dim=0)\n return tokens","source_hash":"97fd6e8149ba6a16db8522d1d90eb3c483930251d4a36cc20625e750e97f82ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_expert_parallel.rank_first_to_expert_first","uri":"program://Fuser/function/tests.python.multidevice.test_expert_parallel.rank_first_to_expert_first#L36-L52","kind":"function","name":"rank_first_to_expert_first","path":"tests/python/multidevice/test_expert_parallel.py","language":"python","start_line":36,"end_line":52,"context_start_line":16,"context_end_line":72,"code":"\n sizes = []\n prev = 0\n for offset in offsets:\n sizes.append(offset - prev)\n prev = offset\n assert sum(sizes) == n\n assert len(sizes) == k\n return torch.tensor(sizes, device=\"cuda\")\n\n\ndef list_to_matrix(l: list, rows: int, cols: int) -> list[list]:\n return [l[row * cols : (row + 1) * cols] for row in range(rows)]\n\n\ndef matrix_to_list(m: list[list]) -> list:\n return [item for row in m for item in row]\n\n\n# This can be fused into one kernel.\ndef rank_first_to_expert_first(\n tokens: torch.Tensor, n_tokens_for_expert_from_rank: torch.Tensor\n) -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Rank first, expert second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(\n tokens_for_expert_from_rank, d, num_experts_per_rank\n )\n # list(zip(*matrix)) transposes the matrix.\n # Expert first, rank second\n tokens_for_expert_from_rank = list(zip(*tokens_for_expert_from_rank))\n tokens_for_expert_from_rank = matrix_to_list(tokens_for_expert_from_rank)\n tokens = torch.cat(tokens_for_expert_from_rank, dim=0)\n return tokens\n\n\n# This can be fused into one kernel as well.\ndef expert_first_to_rank_first(\n tokens: torch.Tensor, n_tokens_for_expert_from_rank: torch.Tensor\n) -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Expert first, rank second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.t().flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(\n tokens_for_expert_from_rank, num_experts_per_rank, d\n )\n # Rank first, expert second\n tokens_for_expert_from_rank = list(zip(*tokens_for_expert_from_rank))\n tokens_for_expert_from_rank = matrix_to_list(tokens_for_expert_from_rank)\n tokens = torch.cat(tokens_for_expert_from_rank, dim=0)\n return tokens\n","source_hash":"97fd6e8149ba6a16db8522d1d90eb3c483930251d4a36cc20625e750e97f82ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_expert_parallel.expert_first_to_rank_first","uri":"program://Fuser/function/tests.python.multidevice.test_expert_parallel.expert_first_to_rank_first#L56-L71","kind":"function","name":"expert_first_to_rank_first","path":"tests/python/multidevice/test_expert_parallel.py","language":"python","start_line":56,"end_line":71,"context_start_line":36,"context_end_line":91,"code":"def rank_first_to_expert_first(\n tokens: torch.Tensor, n_tokens_for_expert_from_rank: torch.Tensor\n) -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Rank first, expert second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(\n tokens_for_expert_from_rank, d, num_experts_per_rank\n )\n # list(zip(*matrix)) transposes the matrix.\n # Expert first, rank second\n tokens_for_expert_from_rank = list(zip(*tokens_for_expert_from_rank))\n tokens_for_expert_from_rank = matrix_to_list(tokens_for_expert_from_rank)\n tokens = torch.cat(tokens_for_expert_from_rank, dim=0)\n return tokens\n\n\n# This can be fused into one kernel as well.\ndef expert_first_to_rank_first(\n tokens: torch.Tensor, n_tokens_for_expert_from_rank: torch.Tensor\n) -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Expert first, rank second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.t().flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(\n tokens_for_expert_from_rank, num_experts_per_rank, d\n )\n # Rank first, expert second\n tokens_for_expert_from_rank = list(zip(*tokens_for_expert_from_rank))\n tokens_for_expert_from_rank = matrix_to_list(tokens_for_expert_from_rank)\n tokens = torch.cat(tokens_for_expert_from_rank, dim=0)\n return tokens\n\n\n# This test serves as the reference implementation for the expert parallelism\n# dispatch and combine logic. The test is written in a way that is easy to\n# understand, but not efficient.\n@pytest.mark.mpi\ndef test_dispatch_and_combine(setup_default_process_group):\n rank = dist.get_rank()\n # So RNG generates different numbers for each rank.\n torch.manual_seed(rank)\n\n d = dist.get_world_size()\n num_experts_per_rank = 3\n n_experts = d * num_experts_per_rank\n\n # Input tokens are distributed among ranks, so the effective sequence length is `n_tokens * d`.\n n_tokens = 12\n # GPU 0: [n_tokens_for_expert_0_from_rank_0, n_tokens_for_expert_1_from_rank_0, ..., n_tokens_for_expert_5_from_rank_0]\n # GPU 1: [n_tokens_for_expert_0_from_rank_1, n_tokens_for_expert_1_from_rank_1, ..., n_tokens_for_expert_5_from_rank_1]\n # Both sum to `n_tokens`.","source_hash":"97fd6e8149ba6a16db8522d1d90eb3c483930251d4a36cc20625e750e97f82ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_expert_parallel.test_dispatch_and_combine","uri":"program://Fuser/function/tests.python.multidevice.test_expert_parallel.test_dispatch_and_combine#L78-L189","kind":"function","name":"test_dispatch_and_combine","path":"tests/python/multidevice/test_expert_parallel.py","language":"python","start_line":78,"end_line":189,"context_start_line":58,"context_end_line":189,"code":") -> torch.Tensor:\n d, num_experts_per_rank = n_tokens_for_expert_from_rank.size()\n # Expert first, rank second\n tokens_for_expert_from_rank = tokens.split(\n n_tokens_for_expert_from_rank.t().flatten().tolist()\n )\n tokens_for_expert_from_rank = list_to_matrix(\n tokens_for_expert_from_rank, num_experts_per_rank, d\n )\n # Rank first, expert second\n tokens_for_expert_from_rank = list(zip(*tokens_for_expert_from_rank))\n tokens_for_expert_from_rank = matrix_to_list(tokens_for_expert_from_rank)\n tokens = torch.cat(tokens_for_expert_from_rank, dim=0)\n return tokens\n\n\n# This test serves as the reference implementation for the expert parallelism\n# dispatch and combine logic. The test is written in a way that is easy to\n# understand, but not efficient.\n@pytest.mark.mpi\ndef test_dispatch_and_combine(setup_default_process_group):\n rank = dist.get_rank()\n # So RNG generates different numbers for each rank.\n torch.manual_seed(rank)\n\n d = dist.get_world_size()\n num_experts_per_rank = 3\n n_experts = d * num_experts_per_rank\n\n # Input tokens are distributed among ranks, so the effective sequence length is `n_tokens * d`.\n n_tokens = 12\n # GPU 0: [n_tokens_for_expert_0_from_rank_0, n_tokens_for_expert_1_from_rank_0, ..., n_tokens_for_expert_5_from_rank_0]\n # GPU 1: [n_tokens_for_expert_0_from_rank_1, n_tokens_for_expert_1_from_rank_1, ..., n_tokens_for_expert_5_from_rank_1]\n # Both sum to `n_tokens`.\n n_tokens_for_expert = random_partition(n_tokens, n_experts)\n\n # For illustration, input tokens are complex numbers of value `token_id + expert_id * j`.\n expert_ids = []\n for expert, n in enumerate(n_tokens_for_expert.tolist()):\n expert_ids.extend([expert] * n)\n tokens = (\n torch.arange(\n rank * n_tokens, (rank + 1) * n_tokens, dtype=torch.float, device=\"cuda\"\n )\n + torch.tensor(expert_ids, dtype=torch.float, device=\"cuda\") * 1j\n )\n\n # --------------------------------------------------------------------------\n # An expert-parallel MoE layer dispatches, processes, and combines tokens\n # in the following steps:\n #\n # Step 1: Tokens are dispatched to the rank hosting the corresponding expert.\n # --------------------------------------------------------------------------\n n_tokens_for_expert_from_rank = torch.empty(\n d, num_experts_per_rank, dtype=torch.int64, device=\"cuda\"\n )\n # The following all_to_all_single communicates the number of tokens each\n # rank sends to each expert. This way, we can compute `output_split_sizes`\n # of the next all_to_all_single. In a more efficient implementation (e.g.\n # https://www.perplexity.ai/hub/blog/efficient-and-portable-mixture-of-experts-communication),\n # the two `all_to_all_single`s can be fused into one kernel.\n #\n # GPU 0: [[n_tokens_for_expert_0_from_rank_0, n_tokens_for_expert_1_from_rank_0, n_tokens_for_expert_2_from_rank_0],\n # [n_tokens_for_expert_0_from_rank_1, n_tokens_for_expert_1_from_rank_1, n_tokens_for_expert_2_from_rank_1]]\n # GPU 1: [[n_tokens_for_expert_3_from_rank_0, n_tokens_for_expert_4_from_rank_0, n_tokens_for_expert_5_from_rank_0],\n # [n_tokens_for_expert_3_from_rank_1, n_tokens_for_expert_4_from_rank_1, n_tokens_for_expert_5_from_rank_1]]\n dist.all_to_all_single(n_tokens_for_expert_from_rank, n_tokens_for_expert)\n\n # Number of tokens to receive from each rank\n # GPU 0: [n_tokens_for_expert_012_from_rank_0, n_tokens_for_expert_012_from_rank_1]\n # GPU 1: [n_tokens_for_expert_345_from_rank_0, n_tokens_for_expert_345_from_rank_1]\n n_tokens_from_rank = n_tokens_for_expert_from_rank.sum(-1)\n\n # Number of tokens to send to each rank\n # GPU 0: [n_tokens_for_expert_012_from_rank_0, n_tokens_for_expert_345_from_rank_0]\n # GPU 1: [n_tokens_for_expert_012_from_rank_1, n_tokens_for_expert_345_from_rank_1]\n n_tokens_to_rank = n_tokens_for_expert.view(d, -1).sum(-1)\n\n tokens_by_rank = torch.empty(\n n_tokens_from_rank.sum(), dtype=torch.complex64, device=\"cuda\"\n )\n # GPU 0: tokens_for_expert_0_from_rank_0 || tokens_for_expert_1_from_rank_0 || tokens_for_expert_2_from_rank_0 || tokens_for_expert_0_from_rank_1 || tokens_for_expert_1_from_rank_1 || tokens_for_expert_2_from_rank_1\n # GPU 1: tokens_for_expert_3_from_rank_0 || tokens_for_expert_4_from_rank_0 || tokens_for_expert_5_from_rank_0 || tokens_for_expert_3_from_rank_1 || tokens_for_expert_4_from_rank_1 || tokens_for_expert_5_from_rank_1\n dist.all_to_all_single(\n tokens_by_rank, tokens, n_tokens_from_rank.tolist(), n_tokens_to_rank.tolist()\n )\n\n # --------------------------------------------------------------------------\n # Step 2: Each rank sorts the received tokens by expert ID.\n # --------------------------------------------------------------------------\n # GPU 0: tokens_for_expert_0_from_rank_0 || tokens_for_expert_0_from_rank_1 || tokens_for_expert_1_from_rank_0 || tokens_for_expert_1_from_rank_1 || tokens_for_expert_2_from_rank_0 || tokens_for_expert_2_from_rank_1\n # GPU 1: tokens_for_expert_3_from_rank_0 || tokens_for_expert_3_from_rank_1 || tokens_for_expert_4_from_rank_0 || tokens_for_expert_4_from_rank_1 || tokens_for_expert_5_from_rank_0 || tokens_for_expert_5_from_rank_1\n tokens_by_expert = rank_first_to_expert_first(\n tokens_by_rank, n_tokens_for_expert_from_rank\n )\n\n imag = torch.imag(tokens_by_expert)\n assert (imag >= num_experts_per_rank * rank).all()\n assert (imag < num_experts_per_rank * (rank + 1)).all()\n assert (imag[:-1] <= imag[1:]).all()\n\n # --------------------------------------------------------------------------\n # Step 3: Each rank processes the received tokens with their corresponding\n # experts. This is skipped by the test for simplicity.\n # --------------------------------------------------------------------------\n processed_tokens_by_expert = tokens_by_expert\n\n # --------------------------------------------------------------------------\n # Step 4: Each rank sorts the processed tokens by rank ID.\n # --------------------------------------------------------------------------\n # GPU 0: tokens_for_expert_0_from_rank_0 || tokens_for_expert_1_from_rank_0 || tokens_for_expert_2_from_rank_0 || tokens_for_expert_0_from_rank_1 || tokens_for_expert_1_from_rank_1 || tokens_for_expert_2_from_rank_1\n # GPU 1: tokens_for_expert_3_from_rank_0 || tokens_for_expert_4_from_rank_0 || tokens_for_expert_5_from_rank_0 || tokens_for_expert_3_from_rank_1 || tokens_for_expert_4_from_rank_1 || tokens_for_expert_5_from_rank_1\n processed_tokens_by_rank = expert_first_to_rank_first(\n processed_tokens_by_expert, n_tokens_for_expert_from_rank\n )\n\n # --------------------------------------------------------------------------\n # Step 5: Processed tokens are sent back to the original ranks.\n # --------------------------------------------------------------------------\n processed_tokens = torch.empty(n_tokens, dtype=torch.complex64, device=\"cuda\")\n # GPU 0: tokens_for_expert_0_from_rank_0 || tokens_for_expert_1_from_rank_0 || tokens_for_expert_2_from_rank_0 || tokens_for_expert_3_from_rank_0 || tokens_for_expert_4_from_rank_0 || tokens_for_expert_5_from_rank_0\n # GPU 1: tokens_for_expert_0_from_rank_1 || tokens_for_expert_1_from_rank_1 || tokens_for_expert_2_from_rank_1 || tokens_for_expert_3_from_rank_1 || tokens_for_expert_4_from_rank_1 || tokens_for_expert_5_from_rank_1\n dist.all_to_all_single(\n processed_tokens,\n processed_tokens_by_rank,\n n_tokens_to_rank.tolist(),\n n_tokens_from_rank.tolist(),\n )\n\n # Because we skipped expert processing, the processed tokens should be the\n # same as the original tokens.\n torch.testing.assert_close(processed_tokens, tokens, rtol=0, atol=0)","source_hash":"97fd6e8149ba6a16db8522d1d90eb3c483930251d4a36cc20625e750e97f82ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer","uri":"program://Fuser/module/tests.python.multidevice.test_transformer#L1-L1188","kind":"module","name":"tests.python.multidevice.test_transformer","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":1,"end_line":1188,"context_start_line":1,"context_end_line":1188,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\n\nimport torch\nimport torch.nn.functional as F\n\nimport nvfuser_direct as nvfuser\nfrom . import Parallelism\nfrom .benchmark_utils import get_benchmark_fns\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom python.direct_utils import (\n create_sdpa_rng_tensors,\n is_pre_ampere,\n)\n\n\n@pytest.mark.mpi\ndef test_grouped_mlp(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n g = 4\n k = 16\n n = 16 * d\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, k], dtype=DataType.BFloat16, contiguity=True)\n gate_w_tv = fd.define_tensor(\n [g, k, n], dtype=DataType.BFloat16, contiguity=True\n )\n up_w_tv = fd.define_tensor([g, k, n], dtype=DataType.BFloat16, contiguity=True)\n down_w_tv = fd.define_tensor(\n [g, n, k], dtype=DataType.BFloat16, contiguity=True\n )\n offsets_tv = fd.define_tensor([g], dtype=DataType.Int32, contiguity=True)\n\n gate_out = fd.ops.grouped_mm(inp_tv, gate_w_tv, offsets_tv)\n gate_out = fd.ops.cast(gate_out, DataType.Float)\n\n up_out = fd.ops.grouped_mm(inp_tv, up_w_tv, offsets_tv)\n\n mul_out = fd.ops.mul(fd.ops.silu(gate_out), up_out)\n mul_out = fd.ops.cast(mul_out, DataType.BFloat16)\n\n out = fd.ops.grouped_mm(mul_out, down_w_tv, offsets_tv)\n\n fd.add_output(out)\n\n for t in [inp_tv, gate_w_tv, up_w_tv, down_w_tv, offsets_tv]:\n t.set_device_mesh(mesh)\n\n for w in [gate_w_tv, up_w_tv]:\n w.split(-1, d, False)\n w.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n down_w_tv.split(-2, d, False)\n down_w_tv.axis(-3).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 32\n assert m % g == 0\n group_sizes = [m // g] * g\n inp_ref = torch.randn(m, k, dtype=torch.bfloat16)\n gate_w_ref = torch.randn(g, k, n, dtype=torch.bfloat16)\n up_w_ref = torch.randn(g, k, n, dtype=torch.bfloat16)\n down_w_ref = torch.randn(g, n, k, dtype=torch.bfloat16)\n offsets_ref = torch.cumsum(torch.tensor(group_sizes), 0, dtype=torch.int32)\n group_outs = [\n (F.silu(group_in @ group_gate_w) * (group_in @ group_up_w)) @ group_down_w\n for group_in, group_gate_w, group_up_w, group_down_w in zip(\n inp_ref.split(group_sizes),\n gate_w_ref.unbind(),\n up_w_ref.unbind(),\n down_w_ref.unbind(),\n )\n ]\n out_ref = torch.cat(group_outs, dim=0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n gate_w = multidevice_test.shard_tensor(gate_w_ref, gate_w_tv)\n up_w = multidevice_test.shard_tensor(up_w_ref, up_w_tv)\n down_w = multidevice_test.shard_tensor(down_w_ref, down_w_tv)\n offsets = multidevice_test.shard_tensor(offsets_ref, offsets_tv)\n (out,) = fd.execute([inp, gate_w, up_w, down_w, offsets])\n\n # Unfortunately, I couldn't come up with meaningful thresholds to pass the\n # comparison even with one GPU. I manually examined the results. They are\n # not completely off, which is good.\n #\n # I tried several easy things:\n # 1. run the reference implementation on GPU,\n # 2. upcast tensors to `float` here and there in the reference implementation.\n #\n # None of them significantly reduce the error. It could be a problem in the\n # grouped gemm kernel.\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1.0, atol=float(\"inf\"))\n\n\n# The following benchmarks the fusion generated from NanoGPTBlockBenchmark in Thunder.\n# To generate the fusion, use the following snippet which turns on the necessary options\n# to get a single nvfuser definition.\n# ```\n# from thunder.benchmarks import NanoGPTBlockBenchmark, NanoGPTConfig\n# from thunder.executors.nvfuserex import nvfuserex\n\n# config = NanoGPTConfig(seq_len=2048, n_head=96, n_embd=12288)\n# bench = NanoGPTBlockBenchmark(\n# batchdims=(1,), config=config, device=\"cuda:0\", dtype=thunder.bfloat16, requires_grad=True\n# )\n# args, kwargs = bench.make_batch()\n#\n# jfn = thunder.jit(\n# bench.fn(),\n# executors=[nvfuserex],\n# nv_enable_sdpa=True,\n# nv_enable_matmul=True,\n# nv_enable_linear=True,\n# disable_replace_uniform=True,\n# )\n# out = jfn(*args, **kwargs)\n# grads = torch.randn_like(out, device=\"cuda\", dtype=torch.bfloat16)\n# out.backward(grads)\n# print(thunder.last_traces(jfn)[-1].python_ctx()['nvFusion0'].last_used)\n# print(thunder.last_backward_traces(jfn)[-1].python_ctx()['nvFusion0'].last_used)\n# ```\n# Fusions generated from Thunder commit: b0dc72ef1a9825a70923ae1a270d919f5948c4ed\n\n\ndef transformer_forward_definition(\n fd: FusionDefinition, batch: int, sequence: int, head: int, hidden: int\n) -> None:\n # Same notations as in test_multidevice_transformer.cpp.\n b, s, h, e = batch, sequence, head, hidden\n inp = fd.define_tensor(\n shape=[b, s, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n layernorm0_weight = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n layernorm0_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n mha_linear0_weight = fd.define_tensor(\n shape=[e * 3, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n mha_linear0_bias = fd.define_tensor(\n shape=[e * 3],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n mha_linear1_weight = fd.define_tensor(\n shape=[e, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n mha_linear1_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n layernorm1_weight = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n layernorm1_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n mlp_linear0_weight = fd.define_tensor(\n shape=[e * 4, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n mlp_linear0_bias = fd.define_tensor(\n shape=[e * 4],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n mlp_linear1_weight = fd.define_tensor(\n shape=[e, e * 4],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n mlp_linear1_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n\n T13 = fd.ops.cast(inp, dtype=DataType.Float)\n T14, layernorm0_mean = fd.ops.var_mean(T13, dims=[2], correction=0, keepdim=False)\n T20 = fd.ops.broadcast_in_dim(T14, shape=[b, s, 1], broadcast_dims=[0, 1])\n T25 = fd.ops.broadcast_in_dim(\n layernorm0_mean, shape=[b, s, 1], broadcast_dims=[0, 1]\n )\n S26 = fd.define_scalar(1.00000e-05, dtype=DataType.Double)\n T27 = fd.ops.add(T20, S26)\n layernorm0_rstd = fd.ops.rsqrt(T27)\n T33 = fd.ops.broadcast_in_dim(T25, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T34 = fd.ops.sub(T13, T33)\n T39 = fd.ops.broadcast_in_dim(\n layernorm0_rstd, shape=[b, s, e], broadcast_dims=[0, 1, 2]\n )\n T40 = fd.ops.mul(T34, T39)\n T45 = fd.ops.broadcast_in_dim(\n layernorm0_weight, shape=[b, s, e], broadcast_dims=[2]\n )\n T46 = fd.ops.cast(T45, dtype=DataType.Float)\n T47 = fd.ops.mul(T40, T46)\n T52 = fd.ops.broadcast_in_dim(layernorm0_bias, shape=[b, s, e], broadcast_dims=[2])\n T53 = fd.ops.cast(T52, dtype=DataType.Float)\n T54 = fd.ops.add(T47, T53)\n T55 = fd.ops.cast(T54, dtype=DataType.BFloat16)\n mha_linear0_out = fd.ops.linear(T55, mha_linear0_weight, mha_linear0_bias)\n\n # Reshape before slice to avoid slicing a tensor along sharded dimension.\n # This is different from the single-GPU definition obtained from Thunder.\n T57 = fd.ops.reshape(mha_linear0_out, new_shape=[b, s, h, 3 * e // h])\n T69 = fd.ops.slice(T57, start_indices=[0, 0, 0, 0], end_indices=[b, s, h, e // h])\n T82 = fd.ops.slice(\n T57, start_indices=[0, 0, 0, e // h], end_indices=[b, s, h, 2 * e // h]\n )\n T95 = fd.ops.slice(\n T57, start_indices=[0, 0, 0, 2 * e // h], end_indices=[b, s, h, 3 * e // h]\n )\n\n T102 = fd.ops.permute(T82, dims=[0, 2, 1, 3])\n T109 = fd.ops.permute(T69, dims=[0, 2, 1, 3])\n T116 = fd.ops.permute(T95, dims=[0, 2, 1, 3])\n\n S117 = fd.define_scalar(0.100000, dtype=DataType.Double)\n S118 = fd.define_scalar(True, dtype=DataType.Bool)\n sdpa_out, sdpa_logsum_exp, sdpa_seed, sdpa_offset = fd.ops.sdpfa_fwd(\n T109, T102, T116, dropout_p=S117, is_causal=S118, scale=None\n )\n T123 = fd.ops.permute(sdpa_out, dims=[0, 2, 1, 3])\n T124 = fd.ops.stride_order(T123, stride_order=[3, 2, 1, 0])\n T129 = fd.ops.reshape(T124, new_shape=[b, s, e])\n mha_linear1_out = fd.ops.linear(T129, mha_linear1_weight, mha_linear1_bias)\n S131 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S132 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T137 = fd.ops.uniform(S131, S132, shape=[b, s, e], dtype=DataType.BFloat16)\n S138 = fd.define_scalar(0.900000, dtype=DataType.Double)\n mha_dropout_mask = fd.ops.lt(T137, S138)\n T140 = fd.ops.cast(mha_linear1_out, dtype=DataType.Float)\n T141 = fd.ops.cast(mha_dropout_mask, dtype=DataType.Float)\n T142 = fd.ops.mul(T140, T141)\n S143 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T144 = fd.ops.mul(T142, S143)\n T145 = fd.ops.add(T13, T144)\n T146, layernorm1_mean = fd.ops.var_mean(T145, dims=[2], correction=0, keepdim=False)\n T152 = fd.ops.broadcast_in_dim(T146, shape=[b, s, 1], broadcast_dims=[0, 1])\n T157 = fd.ops.broadcast_in_dim(\n layernorm1_mean, shape=[b, s, 1], broadcast_dims=[0, 1]\n )\n S158 = fd.define_scalar(1.00000e-05, dtype=DataType.Double)\n T159 = fd.ops.add(T152, S158)\n layernorm1_rstd = fd.ops.rsqrt(T159)\n T165 = fd.ops.broadcast_in_dim(T157, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T166 = fd.ops.sub(T145, T165)\n T171 = fd.ops.broadcast_in_dim(\n layernorm1_rstd, shape=[b, s, e], broadcast_dims=[0, 1, 2]\n )\n T172 = fd.ops.mul(T166, T171)\n T177 = fd.ops.broadcast_in_dim(\n layernorm1_weight, shape=[b, s, e], broadcast_dims=[2]\n )\n T178 = fd.ops.cast(T177, dtype=DataType.Float)\n T179 = fd.ops.mul(T172, T178)\n T184 = fd.ops.broadcast_in_dim(layernorm1_bias, shape=[b, s, e], broadcast_dims=[2])\n T185 = fd.ops.cast(T184, dtype=DataType.Float)\n T186 = fd.ops.add(T179, T185)\n T187 = fd.ops.cast(T186, dtype=DataType.BFloat16)\n mlp_linear0_out = fd.ops.linear(T187, mlp_linear0_weight, mlp_linear0_bias)\n T189 = fd.ops.cast(mlp_linear0_out, dtype=DataType.Float)\n T190 = fd.ops.mul(T189, T189)\n T191 = fd.ops.mul(T190, T189)\n S192 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T193 = fd.ops.mul(S192, T189)\n S194 = fd.define_scalar(0.0447150, dtype=DataType.Double)\n T195 = fd.ops.mul(S194, T191)\n T196 = fd.ops.add(T189, T195)\n S197 = fd.define_scalar(0.797885, dtype=DataType.Double)\n T198 = fd.ops.mul(S197, T196)\n T199 = fd.ops.tanh(T198)\n S200 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T201 = fd.ops.add(S200, T199)\n T202 = fd.ops.mul(T193, T201)\n T203 = fd.ops.cast(T202, dtype=DataType.BFloat16)\n mlp_linear1_out = fd.ops.linear(T203, mlp_linear1_weight, mlp_linear1_bias)\n S205 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S206 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T211 = fd.ops.uniform(S205, S206, shape=[b, s, e], dtype=DataType.BFloat16)\n S212 = fd.define_scalar(0.900000, dtype=DataType.Double)\n mlp_dropout_mask = fd.ops.lt(T211, S212)\n T214 = fd.ops.cast(mlp_linear1_out, dtype=DataType.Float)\n T215 = fd.ops.cast(mlp_dropout_mask, dtype=DataType.Float)\n T216 = fd.ops.mul(T214, T215)\n S217 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T218 = fd.ops.mul(T216, S217)\n T219 = fd.ops.add(T145, T218)\n out = fd.ops.cast(T219, dtype=DataType.BFloat16)\n fd.add_output(layernorm0_mean)\n fd.add_output(layernorm0_rstd)\n fd.add_output(mha_linear0_out)\n fd.add_output(sdpa_out)\n fd.add_output(sdpa_logsum_exp)\n fd.add_output(sdpa_seed)\n fd.add_output(sdpa_offset)\n fd.add_output(mha_linear1_out)\n fd.add_output(mha_dropout_mask)\n fd.add_output(layernorm1_mean)\n fd.add_output(layernorm1_rstd)\n fd.add_output(mlp_linear0_out)\n fd.add_output(mlp_dropout_mask)\n fd.add_output(out)\n\n\ndef transformer_forward_multidevice_schedule(\n fd: FusionDefinition, num_devices: int, parallelism: Parallelism\n):\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n inputs = fd.fusion.inputs()\n (\n inp,\n layernorm0_weight,\n layernorm0_bias,\n mha_linear0_weight,\n mha_linear0_bias,\n mha_linear1_weight,\n mha_linear1_bias,\n layernorm1_weight,\n layernorm1_bias,\n mlp_linear0_weight,\n mlp_linear0_bias,\n mlp_linear1_weight,\n mlp_linear1_bias,\n ) = inputs\n\n for tv in inputs:\n tv.set_device_mesh(mesh)\n\n if parallelism == Parallelism.SEQUENCE_PARALLEL:\n inp.outer_split(1, num_devices)\n inp.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n for tv in [\n mha_linear0_weight,\n mha_linear0_bias,\n mlp_linear0_weight,\n mlp_linear0_bias,\n ]:\n tv.outer_split(0, num_devices)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n for tv in [\n mha_linear1_weight,\n mlp_linear1_weight,\n ]:\n tv.outer_split(-1, num_devices)\n tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n\n# TODO(#2962): validate the numbers as well. Currently, the numbers are off\n# by a lot, making comparison infeasible.\ndef _assert_shape_dtype(\n t: torch.Tensor, expected_sizes: list[int], expected_dtype: torch.dtype\n) -> None:\n assert t.shape == torch.Size(expected_sizes)\n assert t.dtype == expected_dtype\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\n \"parallelism\",\n [Parallelism.TENSOR_PARALLEL, Parallelism.SEQUENCE_PARALLEL],\n ids=lambda p: p.name,\n)\n@pytest.mark.mpi\ndef test_transformer_forward(multidevice_test, benchmark, parallelism: Parallelism):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n b, s, h, e = 1, 2048, 96, 12288\n\n assert (\n e % h == 0\n ), f\"The hidden size ({e}) has to be divisible by the number of heads ({h}).\"\n\n if h % d != 0:\n pytest.skip(\n f\"We only support even DID split, so the number of heads ({h}) has \\\n to be divisible by the number of GPUs ({d}).\"\n )\n\n assert e * 4 % d == 0, (\n \"This is required to evenly DID split MLP. This condition is implied \"\n \"by the previous two checks; a fail would indicate a programming \"\n \"error. So I use `assert` instead of `pytest.skip`.\"\n )\n\n if parallelism == Parallelism.SEQUENCE_PARALLEL and s % d != 0:\n pytest.skip(\n f\"Sequence length {s} must be divisible by the number \\\n of devices {d} for sequence parallelism.\"\n )\n # To reduce memory footprint, create unsharded data on CPU and copy only\n # the needed slice to GPU.\n inp = torch.testing.make_tensor(b, s, e, dtype=torch.bfloat16, device=\"cpu\")\n mha_linear0_weight = torch.testing.make_tensor(\n e * 3, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n mha_linear0_bias = torch.testing.make_tensor(\n e * 3, dtype=torch.bfloat16, device=\"cpu\"\n )\n mha_linear1_weight = torch.testing.make_tensor(\n e, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n mlp_linear0_weight = torch.testing.make_tensor(\n e * 4, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n mlp_linear0_bias = torch.testing.make_tensor(\n e * 4, dtype=torch.bfloat16, device=\"cpu\"\n )\n mlp_linear1_weight = torch.testing.make_tensor(\n e, e * 4, dtype=torch.bfloat16, device=\"cpu\"\n )\n\n # See TransformerForwardFusion.definition for the meanings of these\n # arguments. They are passed in in the same order as the `define_scalar`s\n # and `define_tensor`s.\n ins = [\n inp.cuda()\n if parallelism == Parallelism.TENSOR_PARALLEL\n else multidevice_test.shard_tensor_1d(inp, 1, mesh),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n multidevice_test.shard_tensor_1d(mha_linear0_weight, 0, mesh),\n multidevice_test.shard_tensor_1d(mha_linear0_bias, 0, mesh),\n multidevice_test.shard_tensor_1d(mha_linear1_weight, -1, mesh),\n torch.testing.make_tensor(e, dtype=torch.bfloat16, device=\"cuda\"),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n multidevice_test.shard_tensor_1d(mlp_linear0_weight, 0, mesh),\n multidevice_test.shard_tensor_1d(mlp_linear0_bias, 0, mesh),\n multidevice_test.shard_tensor_1d(mlp_linear1_weight, -1, mesh),\n torch.testing.make_tensor(e, dtype=torch.bfloat16, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n transformer_forward_definition(fd, b, s, h, e)\n transformer_forward_multidevice_schedule(fd, d, parallelism)\n\n warmup_fn, benchmark_fn = get_benchmark_fns(lambda: fd.execute(ins))\n\n # Warm up and validate.\n (\n layernorm0_mean,\n layernorm0_rstd,\n mha_linear0_out,\n sdpa_out,\n sdpa_logsum_exp,\n sdpa_seed,\n sdpa_offset,\n mha_linear1_out,\n mha_dropout_mask,\n layernorm1_mean,\n layernorm1_rstd,\n mlp_linear0_out,\n mlp_dropout_mask,\n out,\n ) = warmup_fn()\n\n s_local = s // d if parallelism == Parallelism.SEQUENCE_PARALLEL else s\n\n _assert_shape_dtype(layernorm0_mean, [b, s_local], torch.float32)\n _assert_shape_dtype(layernorm0_rstd, [b, s_local, 1], torch.float32)\n _assert_shape_dtype(mha_linear0_out, [b, s, e * 3 // d], torch.bfloat16)\n _assert_shape_dtype(sdpa_out, [b, h // d, s, e // h], torch.bfloat16)\n _assert_shape_dtype(sdpa_logsum_exp, [b, h // d, s], torch.float32)\n ref_philox_seed, ref_philox_offset = create_sdpa_rng_tensors()\n _assert_shape_dtype(sdpa_seed, ref_philox_seed.shape, ref_philox_seed.dtype)\n _assert_shape_dtype(sdpa_offset, ref_philox_offset.shape, ref_philox_offset.dtype)\n _assert_shape_dtype(mha_linear1_out, [b, s_local, e], torch.bfloat16)\n _assert_shape_dtype(mha_dropout_mask, [b, s_local, e], torch.bool)\n _assert_shape_dtype(layernorm1_mean, [b, s_local], torch.float32)\n _assert_shape_dtype(layernorm1_rstd, [b, s_local, 1], torch.float32)\n _assert_shape_dtype(mlp_linear0_out, [b, s, e * 4 // d], torch.bfloat16)\n _assert_shape_dtype(mlp_dropout_mask, [b, s_local, e], torch.bool)\n _assert_shape_dtype(out, [b, s_local, e], torch.bfloat16)\n\n # Benchmark and profile. The profile can be colle\n# ... truncated ...","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer.test_grouped_mlp","uri":"program://Fuser/function/tests.python.multidevice.test_transformer.test_grouped_mlp#L20-L96","kind":"function","name":"test_grouped_mlp","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":20,"end_line":96,"context_start_line":1,"context_end_line":116,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\n\nimport torch\nimport torch.nn.functional as F\n\nimport nvfuser_direct as nvfuser\nfrom . import Parallelism\nfrom .benchmark_utils import get_benchmark_fns\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom python.direct_utils import (\n create_sdpa_rng_tensors,\n is_pre_ampere,\n)\n\n\n@pytest.mark.mpi\ndef test_grouped_mlp(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n g = 4\n k = 16\n n = 16 * d\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, k], dtype=DataType.BFloat16, contiguity=True)\n gate_w_tv = fd.define_tensor(\n [g, k, n], dtype=DataType.BFloat16, contiguity=True\n )\n up_w_tv = fd.define_tensor([g, k, n], dtype=DataType.BFloat16, contiguity=True)\n down_w_tv = fd.define_tensor(\n [g, n, k], dtype=DataType.BFloat16, contiguity=True\n )\n offsets_tv = fd.define_tensor([g], dtype=DataType.Int32, contiguity=True)\n\n gate_out = fd.ops.grouped_mm(inp_tv, gate_w_tv, offsets_tv)\n gate_out = fd.ops.cast(gate_out, DataType.Float)\n\n up_out = fd.ops.grouped_mm(inp_tv, up_w_tv, offsets_tv)\n\n mul_out = fd.ops.mul(fd.ops.silu(gate_out), up_out)\n mul_out = fd.ops.cast(mul_out, DataType.BFloat16)\n\n out = fd.ops.grouped_mm(mul_out, down_w_tv, offsets_tv)\n\n fd.add_output(out)\n\n for t in [inp_tv, gate_w_tv, up_w_tv, down_w_tv, offsets_tv]:\n t.set_device_mesh(mesh)\n\n for w in [gate_w_tv, up_w_tv]:\n w.split(-1, d, False)\n w.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n down_w_tv.split(-2, d, False)\n down_w_tv.axis(-3).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 32\n assert m % g == 0\n group_sizes = [m // g] * g\n inp_ref = torch.randn(m, k, dtype=torch.bfloat16)\n gate_w_ref = torch.randn(g, k, n, dtype=torch.bfloat16)\n up_w_ref = torch.randn(g, k, n, dtype=torch.bfloat16)\n down_w_ref = torch.randn(g, n, k, dtype=torch.bfloat16)\n offsets_ref = torch.cumsum(torch.tensor(group_sizes), 0, dtype=torch.int32)\n group_outs = [\n (F.silu(group_in @ group_gate_w) * (group_in @ group_up_w)) @ group_down_w\n for group_in, group_gate_w, group_up_w, group_down_w in zip(\n inp_ref.split(group_sizes),\n gate_w_ref.unbind(),\n up_w_ref.unbind(),\n down_w_ref.unbind(),\n )\n ]\n out_ref = torch.cat(group_outs, dim=0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n gate_w = multidevice_test.shard_tensor(gate_w_ref, gate_w_tv)\n up_w = multidevice_test.shard_tensor(up_w_ref, up_w_tv)\n down_w = multidevice_test.shard_tensor(down_w_ref, down_w_tv)\n offsets = multidevice_test.shard_tensor(offsets_ref, offsets_tv)\n (out,) = fd.execute([inp, gate_w, up_w, down_w, offsets])\n\n # Unfortunately, I couldn't come up with meaningful thresholds to pass the\n # comparison even with one GPU. I manually examined the results. They are\n # not completely off, which is good.\n #\n # I tried several easy things:\n # 1. run the reference implementation on GPU,\n # 2. upcast tensors to `float` here and there in the reference implementation.\n #\n # None of them significantly reduce the error. It could be a problem in the\n # grouped gemm kernel.\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1.0, atol=float(\"inf\"))\n\n\n# The following benchmarks the fusion generated from NanoGPTBlockBenchmark in Thunder.\n# To generate the fusion, use the following snippet which turns on the necessary options\n# to get a single nvfuser definition.\n# ```\n# from thunder.benchmarks import NanoGPTBlockBenchmark, NanoGPTConfig\n# from thunder.executors.nvfuserex import nvfuserex\n\n# config = NanoGPTConfig(seq_len=2048, n_head=96, n_embd=12288)\n# bench = NanoGPTBlockBenchmark(\n# batchdims=(1,), config=config, device=\"cuda:0\", dtype=thunder.bfloat16, requires_grad=True\n# )\n# args, kwargs = bench.make_batch()\n#\n# jfn = thunder.jit(\n# bench.fn(),\n# executors=[nvfuserex],\n# nv_enable_sdpa=True,\n# nv_enable_matmul=True,","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer.transformer_forward_definition","uri":"program://Fuser/function/tests.python.multidevice.test_transformer.transformer_forward_definition#L129-L352","kind":"function","name":"transformer_forward_definition","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":129,"end_line":352,"context_start_line":109,"context_end_line":372,"code":"# )\n# args, kwargs = bench.make_batch()\n#\n# jfn = thunder.jit(\n# bench.fn(),\n# executors=[nvfuserex],\n# nv_enable_sdpa=True,\n# nv_enable_matmul=True,\n# nv_enable_linear=True,\n# disable_replace_uniform=True,\n# )\n# out = jfn(*args, **kwargs)\n# grads = torch.randn_like(out, device=\"cuda\", dtype=torch.bfloat16)\n# out.backward(grads)\n# print(thunder.last_traces(jfn)[-1].python_ctx()['nvFusion0'].last_used)\n# print(thunder.last_backward_traces(jfn)[-1].python_ctx()['nvFusion0'].last_used)\n# ```\n# Fusions generated from Thunder commit: b0dc72ef1a9825a70923ae1a270d919f5948c4ed\n\n\ndef transformer_forward_definition(\n fd: FusionDefinition, batch: int, sequence: int, head: int, hidden: int\n) -> None:\n # Same notations as in test_multidevice_transformer.cpp.\n b, s, h, e = batch, sequence, head, hidden\n inp = fd.define_tensor(\n shape=[b, s, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n layernorm0_weight = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n layernorm0_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n mha_linear0_weight = fd.define_tensor(\n shape=[e * 3, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n mha_linear0_bias = fd.define_tensor(\n shape=[e * 3],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n mha_linear1_weight = fd.define_tensor(\n shape=[e, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n mha_linear1_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n layernorm1_weight = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n layernorm1_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n mlp_linear0_weight = fd.define_tensor(\n shape=[e * 4, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n mlp_linear0_bias = fd.define_tensor(\n shape=[e * 4],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n mlp_linear1_weight = fd.define_tensor(\n shape=[e, e * 4],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n mlp_linear1_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n\n T13 = fd.ops.cast(inp, dtype=DataType.Float)\n T14, layernorm0_mean = fd.ops.var_mean(T13, dims=[2], correction=0, keepdim=False)\n T20 = fd.ops.broadcast_in_dim(T14, shape=[b, s, 1], broadcast_dims=[0, 1])\n T25 = fd.ops.broadcast_in_dim(\n layernorm0_mean, shape=[b, s, 1], broadcast_dims=[0, 1]\n )\n S26 = fd.define_scalar(1.00000e-05, dtype=DataType.Double)\n T27 = fd.ops.add(T20, S26)\n layernorm0_rstd = fd.ops.rsqrt(T27)\n T33 = fd.ops.broadcast_in_dim(T25, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T34 = fd.ops.sub(T13, T33)\n T39 = fd.ops.broadcast_in_dim(\n layernorm0_rstd, shape=[b, s, e], broadcast_dims=[0, 1, 2]\n )\n T40 = fd.ops.mul(T34, T39)\n T45 = fd.ops.broadcast_in_dim(\n layernorm0_weight, shape=[b, s, e], broadcast_dims=[2]\n )\n T46 = fd.ops.cast(T45, dtype=DataType.Float)\n T47 = fd.ops.mul(T40, T46)\n T52 = fd.ops.broadcast_in_dim(layernorm0_bias, shape=[b, s, e], broadcast_dims=[2])\n T53 = fd.ops.cast(T52, dtype=DataType.Float)\n T54 = fd.ops.add(T47, T53)\n T55 = fd.ops.cast(T54, dtype=DataType.BFloat16)\n mha_linear0_out = fd.ops.linear(T55, mha_linear0_weight, mha_linear0_bias)\n\n # Reshape before slice to avoid slicing a tensor along sharded dimension.\n # This is different from the single-GPU definition obtained from Thunder.\n T57 = fd.ops.reshape(mha_linear0_out, new_shape=[b, s, h, 3 * e // h])\n T69 = fd.ops.slice(T57, start_indices=[0, 0, 0, 0], end_indices=[b, s, h, e // h])\n T82 = fd.ops.slice(\n T57, start_indices=[0, 0, 0, e // h], end_indices=[b, s, h, 2 * e // h]\n )\n T95 = fd.ops.slice(\n T57, start_indices=[0, 0, 0, 2 * e // h], end_indices=[b, s, h, 3 * e // h]\n )\n\n T102 = fd.ops.permute(T82, dims=[0, 2, 1, 3])\n T109 = fd.ops.permute(T69, dims=[0, 2, 1, 3])\n T116 = fd.ops.permute(T95, dims=[0, 2, 1, 3])\n\n S117 = fd.define_scalar(0.100000, dtype=DataType.Double)\n S118 = fd.define_scalar(True, dtype=DataType.Bool)\n sdpa_out, sdpa_logsum_exp, sdpa_seed, sdpa_offset = fd.ops.sdpfa_fwd(\n T109, T102, T116, dropout_p=S117, is_causal=S118, scale=None\n )\n T123 = fd.ops.permute(sdpa_out, dims=[0, 2, 1, 3])\n T124 = fd.ops.stride_order(T123, stride_order=[3, 2, 1, 0])\n T129 = fd.ops.reshape(T124, new_shape=[b, s, e])\n mha_linear1_out = fd.ops.linear(T129, mha_linear1_weight, mha_linear1_bias)\n S131 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S132 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T137 = fd.ops.uniform(S131, S132, shape=[b, s, e], dtype=DataType.BFloat16)\n S138 = fd.define_scalar(0.900000, dtype=DataType.Double)\n mha_dropout_mask = fd.ops.lt(T137, S138)\n T140 = fd.ops.cast(mha_linear1_out, dtype=DataType.Float)\n T141 = fd.ops.cast(mha_dropout_mask, dtype=DataType.Float)\n T142 = fd.ops.mul(T140, T141)\n S143 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T144 = fd.ops.mul(T142, S143)\n T145 = fd.ops.add(T13, T144)\n T146, layernorm1_mean = fd.ops.var_mean(T145, dims=[2], correction=0, keepdim=False)\n T152 = fd.ops.broadcast_in_dim(T146, shape=[b, s, 1], broadcast_dims=[0, 1])\n T157 = fd.ops.broadcast_in_dim(\n layernorm1_mean, shape=[b, s, 1], broadcast_dims=[0, 1]\n )\n S158 = fd.define_scalar(1.00000e-05, dtype=DataType.Double)\n T159 = fd.ops.add(T152, S158)\n layernorm1_rstd = fd.ops.rsqrt(T159)\n T165 = fd.ops.broadcast_in_dim(T157, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T166 = fd.ops.sub(T145, T165)\n T171 = fd.ops.broadcast_in_dim(\n layernorm1_rstd, shape=[b, s, e], broadcast_dims=[0, 1, 2]\n )\n T172 = fd.ops.mul(T166, T171)\n T177 = fd.ops.broadcast_in_dim(\n layernorm1_weight, shape=[b, s, e], broadcast_dims=[2]\n )\n T178 = fd.ops.cast(T177, dtype=DataType.Float)\n T179 = fd.ops.mul(T172, T178)\n T184 = fd.ops.broadcast_in_dim(layernorm1_bias, shape=[b, s, e], broadcast_dims=[2])\n T185 = fd.ops.cast(T184, dtype=DataType.Float)\n T186 = fd.ops.add(T179, T185)\n T187 = fd.ops.cast(T186, dtype=DataType.BFloat16)\n mlp_linear0_out = fd.ops.linear(T187, mlp_linear0_weight, mlp_linear0_bias)\n T189 = fd.ops.cast(mlp_linear0_out, dtype=DataType.Float)\n T190 = fd.ops.mul(T189, T189)\n T191 = fd.ops.mul(T190, T189)\n S192 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T193 = fd.ops.mul(S192, T189)\n S194 = fd.define_scalar(0.0447150, dtype=DataType.Double)\n T195 = fd.ops.mul(S194, T191)\n T196 = fd.ops.add(T189, T195)\n S197 = fd.define_scalar(0.797885, dtype=DataType.Double)\n T198 = fd.ops.mul(S197, T196)\n T199 = fd.ops.tanh(T198)\n S200 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T201 = fd.ops.add(S200, T199)\n T202 = fd.ops.mul(T193, T201)\n T203 = fd.ops.cast(T202, dtype=DataType.BFloat16)\n mlp_linear1_out = fd.ops.linear(T203, mlp_linear1_weight, mlp_linear1_bias)\n S205 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S206 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T211 = fd.ops.uniform(S205, S206, shape=[b, s, e], dtype=DataType.BFloat16)\n S212 = fd.define_scalar(0.900000, dtype=DataType.Double)\n mlp_dropout_mask = fd.ops.lt(T211, S212)\n T214 = fd.ops.cast(mlp_linear1_out, dtype=DataType.Float)\n T215 = fd.ops.cast(mlp_dropout_mask, dtype=DataType.Float)\n T216 = fd.ops.mul(T214, T215)\n S217 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T218 = fd.ops.mul(T216, S217)\n T219 = fd.ops.add(T145, T218)\n out = fd.ops.cast(T219, dtype=DataType.BFloat16)\n fd.add_output(layernorm0_mean)\n fd.add_output(layernorm0_rstd)\n fd.add_output(mha_linear0_out)\n fd.add_output(sdpa_out)\n fd.add_output(sdpa_logsum_exp)\n fd.add_output(sdpa_seed)\n fd.add_output(sdpa_offset)\n fd.add_output(mha_linear1_out)\n fd.add_output(mha_dropout_mask)\n fd.add_output(layernorm1_mean)\n fd.add_output(layernorm1_rstd)\n fd.add_output(mlp_linear0_out)\n fd.add_output(mlp_dropout_mask)\n fd.add_output(out)\n\n\ndef transformer_forward_multidevice_schedule(\n fd: FusionDefinition, num_devices: int, parallelism: Parallelism\n):\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n inputs = fd.fusion.inputs()\n (\n inp,\n layernorm0_weight,\n layernorm0_bias,\n mha_linear0_weight,\n mha_linear0_bias,\n mha_linear1_weight,\n mha_linear1_bias,\n layernorm1_weight,\n layernorm1_bias,\n mlp_linear0_weight,\n mlp_linear0_bias,\n mlp_linear1_weight,","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer.transformer_forward_multidevice_schedule","uri":"program://Fuser/function/tests.python.multidevice.test_transformer.transformer_forward_multidevice_schedule#L355-L397","kind":"function","name":"transformer_forward_multidevice_schedule","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":355,"end_line":397,"context_start_line":335,"context_end_line":417,"code":" S217 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T218 = fd.ops.mul(T216, S217)\n T219 = fd.ops.add(T145, T218)\n out = fd.ops.cast(T219, dtype=DataType.BFloat16)\n fd.add_output(layernorm0_mean)\n fd.add_output(layernorm0_rstd)\n fd.add_output(mha_linear0_out)\n fd.add_output(sdpa_out)\n fd.add_output(sdpa_logsum_exp)\n fd.add_output(sdpa_seed)\n fd.add_output(sdpa_offset)\n fd.add_output(mha_linear1_out)\n fd.add_output(mha_dropout_mask)\n fd.add_output(layernorm1_mean)\n fd.add_output(layernorm1_rstd)\n fd.add_output(mlp_linear0_out)\n fd.add_output(mlp_dropout_mask)\n fd.add_output(out)\n\n\ndef transformer_forward_multidevice_schedule(\n fd: FusionDefinition, num_devices: int, parallelism: Parallelism\n):\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n inputs = fd.fusion.inputs()\n (\n inp,\n layernorm0_weight,\n layernorm0_bias,\n mha_linear0_weight,\n mha_linear0_bias,\n mha_linear1_weight,\n mha_linear1_bias,\n layernorm1_weight,\n layernorm1_bias,\n mlp_linear0_weight,\n mlp_linear0_bias,\n mlp_linear1_weight,\n mlp_linear1_bias,\n ) = inputs\n\n for tv in inputs:\n tv.set_device_mesh(mesh)\n\n if parallelism == Parallelism.SEQUENCE_PARALLEL:\n inp.outer_split(1, num_devices)\n inp.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n for tv in [\n mha_linear0_weight,\n mha_linear0_bias,\n mlp_linear0_weight,\n mlp_linear0_bias,\n ]:\n tv.outer_split(0, num_devices)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n for tv in [\n mha_linear1_weight,\n mlp_linear1_weight,\n ]:\n tv.outer_split(-1, num_devices)\n tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n\n# TODO(#2962): validate the numbers as well. Currently, the numbers are off\n# by a lot, making comparison infeasible.\ndef _assert_shape_dtype(\n t: torch.Tensor, expected_sizes: list[int], expected_dtype: torch.dtype\n) -> None:\n assert t.shape == torch.Size(expected_sizes)\n assert t.dtype == expected_dtype\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\n \"parallelism\",\n [Parallelism.TENSOR_PARALLEL, Parallelism.SEQUENCE_PARALLEL],\n ids=lambda p: p.name,\n)","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer._assert_shape_dtype","uri":"program://Fuser/function/tests.python.multidevice.test_transformer._assert_shape_dtype#L402-L406","kind":"function","name":"_assert_shape_dtype","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":402,"end_line":406,"context_start_line":382,"context_end_line":426,"code":"\n for tv in [\n mha_linear0_weight,\n mha_linear0_bias,\n mlp_linear0_weight,\n mlp_linear0_bias,\n ]:\n tv.outer_split(0, num_devices)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n for tv in [\n mha_linear1_weight,\n mlp_linear1_weight,\n ]:\n tv.outer_split(-1, num_devices)\n tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n\n# TODO(#2962): validate the numbers as well. Currently, the numbers are off\n# by a lot, making comparison infeasible.\ndef _assert_shape_dtype(\n t: torch.Tensor, expected_sizes: list[int], expected_dtype: torch.dtype\n) -> None:\n assert t.shape == torch.Size(expected_sizes)\n assert t.dtype == expected_dtype\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\n \"parallelism\",\n [Parallelism.TENSOR_PARALLEL, Parallelism.SEQUENCE_PARALLEL],\n ids=lambda p: p.name,\n)\n@pytest.mark.mpi\ndef test_transformer_forward(multidevice_test, benchmark, parallelism: Parallelism):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n b, s, h, e = 1, 2048, 96, 12288\n\n assert (\n e % h == 0","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer.test_transformer_forward","uri":"program://Fuser/function/tests.python.multidevice.test_transformer.test_transformer_forward#L419-L533","kind":"function","name":"test_transformer_forward","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":419,"end_line":533,"context_start_line":399,"context_end_line":553,"code":"\n# TODO(#2962): validate the numbers as well. Currently, the numbers are off\n# by a lot, making comparison infeasible.\ndef _assert_shape_dtype(\n t: torch.Tensor, expected_sizes: list[int], expected_dtype: torch.dtype\n) -> None:\n assert t.shape == torch.Size(expected_sizes)\n assert t.dtype == expected_dtype\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\n \"parallelism\",\n [Parallelism.TENSOR_PARALLEL, Parallelism.SEQUENCE_PARALLEL],\n ids=lambda p: p.name,\n)\n@pytest.mark.mpi\ndef test_transformer_forward(multidevice_test, benchmark, parallelism: Parallelism):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n b, s, h, e = 1, 2048, 96, 12288\n\n assert (\n e % h == 0\n ), f\"The hidden size ({e}) has to be divisible by the number of heads ({h}).\"\n\n if h % d != 0:\n pytest.skip(\n f\"We only support even DID split, so the number of heads ({h}) has \\\n to be divisible by the number of GPUs ({d}).\"\n )\n\n assert e * 4 % d == 0, (\n \"This is required to evenly DID split MLP. This condition is implied \"\n \"by the previous two checks; a fail would indicate a programming \"\n \"error. So I use `assert` instead of `pytest.skip`.\"\n )\n\n if parallelism == Parallelism.SEQUENCE_PARALLEL and s % d != 0:\n pytest.skip(\n f\"Sequence length {s} must be divisible by the number \\\n of devices {d} for sequence parallelism.\"\n )\n # To reduce memory footprint, create unsharded data on CPU and copy only\n # the needed slice to GPU.\n inp = torch.testing.make_tensor(b, s, e, dtype=torch.bfloat16, device=\"cpu\")\n mha_linear0_weight = torch.testing.make_tensor(\n e * 3, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n mha_linear0_bias = torch.testing.make_tensor(\n e * 3, dtype=torch.bfloat16, device=\"cpu\"\n )\n mha_linear1_weight = torch.testing.make_tensor(\n e, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n mlp_linear0_weight = torch.testing.make_tensor(\n e * 4, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n mlp_linear0_bias = torch.testing.make_tensor(\n e * 4, dtype=torch.bfloat16, device=\"cpu\"\n )\n mlp_linear1_weight = torch.testing.make_tensor(\n e, e * 4, dtype=torch.bfloat16, device=\"cpu\"\n )\n\n # See TransformerForwardFusion.definition for the meanings of these\n # arguments. They are passed in in the same order as the `define_scalar`s\n # and `define_tensor`s.\n ins = [\n inp.cuda()\n if parallelism == Parallelism.TENSOR_PARALLEL\n else multidevice_test.shard_tensor_1d(inp, 1, mesh),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n multidevice_test.shard_tensor_1d(mha_linear0_weight, 0, mesh),\n multidevice_test.shard_tensor_1d(mha_linear0_bias, 0, mesh),\n multidevice_test.shard_tensor_1d(mha_linear1_weight, -1, mesh),\n torch.testing.make_tensor(e, dtype=torch.bfloat16, device=\"cuda\"),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n multidevice_test.shard_tensor_1d(mlp_linear0_weight, 0, mesh),\n multidevice_test.shard_tensor_1d(mlp_linear0_bias, 0, mesh),\n multidevice_test.shard_tensor_1d(mlp_linear1_weight, -1, mesh),\n torch.testing.make_tensor(e, dtype=torch.bfloat16, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n transformer_forward_definition(fd, b, s, h, e)\n transformer_forward_multidevice_schedule(fd, d, parallelism)\n\n warmup_fn, benchmark_fn = get_benchmark_fns(lambda: fd.execute(ins))\n\n # Warm up and validate.\n (\n layernorm0_mean,\n layernorm0_rstd,\n mha_linear0_out,\n sdpa_out,\n sdpa_logsum_exp,\n sdpa_seed,\n sdpa_offset,\n mha_linear1_out,\n mha_dropout_mask,\n layernorm1_mean,\n layernorm1_rstd,\n mlp_linear0_out,\n mlp_dropout_mask,\n out,\n ) = warmup_fn()\n\n s_local = s // d if parallelism == Parallelism.SEQUENCE_PARALLEL else s\n\n _assert_shape_dtype(layernorm0_mean, [b, s_local], torch.float32)\n _assert_shape_dtype(layernorm0_rstd, [b, s_local, 1], torch.float32)\n _assert_shape_dtype(mha_linear0_out, [b, s, e * 3 // d], torch.bfloat16)\n _assert_shape_dtype(sdpa_out, [b, h // d, s, e // h], torch.bfloat16)\n _assert_shape_dtype(sdpa_logsum_exp, [b, h // d, s], torch.float32)\n ref_philox_seed, ref_philox_offset = create_sdpa_rng_tensors()\n _assert_shape_dtype(sdpa_seed, ref_philox_seed.shape, ref_philox_seed.dtype)\n _assert_shape_dtype(sdpa_offset, ref_philox_offset.shape, ref_philox_offset.dtype)\n _assert_shape_dtype(mha_linear1_out, [b, s_local, e], torch.bfloat16)\n _assert_shape_dtype(mha_dropout_mask, [b, s_local, e], torch.bool)\n _assert_shape_dtype(layernorm1_mean, [b, s_local], torch.float32)\n _assert_shape_dtype(layernorm1_rstd, [b, s_local, 1], torch.float32)\n _assert_shape_dtype(mlp_linear0_out, [b, s, e * 4 // d], torch.bfloat16)\n _assert_shape_dtype(mlp_dropout_mask, [b, s_local, e], torch.bool)\n _assert_shape_dtype(out, [b, s_local, e], torch.bfloat16)\n\n # Benchmark and profile. The profile can be collected and displayed using\n # `nsys`. See instructions in test_transformer_engine.py.\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\ndef transformer_backward_definition(\n fd: FusionDefinition,\n batch: int,\n sequence: int,\n head: int,\n hidden: int,\n parallelism: Parallelism,\n num_devices: int,\n) -> None:\n b, s, h, e = batch, sequence, head, hidden\n\n fd.mlp_linear0_out = fd.define_tensor(\n shape=[b, s, 4 * e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer.transformer_backward_definition","uri":"program://Fuser/function/tests.python.multidevice.test_transformer.transformer_backward_definition#L536-L1044","kind":"function","name":"transformer_backward_definition","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":536,"end_line":1044,"context_start_line":516,"context_end_line":1064,"code":" _assert_shape_dtype(layernorm0_rstd, [b, s_local, 1], torch.float32)\n _assert_shape_dtype(mha_linear0_out, [b, s, e * 3 // d], torch.bfloat16)\n _assert_shape_dtype(sdpa_out, [b, h // d, s, e // h], torch.bfloat16)\n _assert_shape_dtype(sdpa_logsum_exp, [b, h // d, s], torch.float32)\n ref_philox_seed, ref_philox_offset = create_sdpa_rng_tensors()\n _assert_shape_dtype(sdpa_seed, ref_philox_seed.shape, ref_philox_seed.dtype)\n _assert_shape_dtype(sdpa_offset, ref_philox_offset.shape, ref_philox_offset.dtype)\n _assert_shape_dtype(mha_linear1_out, [b, s_local, e], torch.bfloat16)\n _assert_shape_dtype(mha_dropout_mask, [b, s_local, e], torch.bool)\n _assert_shape_dtype(layernorm1_mean, [b, s_local], torch.float32)\n _assert_shape_dtype(layernorm1_rstd, [b, s_local, 1], torch.float32)\n _assert_shape_dtype(mlp_linear0_out, [b, s, e * 4 // d], torch.bfloat16)\n _assert_shape_dtype(mlp_dropout_mask, [b, s_local, e], torch.bool)\n _assert_shape_dtype(out, [b, s_local, e], torch.bfloat16)\n\n # Benchmark and profile. The profile can be collected and displayed using\n # `nsys`. See instructions in test_transformer_engine.py.\n benchmark.pedantic(benchmark_fn, rounds=5)\n\n\ndef transformer_backward_definition(\n fd: FusionDefinition,\n batch: int,\n sequence: int,\n head: int,\n hidden: int,\n parallelism: Parallelism,\n num_devices: int,\n) -> None:\n b, s, h, e = batch, sequence, head, hidden\n\n fd.mlp_linear0_out = fd.define_tensor(\n shape=[b, s, 4 * e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.out_grad = fd.define_tensor(\n shape=[b, s, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.mlp_dropout_mask = fd.define_tensor(\n shape=[b, s, e],\n contiguity=True,\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.mlp_linear1_weight = fd.define_tensor(\n shape=[e, e * 4],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n fd.mha_dropout_mask = fd.define_tensor(\n shape=[b, s, e],\n contiguity=True,\n dtype=DataType.Bool,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.mha_linear1_out = fd.define_tensor(\n shape=[b, s, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.mlp_linear0_weight = fd.define_tensor(\n shape=[4 * e, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n fd.layernorm1_weight = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n fd.layernorm1_mean = fd.define_tensor(\n shape=[b, s],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n fd.inp = fd.define_tensor(\n shape=[b, s, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.layernorm1_rstd = fd.define_tensor(\n shape=[b, s, 1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.mha_linear1_weight = fd.define_tensor(\n shape=[e, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n fd.mha_linear0_out = fd.define_tensor(\n shape=[b, s, 3 * e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.sdpa_out = fd.define_tensor(\n shape=[b, h, s, e // h],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n fd.sdpa_logsum_exp = fd.define_tensor(\n shape=[b, h, s],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.sdpa_seed = fd.define_tensor(\n shape=[2],\n contiguity=True,\n dtype=DataType.UInt64,\n is_cpu=False,\n stride_order=[0],\n )\n fd.sdpa_offset = fd.define_tensor(\n shape=[], contiguity=[], dtype=DataType.UInt64, is_cpu=False\n )\n fd.mha_linear0_weight = fd.define_tensor(\n shape=[3 * e, e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n fd.layernorm0_weight = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n fd.layernorm0_mean = fd.define_tensor(\n shape=[b, s],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[1, 0],\n )\n fd.layernorm0_rstd = fd.define_tensor(\n shape=[b, s, 1],\n contiguity=True,\n dtype=DataType.Float,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n fd.layernorm0_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n fd.layernorm1_bias = fd.define_tensor(\n shape=[e],\n contiguity=True,\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[0],\n )\n T23 = fd.ops.cast(fd.mlp_linear0_out, dtype=DataType.Float)\n T24 = fd.ops.cast(fd.out_grad, dtype=DataType.Float)\n T25 = fd.ops.mul(T23, T23)\n S26 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T27 = fd.ops.mul(S26, T24)\n T28 = fd.ops.cast(fd.mlp_dropout_mask, dtype=DataType.Float)\n T29 = fd.ops.mul(T25, T23)\n mlp_linear1_out_grad = fd.ops.mul(T28, T27)\n S31 = fd.define_scalar(0.0447150, dtype=DataType.Double)\n T32 = fd.ops.mul(S31, T29)\n T33 = fd.ops.cast(mlp_linear1_out_grad, dtype=DataType.BFloat16)\n T34 = fd.ops.add(T23, T32)\n T38 = fd.ops.reshape(T33, new_shape=[b * s, e])\n S39 = fd.define_scalar(0.797885, dtype=DataType.Double)\n T40 = fd.ops.mul(S39, T34)\n T41 = fd.ops.matmul(T38, fd.mlp_linear1_weight)\n T42 = fd.ops.tanh(T40)\n T47 = fd.ops.reshape(T41, new_shape=[b, s, 4 * e])\n T48 = fd.ops.mul(T42, T42)\n T49 = fd.ops.cast(T47, dtype=DataType.Float)\n S50 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T51 = fd.ops.mul(S50, T23)\n S52 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T53 = fd.ops.sub(S52, T48)\n T54 = fd.ops.mul(T51, T49)\n T55 = fd.ops.mul(T54, T53)\n S56 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T57 = fd.ops.add(S56, T42)\n S58 = fd.define_scalar(0.797885, dtype=DataType.Double)\n T59 = fd.ops.mul(S58, T55)\n T60 = fd.ops.mul(T57, T49)\n S61 = fd.define_scalar(0.0447150, dtype=DataType.Double)\n T62 = fd.ops.mul(S61, T59)\n S63 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T64 = fd.ops.mul(S63, T60)\n T65 = fd.ops.mul(T23, T62)\n T66 = fd.ops.mul(T25, T62)\n T67 = fd.ops.add(T59, T64)\n T68 = fd.ops.mul(T23, T65)\n T69 = fd.ops.add(T67, T66)\n T70 = fd.ops.add(T69, T68)\n T71 = fd.ops.add(T70, T68)\n T72 = fd.ops.cast(T71, dtype=DataType.BFloat16)\n T76 = fd.ops.reshape(T72, new_shape=[b * s, e * 4])\n T77 = fd.ops.cast(fd.mha_dropout_mask, dtype=DataType.Float)\n T78 = fd.ops.cast(fd.mha_linear1_out, dtype=DataType.Float)\n T79 = fd.ops.matmul(T76, fd.mlp_linear0_weight)\n T80 = fd.ops.mul(T78, T77)\n layernorm1_out_grad = fd.ops.reshape(T79, new_shape=[b, s, e])\n T90 = fd.ops.broadcast_in_dim(\n fd.layernorm1_weight, shape=[b, s, e], broadcast_dims=[2]\n )\n T95 = fd.ops.broadcast_in_dim(\n fd.layernorm1_mean, shape=[b, s, 1], broadcast_dims=[0, 1]\n )\n S96 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T97 = fd.ops.mul(T80, S96)\n T98 = fd.ops.cast(fd.inp, dtype=DataType.Float)\n T99 = fd.ops.cast(layernorm1_out_grad, dtype=DataType.Float)\n T100 = fd.ops.cast(T90, dtype=DataType.Float)\n T105 = fd.ops.broadcast_in_dim(T95, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T106 = fd.ops.add(T98, T97)\n T107 = fd.ops.mul(T100, T99)\n T108 = fd.ops.sub(T106, T105)\n T109 = fd.ops.mul(T108, T107)\n T110 = fd.ops.sum(T109, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T115 = fd.ops.broadcast_in_dim(T110, shape=[b, s, 1], broadcast_dims=[1])\n T120 = fd.ops.broadcast_in_dim(\n fd.layernorm1_rstd, shape=[b, s, e], broadcast_dims=[0, 1, 2]\n )\n S121 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T122 = fd.ops.pow(fd.layernorm1_rstd, S121)\n S123 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T124 = fd.ops.mul(S123, T115)\n T125 = fd.ops.mul(T120, T107)\n T126 = fd.ops.mul(T124, T122)\n T127 = fd.ops.neg(T125)\n T128 = fd.ops.sum(T126, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T129 = fd.ops.sum(T127, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T133 = fd.ops.broadcast_in_dim(T128, shape=[b, s], broadcast_dims=[1])\n T138 = fd.ops.broadcast_in_dim(T129, shape=[b, s, 1], broadcast_dims=[1])\n T143 = fd.ops.broadcast_in_dim(\n fd.layernorm1_mean, shape=[b, s, 1], broadcast_dims=[0, 1]\n )\n T148 = fd.ops.broadcast_in_dim(T133, shape=[b, s, 1], broadcast_dims=[0, 1])\n T149 = fd.ops.sum(T138, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T154 = fd.ops.broadcast_in_dim(T143, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T159 = fd.ops.broadcast_in_dim(T148, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T163 = fd.ops.broadcast_in_dim(T149, shape=[b, s], broadcast_dims=[1])\n T164 = fd.ops.sub(T106, T154)\n S165 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T166 = fd.ops.mul(S165, T159)\n T171 = fd.ops.broadcast_in_dim(T163, shape=[b, s, 1], broadcast_dims=[0, 1])\n T172 = fd.ops.mul(T166, T164)\n T177 = fd.ops.broadcast_in_dim(T171, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n S178 = fd.define_scalar(float(e), dtype=DataType.Double)\n S179 = fd.ops.reciprocal(S178)\n T180 = fd.ops.mul(T172, S179)\n S181 = fd.define_scalar(1 / e, dtype=DataType.Double)\n T182 = fd.ops.mul(S181, T177)\n T183 = fd.ops.add(T182, T180)\n T184 = fd.ops.add(T24, T125)\n T185 = fd.ops.add(T184, T183)\n S186 = fd.define_scalar(1.11111, dtype=DataType.Double)\n T187 = fd.ops.mul(S186, T185)\n mha_linear1_out_grad = fd.ops.mul(T77, T187)\n T189 = fd.ops.cast(mha_linear1_out_grad, dtype=DataType.BFloat16)\n T193 = fd.ops.reshape(T189, new_shape=[b * s, e])\n T194 = fd.ops.matmul(T193, fd.mha_linear1_weight)\n\n # Reshape before slicing to avoid slicing along sharded dimensions.\n T195 = fd.ops.reshape(fd.mha_linear0_out, new_shape=[b, s, h, 3 * e // h])\n T244 = fd.ops.slice(\n T195,\n start_indices=[0, 0, 0, 2 * e // h],\n end_indices=[b, s, h, 3 * e // h],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T250 = fd.ops.slice(\n T195,\n start_indices=[0, 0, 0, e // h],\n end_indices=[b, s, h, 2 * e // h],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T256 = fd.ops.slice(\n T195,\n start_indices=[0, 0, 0, 0],\n end_indices=[b, s, h, e // h],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T238 = fd.ops.reshape(T194, new_shape=[b, s, e])\n T262 = fd.ops.reshape(T238, new_shape=[b, s, h, e // h])\n T263 = fd.ops.permute(T244, dims=[0, 2, 1, 3])\n T264 = fd.ops.permute(T250, dims=[0, 2, 1, 3])\n T265 = fd.ops.permute(T256, dims=[0, 2, 1, 3])\n T266 = fd.ops.permute(T262, dims=[0, 2, 1, 3])\n S267 = fd.define_scalar(0.100000, dtype=DataType.Double)\n S268 = fd.define_scalar(True, dtype=DataType.Bool)\n T269, T270, T271 = fd.ops.sdpfa_bwd(\n T266,\n T265,\n T264,\n T263,\n fd.sdpa_out,\n fd.sdpa_logsum_exp,\n S267,\n S268,\n fd.sdpa_seed,\n fd.sdpa_offset,\n None,\n )\n T272 = fd.ops.permute(T271, dims=[0, 2, 1, 3])\n T273 = fd.ops.permute(T270, dims=[0, 2, 1, 3])\n T274 = fd.ops.permute(T269, dims=[0, 2, 1, 3])\n # Cat before reshape to avoid concatenating along sharded dimensions.\n\n T290 = fd.ops.cat([T274, T273, T272], dim=3, manual_padding=0)\n T291 = fd.ops.reshape(T290, new_shape=[b, s, 3 * e])\n T294 = fd.ops.reshape(T291, new_shape=[b * s, 3 * e])\n T295 = fd.ops.matmul(T294, fd.mha_linear0_weight)\n layernorm0_out_grad = fd.ops.reshape(T295, new_shape=[b, s, e])\n T305 = fd.ops.broadcast_in_dim(\n fd.layernorm0_weight, shape=[b, s, e], broadcast_dims=[2]\n )\n T310 = fd.ops.broadcast_in_dim(\n fd.layernorm0_mean, shape=[b, s, 1], broadcast_dims=[0, 1]\n )\n T311 = fd.ops.cast(layernorm0_out_grad, dtype=DataType.Float)\n T312 = fd.ops.cast(T305, dtype=DataType.Float)\n T317 = fd.ops.broadcast_in_dim(T310, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T318 = fd.ops.mul(T312, T311)\n T319 = fd.ops.sub(T98, T317)\n T320 = fd.ops.mul(T319, T318)\n T321 = fd.ops.sum(T320, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T326 = fd.ops.broadcast_in_dim(T321, shape=[b, s, 1], broadcast_dims=[1])\n T331 = fd.ops.broadcast_in_dim(\n fd.layernorm0_rstd, shape=[b, s, e], broadcast_dims=[0, 1, 2]\n )\n S332 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T333 = fd.ops.pow(fd.layernorm0_rstd, S332)\n S334 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T335 = fd.ops.mul(S334, T326)\n T336 = fd.ops.mul(T331, T318)\n T337 = fd.ops.mul(T335, T333)\n T338 = fd.ops.neg(T336)\n T339 = fd.ops.sum(T337, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T340 = fd.ops.sum(T338, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T344 = fd.ops.broadcast_in_dim(T339, shape=[b, s], broadcast_dims=[1])\n T349 = fd.ops.broadcast_in_dim(T340, shape=[b, s, 1], broadcast_dims=[1])\n T354 = fd.ops.broadcast_in_dim(\n fd.layernorm0_mean, shape=[b, s, 1], broadcast_dims=[0, 1]\n )\n T359 = fd.ops.broadcast_in_dim(T344, shape=[b, s, 1], broadcast_dims=[0, 1])\n T360 = fd.ops.sum(T349, dims=[0, 2], keepdim=False, dtype=DataType.Null)\n T365 = fd.ops.broadcast_in_dim(T354, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T370 = fd.ops.broadcast_in_dim(T359, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T374 = fd.ops.broadcast_in_dim(T360, shape=[b, s], broadcast_dims=[1])\n T375 = fd.ops.sub(T98, T365)\n S376 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T377 = fd.ops.mul(S376, T370)\n T382 = fd.ops.broadcast_in_dim(T374, shape=[b, s, 1], broadcast_dims=[0, 1])\n T387 = fd.ops.broadcast_in_dim(\n fd.layernorm0_bias, shape=[b, s, e], broadcast_dims=[2]\n )\n T388 = fd.ops.mul(T319, T331)\n T393 = fd.ops.broadcast_in_dim(\n fd.layernorm1_bias, shape=[b, s, e], broadcast_dims=[2]\n )\n T394 = fd.ops.mul(T108, T120)\n T395 = fd.ops.mul(T377, T375)\n T400 = fd.ops.broadcast_in_dim(T382, shape=[b, s, e], broadcast_dims=[0, 1, 2])\n T401 = fd.ops.cast(T387, dtype=DataType.Float)\n T402 = fd.ops.mul(T388, T312)\n T403 = fd.ops.permute(fd.sdpa_out, dims=[0, 2, 1, 3])\n T404 = fd.ops.cast(T393, dtype=DataType.Float)\n T405 = fd.ops.mul(T394, T100)\n S406 = fd.define_scalar(e, dtype=DataType.Double)\n S407 = fd.ops.reciprocal(S406)\n T408 = fd.ops.mul(T395, S407)\n S409 = fd.define_scalar(1 / e, dtype=DataType.Double)\n T410 = fd.ops.mul(S409, T400)\n T411 = fd.ops.add(T402, T401)\n T412 = fd.ops.stride_order(T403, stride_order=[3, 2, 1, 0])\n T413 = fd.ops.add(T405, T404)\n T414 = fd.ops.mul(T51, T57)\n T415 = fd.ops.add(T410, T408)\n T416 = fd.ops.add(T185, T336)\n T417 = fd.ops.mul(T388, T311)\n T418 = fd.ops.cast(T291, dtype=DataType.Float)\n T419 = fd.ops.cast(T411, dtype=DataType.BFloat16)\n T424 = fd.ops.reshape(T412, new_shape=[b, s, e])\n T425 = fd.ops.mul(T394, T99)\n T426 = fd.ops.cast(T413, dtype=DataType.BFloat16)\n T427 = fd.ops.cast(T414, dtype=DataType.BFloat16)\n T428 = fd.ops.add(T416, T415)\n T429 = fd.ops.sum(T417, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T430 = fd.ops.sum(T311, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T431 = fd.ops.sum(T418, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T435 = fd.ops.reshape(T419, new_shape=[b * s, e])\n T436 = fd.ops.permute(T294, dims=[1, 0])\n T437 = fd.ops.sum(\n mha_linear1_out_grad, dims=[0, 1], keepdim=False, dtype=DataType.Null\n )\n T441 = fd.ops.reshape(T424, new_shape=[b * s, e])\n T442 = fd.ops.permute(T193, dims=[1, 0])\n T443 = fd.ops.sum(T425, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T444 = fd.ops.sum(T99, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T445 = fd.ops.sum(T71, dims=[0, 1], keepdim=False, dtype=DataType.Null)\n T449 = fd.ops.reshape(T426, new_shape=[b * s, e])\n T450 = fd.ops.permute(T76, dims=[1, 0])\n T451 = fd.ops.sum(\n mlp_linear1_out_grad, dims=[0, 1], keepdim=False, dtype=DataType.Null\n )\n T455 = fd.ops.reshape(T427, new_shape=[b * s, e * 4])\n T456 = fd.ops.permute(T38, dims=[1, 0])\n inp_grad = fd.ops.cast(T428, dtype=DataType.BFloat16)\n layernorm0_weight_grad = fd.ops.cast(T429, dtype=DataType.BFloat16)\n layernorm0_bias_grad = fd.ops.cast(T430, dtype=DataType.BFloat16)\n mha_linear0_bias_grad = fd.ops.cast(T431, dtype=DataType.BFloat16)\n mha_linear0_weight_grad = fd.ops.matmul(T436, T435)\n mha_linear1_bias_grad = fd.ops.cast(T437, dtype=DataType.BFloat16)\n mha_linear1_weight_grad = fd.ops.matmul(T442, T441)\n layernorm1_weight_grad = fd.ops.cast(T443, dtype=DataType.BFloat16)\n layernorm1_bias_grad = fd.ops.cast(T444, dtype=DataType.BFloat16)\n mlp_linear0_bias_grad = fd.ops.cast(T445, dtype=DataType.BFloat16)\n mlp_linear0_weight_grad = fd.ops.matmul(T450, T449)\n mlp_linear1_bias_grad = fd.ops.cast(T451, dtype=DataType.BFloat16)\n mlp_linear1_weight_grad = fd.ops.matmul(T456, T455)\n fd.add_output(mlp_linear1_weight_grad)\n fd.add_output(mlp_linear1_bias_grad)\n fd.add_output(mlp_linear0_weight_grad)\n fd.add_output(mlp_linear0_bias_grad)\n fd.add_output(layernorm1_bias_grad)\n fd.add_output(layernorm1_weight_grad)\n fd.add_output(mha_linear1_weight_grad)\n fd.add_output(mha_linear1_bias_grad)\n fd.add_output(mha_linear0_weight_grad)\n fd.add_output(mha_linear0_bias_grad)\n fd.add_output(layernorm0_bias_grad)\n fd.add_output(layernorm0_weight_grad)\n fd.add_output(inp_grad)\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n inputs = fd.fusion.inputs()\n for tv in inputs:\n tv.set_device_mesh(mesh)\n\n for tv in [\n fd.mha_linear0_weight,\n fd.mlp_linear0_weight,\n ]:\n tv.outer_split(0, num_devices)\n tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n for tv in [\n fd.sdpa_out,\n fd.sdpa_logsum_exp,\n ]:\n tv.outer_split(1, num_devices)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n for tv in [\n fd.mlp_linear0_out,\n fd.mha_linear0_out,\n fd.mha_linear1_weight,\n fd.mlp_linear1_weight,\n ]:\n tv.outer_split(-1, num_devices)\n tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n if parallelism == Parallelism.SEQUENCE_PARALLEL:\n for tv in [\n fd.out_grad,\n fd.mlp_dropout_mask,\n fd.mha_dropout_mask,\n fd.mha_linear1_out,\n fd.layernorm1_mean,\n fd.layernorm1_rstd,\n fd.inp,\n fd.layernorm0_mean,\n fd.layernorm0_rstd,\n ]:\n tv.outer_split(1, num_devices)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n # Manually scheduling intermediate tensorviews to avoid\n # sub-\n# ... truncated ...","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":true} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer.test_transformer_backward","uri":"program://Fuser/function/tests.python.multidevice.test_transformer.test_transformer_backward#L1057-L1188","kind":"function","name":"test_transformer_backward","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":1057,"end_line":1188,"context_start_line":1037,"context_end_line":1188,"code":"\n for tv in [mlp_linear1_out_grad, mha_linear1_out_grad]:\n tv.set_device_mesh(mesh)\n\n for tv in [layernorm0_out_grad, layernorm1_out_grad]:\n tv.set_device_mesh(mesh)\n tv.outer_split(1, num_devices)\n tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\n \"parallelism\",\n [Parallelism.TENSOR_PARALLEL, Parallelism.SEQUENCE_PARALLEL],\n ids=lambda p: p.name,\n)\n@pytest.mark.mpi\ndef test_transformer_backward(multidevice_test, benchmark, parallelism: Parallelism):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(range(d))\n\n b, s, h, e = 1, 2048, 96, 12288\n\n if parallelism == Parallelism.SEQUENCE_PARALLEL and s % d != 0:\n pytest.skip(\n f\"Sequence length {s} must be divisible by the number \\\n of devices {d} for sequence parallelism.\"\n )\n mlp_linear0_out = torch.testing.make_tensor(\n b, s, e * 4, dtype=torch.bfloat16, device=\"cpu\"\n )\n out_grad = torch.testing.make_tensor(b, s, e, dtype=torch.bfloat16, device=\"cpu\")\n mlp_dropout_mask = torch.testing.make_tensor(\n b, s, e, dtype=torch.bool, device=\"cpu\"\n )\n mlp_linear1_weight = torch.testing.make_tensor(\n e, e * 4, dtype=torch.bfloat16, device=\"cpu\"\n )\n mha_dropout_mask = torch.testing.make_tensor(\n b, s, e, dtype=torch.bool, device=\"cpu\"\n )\n mha_linear1_out = torch.testing.make_tensor(\n b, s, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n mlp_linear0_weight = torch.testing.make_tensor(\n e * 4, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n layernorm1_mean = torch.testing.make_tensor(b, s, dtype=torch.float32, device=\"cpu\")\n inp = torch.testing.make_tensor(b, s, e, dtype=torch.bfloat16, device=\"cpu\")\n layernorm1_rstd = torch.testing.make_tensor(\n b, s, 1, dtype=torch.float32, device=\"cpu\"\n )\n mha_linear1_weight = torch.testing.make_tensor(\n e, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n mha_linear0_out = torch.testing.make_tensor(\n b, s, e * 3, dtype=torch.bfloat16, device=\"cpu\"\n )\n sdpa_out = torch.testing.make_tensor(\n b, h, s, e // h, dtype=torch.bfloat16, device=\"cpu\"\n )\n\n sdpa_logsumexp = torch.testing.make_tensor(\n b, h, s, dtype=torch.float32, device=\"cpu\"\n )\n mha_linear0_weight = torch.testing.make_tensor(\n e * 3, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n layernorm0_mean = torch.testing.make_tensor(b, s, dtype=torch.float32, device=\"cpu\")\n layernorm0_rstd = torch.testing.make_tensor(\n b, s, 1, dtype=torch.float32, device=\"cpu\"\n )\n sdpa_philox_seed, sdpa_philox_offset = create_sdpa_rng_tensors()\n\n def maybe_shard_sequence(tensor):\n if parallelism == Parallelism.SEQUENCE_PARALLEL:\n return multidevice_test.shard_tensor_1d(tensor, 1, mesh)\n else:\n return tensor.cuda()\n\n ins = [\n multidevice_test.shard_tensor_1d(mlp_linear0_out, -1, mesh),\n maybe_shard_sequence(out_grad),\n maybe_shard_sequence(mlp_dropout_mask),\n multidevice_test.shard_tensor_1d(mlp_linear1_weight, -1, mesh),\n maybe_shard_sequence(mha_dropout_mask),\n maybe_shard_sequence(mha_linear1_out),\n multidevice_test.shard_tensor_1d(mlp_linear0_weight, 0, mesh),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n maybe_shard_sequence(layernorm1_mean),\n maybe_shard_sequence(inp),\n maybe_shard_sequence(layernorm1_rstd),\n multidevice_test.shard_tensor_1d(mha_linear1_weight, -1, mesh),\n multidevice_test.shard_tensor_1d(mha_linear0_out, -1, mesh),\n multidevice_test.shard_tensor_1d(sdpa_out, 1, mesh)\n .transpose(1, 2)\n .contiguous()\n .transpose(1, 2),\n multidevice_test.shard_tensor_1d(sdpa_logsumexp, 1, mesh),\n sdpa_philox_seed,\n sdpa_philox_offset,\n multidevice_test.shard_tensor_1d(mha_linear0_weight, 0, mesh),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n maybe_shard_sequence(layernorm0_mean),\n maybe_shard_sequence(layernorm0_rstd),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n ]\n\n with FusionDefinition() as fd:\n transformer_backward_definition(fd, b, s, h, e, parallelism, d)\n\n # Resize scheduler disabled due to #4890\n warmup_fn, benchmark_fn = get_benchmark_fns(\n lambda: fd.execute(ins, _disable_options=[\"resize_scheduler\"])\n )\n\n s_local = s // d if parallelism == Parallelism.SEQUENCE_PARALLEL else s\n\n (\n mlp_linear1_weight_grad,\n mlp_linear1_bias_grad,\n mlp_linear0_weight_grad,\n mlp_linear0_bias_grad,\n layernorm1_bias_grad,\n layernorm1_weight_grad,\n mha_linear1_weight_grad,\n mha_linear1_bias_grad,\n mha_linear0_weight_grad,\n mha_linear0_bias_grad,\n layernorm0_bias_grad,\n layernorm0_weight_grad,\n inp_grad,\n ) = warmup_fn()\n _assert_shape_dtype(mlp_linear1_weight_grad, [e, e * 4 // d], torch.bfloat16)\n _assert_shape_dtype(mlp_linear1_bias_grad, [e], torch.bfloat16)\n _assert_shape_dtype(mlp_linear0_weight_grad, [e * 4 // d, e], torch.bfloat16)\n _assert_shape_dtype(mlp_linear0_bias_grad, [e * 4 // d], torch.bfloat16)\n _assert_shape_dtype(layernorm1_bias_grad, [e], torch.bfloat16)\n _assert_shape_dtype(layernorm1_weight_grad, [e], torch.bfloat16)\n _assert_shape_dtype(mha_linear1_weight_grad, [e, e // d], torch.bfloat16)\n _assert_shape_dtype(mha_linear1_bias_grad, [e], torch.bfloat16)\n _assert_shape_dtype(mha_linear0_weight_grad, [e * 3 // d, e], torch.bfloat16)\n _assert_shape_dtype(mha_linear0_bias_grad, [e * 3 // d], torch.bfloat16)\n _assert_shape_dtype(layernorm0_bias_grad, [e], torch.bfloat16)\n _assert_shape_dtype(layernorm0_weight_grad, [e], torch.bfloat16)\n _assert_shape_dtype(inp_grad, [b, s_local, e], torch.bfloat16)\n\n benchmark.pedantic(benchmark_fn, rounds=5)","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_transformer.maybe_shard_sequence","uri":"program://Fuser/function/tests.python.multidevice.test_transformer.maybe_shard_sequence#L1114-L1118","kind":"function","name":"maybe_shard_sequence","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":1114,"end_line":1118,"context_start_line":1094,"context_end_line":1138,"code":" )\n mha_linear0_out = torch.testing.make_tensor(\n b, s, e * 3, dtype=torch.bfloat16, device=\"cpu\"\n )\n sdpa_out = torch.testing.make_tensor(\n b, h, s, e // h, dtype=torch.bfloat16, device=\"cpu\"\n )\n\n sdpa_logsumexp = torch.testing.make_tensor(\n b, h, s, dtype=torch.float32, device=\"cpu\"\n )\n mha_linear0_weight = torch.testing.make_tensor(\n e * 3, e, dtype=torch.bfloat16, device=\"cpu\"\n )\n layernorm0_mean = torch.testing.make_tensor(b, s, dtype=torch.float32, device=\"cpu\")\n layernorm0_rstd = torch.testing.make_tensor(\n b, s, 1, dtype=torch.float32, device=\"cpu\"\n )\n sdpa_philox_seed, sdpa_philox_offset = create_sdpa_rng_tensors()\n\n def maybe_shard_sequence(tensor):\n if parallelism == Parallelism.SEQUENCE_PARALLEL:\n return multidevice_test.shard_tensor_1d(tensor, 1, mesh)\n else:\n return tensor.cuda()\n\n ins = [\n multidevice_test.shard_tensor_1d(mlp_linear0_out, -1, mesh),\n maybe_shard_sequence(out_grad),\n maybe_shard_sequence(mlp_dropout_mask),\n multidevice_test.shard_tensor_1d(mlp_linear1_weight, -1, mesh),\n maybe_shard_sequence(mha_dropout_mask),\n maybe_shard_sequence(mha_linear1_out),\n multidevice_test.shard_tensor_1d(mlp_linear0_weight, 0, mesh),\n torch.testing.make_tensor((e,), dtype=torch.bfloat16, device=\"cuda\"),\n maybe_shard_sequence(layernorm1_mean),\n maybe_shard_sequence(inp),\n maybe_shard_sequence(layernorm1_rstd),\n multidevice_test.shard_tensor_1d(mha_linear1_weight, -1, mesh),\n multidevice_test.shard_tensor_1d(mha_linear0_out, -1, mesh),\n multidevice_test.shard_tensor_1d(sdpa_out, 1, mesh)\n .transpose(1, 2)\n .contiguous()\n .transpose(1, 2),\n multidevice_test.shard_tensor_1d(sdpa_logsumexp, 1, mesh),","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul","uri":"program://Fuser/module/tests.python.multidevice.test_matmul#L1-L505","kind":"module","name":"tests.python.multidevice.test_matmul","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":1,"end_line":505,"context_start_line":1,"context_end_line":505,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition, PythonProfiler\n\n\n# Avoid doing this when possible. This test started to exist before nvFuser\n# supports DID loop split. As a result of that, the weight in this test has to be\n# 3D, different from a normal linear.\n@pytest.mark.mpi\ndef test_linear_logical_split(multidevice_test):\n d = multidevice_test.size\n\n b, s, e = 2, 1024, 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([b, s, e])\n weight_tv = fd.define_tensor([d, e, e], contiguity=True)\n bias_tv = fd.define_tensor([d, e], contiguity=True)\n out = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, bias_tv]:\n t.set_device_mesh(mesh)\n for t in [weight_tv, bias_tv]:\n t.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(d, e, e)\n bias_ref = torch.randn(d, e)\n # [b, s, d * e]\n out_ref = torch.nn.functional.linear(\n inp_ref, weight_ref.view(-1, e), bias_ref.view(-1)\n )\n out_ref = out_ref.view(b, s, d, e).permute(2, 0, 1, 3)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n\n (out,) = fd.execute([inp, weight, bias])\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor_1d(out_ref, 0, mesh), rtol=1.3e-6, atol=1e-3\n )\n\n\n@pytest.mark.mpi\ndef test_column_parallel_linear(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n e = 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, e])\n weight_tv = fd.define_tensor([d * e, e])\n bias_tv = fd.define_tensor([d * e])\n out = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out)\n\n for t in [inp_tv, weight_tv, bias_tv]:\n t.set_device_mesh(mesh)\n\n # Shard N for weight (N, K) and bias (N)\n for t in [weight_tv, bias_tv]:\n t.outer_split(0, d)\n t.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(d * e, e)\n bias_ref = torch.randn(d * e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n (out,) = fd.execute([inp, weight, bias])\n\n # [b, s, d*e]\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor_1d(out_ref, 2, mesh), rtol=1.3e-6, atol=1e-3\n )\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear(multidevice_test):\n d = multidevice_test.size\n e = 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, d * e])\n weight_tv = fd.define_tensor([e, d * e])\n out = fd.ops.linear(inp_tv, weight_tv, None)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n inp_ref = torch.randn(b, s, d * e)\n weight_ref = torch.randn(e, d * e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n (out,) = fd.execute([inp, weight])\n\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1.3e-6, atol=1e-3)\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear_with_bias(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n e = 5\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, d * e])\n weight_tv = fd.define_tensor([e, d * e])\n bias_tv = fd.define_tensor([e])\n out = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out)\n\n for t in [inp_tv, weight_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n bias_tv.set_device_mesh(mesh)\n\n b, s = 2, 3\n inp_ref = torch.randn(b, s, d * e)\n weight_ref = torch.randn(e, d * e)\n bias_ref = torch.randn(e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n (out,) = fd.execute([inp, weight, bias])\n\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1.3e-6, atol=1e-3)\n\n\n@pytest.mark.mpi\ndef test_linear_reduce_scatter(multidevice_test):\n d = multidevice_test.size\n b, s, e = 3, 5, 7\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, d * s, d * e], dtype=DataType.BFloat16)\n weight_tv = fd.define_tensor([-1, d * e], dtype=DataType.BFloat16)\n bias_tv = fd.define_tensor([e], dtype=DataType.BFloat16)\n out_tv = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n bias_tv.set_device_mesh(mesh)\n for tv in [inp_tv, weight_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.split(-1, d, inner_split=False)\n tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.outer_split(1, d)\n out_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randint(-2, 3, (b, d * s, d * e)).to(torch.bfloat16)\n weight_ref = torch.randint(-2, 3, (e, d * e)).to(torch.bfloat16)\n bias_ref = torch.randint(-2, 3, (e,)).to(torch.bfloat16)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n\n with PythonProfiler() as prof:\n (out,) = fd.execute([inp, weight, bias])\n\n # Only one reduce scatter kernel should be scheduled.\n assert len(\n [kp for kp in prof.profile.kernel_profiles if kp.scheduler == \"communication\"]\n ) == (1 if d > 1 else 0)\n\n torch.testing.assert_close(\n out,\n multidevice_test.shard_tensor(out_ref, out_tv),\n )\n\n\n@pytest.mark.mpi\ndef test_column_parallel_matmul(multidevice_test):\n d = multidevice_test.size\n e = 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, e]) # [b, s, e]\n weight_tv = fd.define_tensor([e, d * e])\n out = fd.ops.matmul(inp_tv, weight_tv) # [b, s, d*e]\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, out]:\n t.set_device_mesh(mesh)\n\n # Shard N for weight (K, N)\n weight_tv.outer_split(-1, d)\n weight_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n # Output of linear: {.., i{M}, i{N}, r{K}}\n # Shard N -> axis(-2)\n out.outer_split(-2, d)\n out.axis(-3).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(e, d * e)\n out_ref = torch.matmul(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n (out,) = fd.execute([inp, weight])\n\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor_1d(out_ref, 2, mesh), rtol=1.3e-6, atol=1e-3\n )\n\n\n@pytest.mark.mpi\ndef test_row_parallel_matmul(multidevice_test):\n d = multidevice_test.size\n e = 8\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, d * e], contiguity=True, dtype=DataType.Half)\n weight_tv = fd.define_tensor([d * e, e], contiguity=True, dtype=DataType.Half)\n out = fd.ops.matmul(inp_tv, weight_tv)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, out]:\n t.set_device_mesh(mesh)\n\n # Shard K for inp (M, K)\n inp_tv.outer_split(-1, d)\n inp_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n # Shard K for weight (K, N)\n weight_tv.outer_split(0, d)\n weight_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n # I don't think the manual rFactor is necessary any more.\n # DecomposeReshardingsPass should handle it.\n #\n # [i{M}, i{N}, r{K}]\n out.outer_split(-1, d)\n # [i{M}, i{N}, r{d}, r{K//d}]\n local_out = out.rfactor(axes=[-1])\n # local_out = [i{M}, i{N}, i{d}, r{K//d}]\n # out = [i{M}, i{N}, r{d}]\n local_out.set_device_mesh(mesh)\n local_out.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 1, 4\n inp_ref = torch.randn(b * s, d * e, dtype=torch.half)\n weight_ref = torch.randn(d * e, e, dtype=torch.half)\n out_ref = torch.matmul(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n (out,) = fd.execute([inp, weight])\n\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1e-3, atol=1e-2)\n\n\n@pytest.mark.mpi\ndef test_column_parallel_grouped_mm(multidevice_test):\n d = multidevice_test.size\n g = 4\n k = 16\n n = 64 * d\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, k], dtype=DataType.BFloat16, contiguity=True)\n w_tv = fd.define_tensor([g, n, k], dtype=DataType.BFloat16, contiguity=True)\n w_t = fd.ops.permute(w_tv, [0, 2, 1])\n offsets_tv = fd.define_tensor([g], dtype=DataType.Int32, contiguity=True)\n out = fd.ops.grouped_mm(inp_tv, w_t, offsets_tv)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, w_tv, offsets_tv]:\n t.set_device_mesh(mesh)\n\n w_tv.outer_split(1, d)\n w_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 32\n inp_ref = torch.randn(m, k, dtype=torch.bfloat16)\n w_ref = torch.randn(g, n, k, dtype=torch.bfloat16)\n group_sizes = [5, 7, 9, 11]\n assert sum(group_sizes) == m\n group_outs = [\n group_in @ group_w.T\n for group_in, group_w in zip(inp_ref.split(group_sizes), w_ref.unbind())\n ]\n out_ref = torch.cat(group_outs, dim=0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n w = multidevice_test.shard_tensor(w_ref, w_tv)\n offsets = torch.cumsum(torch.tensor(group_sizes), 0, dtype=torch.int32).cuda()\n (out,) = fd.execute([inp, w, offsets])\n\n torch.testing.assert_close(out, multidevice_test.shard_tensor_1d(out_ref, 1, mesh))\n\n\n@pytest.mark.mpi\ndef test_row_parallel_grouped_mm(multidevice_test):\n d = multidevice_test.size\n g = 4\n k = 16 * d\n n = 64\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, k], dtype=DataType.BFloat16, contiguity=True)\n w_tv = fd.define_tensor([g, n, k], dtype=DataType.BFloat16, contiguity=True)\n w_t = fd.ops.permute(w_tv, [0, 2, 1])\n offsets_tv = fd.define_tensor([g], dtype=DataType.Int32, contiguity=True)\n out_tv = fd.ops.grouped_mm(inp_tv, w_t, offsets_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, w_tv, offsets_tv]:\n t.set_device_mesh(mesh)\n\n inp_tv.outer_split(-1, d)\n inp_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n w_tv.outer_split(-1, d)\n w_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 32\n inp_ref = torch.randint(-2, 3, (m, k), dtype=torch.bfloat16)\n w_ref = torch.randint(-2, 3, (g, n, k), dtype=torch.bfloat16)\n group_sizes = [5, 7, 9, 11]\n assert sum(group_sizes) == m\n group_outs = [\n group_in @ group_w.T\n for group_in, group_w in zip(inp_ref.split(group_sizes), w_ref.unbind())\n ]\n out_ref = torch.cat(group_outs, dim=0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n w = multidevice_test.shard_tensor(w_ref, w_tv)\n offsets = torch.cumsum(torch.tensor(group_sizes), 0, dtype=torch.int32).cuda()\n (out,) = fd.execute([inp, w, offsets])\n\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_issue4729(multidevice_test):\n d = multidevice_test.size\n\n with FusionDefinition() as fd:\n x_tv = fd.define_tensor([1, 1, d * 3], dtype=DataType.BFloat16, contiguity=True)\n y_tv = fd.define_tensor([1, 1, d * 3], dtype=DataType.BFloat16, contiguity=True)\n w_tv = fd.define_tensor([-1, d * 3], dtype=DataType.BFloat16, contiguity=True)\n x = fd.ops.cast(x_tv, DataType.Float)\n y = fd.ops.cast(y_tv, DataType.Float)\n xy = fd.ops.mul(x, y)\n xy = fd.ops.cast(xy, DataType.BFloat16)\n z = fd.ops.linear(xy, w_tv)\n fd.add_output(z)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [x_tv, y_tv, w_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n x_ref = torch.randint(-2, 3, (1, 1, d * 3), dtype=torch.bfloat16)\n y_ref = torch.randint(-2, 3, (1, 1, d * 3), dtype=torch.bfloat16)\n w_ref = torch.randint(-2, 3, (2, d * 3), dtype=torch.bfloat16)\n z_ref = torch.nn.functional.linear(x_ref * y_ref, w_ref)\n\n x = multidevice_test.shard_tensor(x_ref, x_tv)\n y = multidevice_test.shard_tensor(y_ref, y_tv)\n w = multidevice_test.shard_tensor(w_ref, w_tv)\n (z,) = fd.execute([x, y, w])\n\n torch.testing.assert_close(z.cpu(), z_ref)\n\n\n@pytest.mark.mpi\ndef test_sequence_parallel_linear(multidevice_test):\n d = multidevice_test.size\n b, s, e = 2, 1024, 768\n assert (\n s % d == 0\n ), f\"Sequence length {s} must be divisible by the number of devices {d}\"\n assert e % d == 0, f\"Hidden size {e} must be divisible by the number of devices {d}\"\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(shape=[-1, -1, -1], contiguity=True) # [b, s, e]\n weight_tv = fd.define_tensor(shape=[-1, -1], contiguity=True) # [e, e]\n bias_tv = fd.define_tensor(shape=[-1], contiguity=True) # [e]\n out_tv = fd.ops.linear(inp_tv, weight_tv, bias_tv) # [b, s, e]\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, bias_tv, out_tv]:\n t.set_device_mesh(mesh)\n\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n weight_tv.outer_split(0, d)\n weight_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n bias_tv.outer_split(0, d)\n bias_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n out_tv.outer_split(1, d)\n out_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(e, e)\n bias_ref = torch.randn(e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n (out,) = fd.execute([inp, weight, bias])\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor(out_ref, out_tv), rtol=1e-3, atol=1e-2\n )\n\n\n@pytest.mark.mpi\ndef test_data_and_tensor_parallel_mlp(multidevice_test):\n # Build a GPT-3 style MLP with data and tensor parallelism.\n d = multidevice_test.size\n tp_size = 2\n\n if d % tp_size != 0:\n pytest.skip(f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\")\n\n dp_size = d // tp_size\n\n e = 3\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, e], contiguity=True)\n up_w_tv = fd.define_tensor([4 * e, e], contiguity=True)\n down_w_tv = fd.define_tensor([e, 4 * e], contiguity=True)\n up_out = fd.ops.linear(inp_tv, up_w_tv)\n down_out = fd.ops.linear(up_out, down_w_tv)\n fd.add_output(down_out)\n\n # mesh_y (dim 0) for data parallelism, mesh_x (dim 1) for tensor parallelism\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d).reshape(dp_size, tp_size))\n for t in [inp_tv, up_w_tv, down_w_tv]:\n t.set_device_mesh(mesh)\n\n inp_tv.outer_split(0, dp_size)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n up_w_tv.outer_split(0, tp_size)\n up_w_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n down_w_tv.outer_split(-1, tp_size)\n down_w_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n batch_per_rank = 7\n b, s = dp_size * batch_per_rank, 5\n\n inp_ref = torch.testing.make_tensor(b, s, e, dtype=torch.int32, device=\"cpu\").to(\n torch.float\n )\n up_w_ref = torch.testing.make_tensor(4 * e, e, dtype=torch.int32, device=\"cpu\").to(\n torch.float\n )\n down_w_ref = torch.testing.make_tensor(\n e, 4 * e, dtype=torch.int32, device=\"cpu\"\n ).to(torch.float)\n up_out_ref = torch.nn.functional.linear(inp_ref, up_w_ref)\n down_out_ref = torch.nn.functional.linear(up_out_ref, down_w_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n up_w = multidevice_test.shard_tensor(up_w_ref, up_w_tv)\n down_w = multidevice_test.shard_tensor(down_w_ref, down_w_tv)\n (out,) = fd.execute([inp, up_w, down_w])\n\n dp_rank = multidevice_test.rank // tp_size\n torch.testing.assert_close(\n out.cpu(),\n down_out_ref[dp_rank * batch_per_rank : (dp_rank + 1) * batch_per_rank],\n )","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_linear_logical_split","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_linear_logical_split#L16-L50","kind":"function","name":"test_linear_logical_split","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":16,"end_line":50,"context_start_line":1,"context_end_line":70,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition, PythonProfiler\n\n\n# Avoid doing this when possible. This test started to exist before nvFuser\n# supports DID loop split. As a result of that, the weight in this test has to be\n# 3D, different from a normal linear.\n@pytest.mark.mpi\ndef test_linear_logical_split(multidevice_test):\n d = multidevice_test.size\n\n b, s, e = 2, 1024, 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([b, s, e])\n weight_tv = fd.define_tensor([d, e, e], contiguity=True)\n bias_tv = fd.define_tensor([d, e], contiguity=True)\n out = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, bias_tv]:\n t.set_device_mesh(mesh)\n for t in [weight_tv, bias_tv]:\n t.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(d, e, e)\n bias_ref = torch.randn(d, e)\n # [b, s, d * e]\n out_ref = torch.nn.functional.linear(\n inp_ref, weight_ref.view(-1, e), bias_ref.view(-1)\n )\n out_ref = out_ref.view(b, s, d, e).permute(2, 0, 1, 3)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n\n (out,) = fd.execute([inp, weight, bias])\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor_1d(out_ref, 0, mesh), rtol=1.3e-6, atol=1e-3\n )\n\n\n@pytest.mark.mpi\ndef test_column_parallel_linear(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n e = 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, e])\n weight_tv = fd.define_tensor([d * e, e])\n bias_tv = fd.define_tensor([d * e])\n out = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out)\n\n for t in [inp_tv, weight_tv, bias_tv]:\n t.set_device_mesh(mesh)\n\n # Shard N for weight (N, K) and bias (N)\n for t in [weight_tv, bias_tv]:","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_column_parallel_linear","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_column_parallel_linear#L54-L89","kind":"function","name":"test_column_parallel_linear","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":54,"end_line":89,"context_start_line":34,"context_end_line":109,"code":" inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(d, e, e)\n bias_ref = torch.randn(d, e)\n # [b, s, d * e]\n out_ref = torch.nn.functional.linear(\n inp_ref, weight_ref.view(-1, e), bias_ref.view(-1)\n )\n out_ref = out_ref.view(b, s, d, e).permute(2, 0, 1, 3)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n\n (out,) = fd.execute([inp, weight, bias])\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor_1d(out_ref, 0, mesh), rtol=1.3e-6, atol=1e-3\n )\n\n\n@pytest.mark.mpi\ndef test_column_parallel_linear(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n e = 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, e])\n weight_tv = fd.define_tensor([d * e, e])\n bias_tv = fd.define_tensor([d * e])\n out = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out)\n\n for t in [inp_tv, weight_tv, bias_tv]:\n t.set_device_mesh(mesh)\n\n # Shard N for weight (N, K) and bias (N)\n for t in [weight_tv, bias_tv]:\n t.outer_split(0, d)\n t.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(d * e, e)\n bias_ref = torch.randn(d * e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n (out,) = fd.execute([inp, weight, bias])\n\n # [b, s, d*e]\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor_1d(out_ref, 2, mesh), rtol=1.3e-6, atol=1e-3\n )\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear(multidevice_test):\n d = multidevice_test.size\n e = 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, d * e])\n weight_tv = fd.define_tensor([e, d * e])\n out = fd.ops.linear(inp_tv, weight_tv, None)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_row_parallel_linear","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_row_parallel_linear#L93-L119","kind":"function","name":"test_row_parallel_linear","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":93,"end_line":119,"context_start_line":73,"context_end_line":139,"code":"\n b, s = 2, 1024\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(d * e, e)\n bias_ref = torch.randn(d * e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n (out,) = fd.execute([inp, weight, bias])\n\n # [b, s, d*e]\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor_1d(out_ref, 2, mesh), rtol=1.3e-6, atol=1e-3\n )\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear(multidevice_test):\n d = multidevice_test.size\n e = 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, d * e])\n weight_tv = fd.define_tensor([e, d * e])\n out = fd.ops.linear(inp_tv, weight_tv, None)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n inp_ref = torch.randn(b, s, d * e)\n weight_ref = torch.randn(e, d * e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n (out,) = fd.execute([inp, weight])\n\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1.3e-6, atol=1e-3)\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear_with_bias(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n e = 5\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, d * e])\n weight_tv = fd.define_tensor([e, d * e])\n bias_tv = fd.define_tensor([e])\n out = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out)\n\n for t in [inp_tv, weight_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n bias_tv.set_device_mesh(mesh)","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_row_parallel_linear_with_bias","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_row_parallel_linear_with_bias#L123-L153","kind":"function","name":"test_row_parallel_linear_with_bias","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":123,"end_line":153,"context_start_line":103,"context_end_line":173,"code":" mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n inp_ref = torch.randn(b, s, d * e)\n weight_ref = torch.randn(e, d * e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n (out,) = fd.execute([inp, weight])\n\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1.3e-6, atol=1e-3)\n\n\n@pytest.mark.mpi\ndef test_row_parallel_linear_with_bias(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n e = 5\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, d * e])\n weight_tv = fd.define_tensor([e, d * e])\n bias_tv = fd.define_tensor([e])\n out = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out)\n\n for t in [inp_tv, weight_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n bias_tv.set_device_mesh(mesh)\n\n b, s = 2, 3\n inp_ref = torch.randn(b, s, d * e)\n weight_ref = torch.randn(e, d * e)\n bias_ref = torch.randn(e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n (out,) = fd.execute([inp, weight, bias])\n\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1.3e-6, atol=1e-3)\n\n\n@pytest.mark.mpi\ndef test_linear_reduce_scatter(multidevice_test):\n d = multidevice_test.size\n b, s, e = 3, 5, 7\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, d * s, d * e], dtype=DataType.BFloat16)\n weight_tv = fd.define_tensor([-1, d * e], dtype=DataType.BFloat16)\n bias_tv = fd.define_tensor([e], dtype=DataType.BFloat16)\n out_tv = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n bias_tv.set_device_mesh(mesh)\n for tv in [inp_tv, weight_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.split(-1, d, inner_split=False)\n tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_linear_reduce_scatter","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_linear_reduce_scatter#L157-L198","kind":"function","name":"test_linear_reduce_scatter","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":157,"end_line":198,"context_start_line":137,"context_end_line":218,"code":" t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n bias_tv.set_device_mesh(mesh)\n\n b, s = 2, 3\n inp_ref = torch.randn(b, s, d * e)\n weight_ref = torch.randn(e, d * e)\n bias_ref = torch.randn(e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n (out,) = fd.execute([inp, weight, bias])\n\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1.3e-6, atol=1e-3)\n\n\n@pytest.mark.mpi\ndef test_linear_reduce_scatter(multidevice_test):\n d = multidevice_test.size\n b, s, e = 3, 5, 7\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, d * s, d * e], dtype=DataType.BFloat16)\n weight_tv = fd.define_tensor([-1, d * e], dtype=DataType.BFloat16)\n bias_tv = fd.define_tensor([e], dtype=DataType.BFloat16)\n out_tv = fd.ops.linear(inp_tv, weight_tv, bias_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n bias_tv.set_device_mesh(mesh)\n for tv in [inp_tv, weight_tv, out_tv]:\n tv.set_device_mesh(mesh)\n tv.split(-1, d, inner_split=False)\n tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n out_tv.outer_split(1, d)\n out_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randint(-2, 3, (b, d * s, d * e)).to(torch.bfloat16)\n weight_ref = torch.randint(-2, 3, (e, d * e)).to(torch.bfloat16)\n bias_ref = torch.randint(-2, 3, (e,)).to(torch.bfloat16)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n\n with PythonProfiler() as prof:\n (out,) = fd.execute([inp, weight, bias])\n\n # Only one reduce scatter kernel should be scheduled.\n assert len(\n [kp for kp in prof.profile.kernel_profiles if kp.scheduler == \"communication\"]\n ) == (1 if d > 1 else 0)\n\n torch.testing.assert_close(\n out,\n multidevice_test.shard_tensor(out_ref, out_tv),\n )\n\n\n@pytest.mark.mpi\ndef test_column_parallel_matmul(multidevice_test):\n d = multidevice_test.size\n e = 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, e]) # [b, s, e]\n weight_tv = fd.define_tensor([e, d * e])\n out = fd.ops.matmul(inp_tv, weight_tv) # [b, s, d*e]\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, out]:\n t.set_device_mesh(mesh)\n\n # Shard N for weight (K, N)\n weight_tv.outer_split(-1, d)\n weight_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_column_parallel_matmul","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_column_parallel_matmul#L202-L237","kind":"function","name":"test_column_parallel_matmul","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":202,"end_line":237,"context_start_line":182,"context_end_line":257,"code":"\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n\n with PythonProfiler() as prof:\n (out,) = fd.execute([inp, weight, bias])\n\n # Only one reduce scatter kernel should be scheduled.\n assert len(\n [kp for kp in prof.profile.kernel_profiles if kp.scheduler == \"communication\"]\n ) == (1 if d > 1 else 0)\n\n torch.testing.assert_close(\n out,\n multidevice_test.shard_tensor(out_ref, out_tv),\n )\n\n\n@pytest.mark.mpi\ndef test_column_parallel_matmul(multidevice_test):\n d = multidevice_test.size\n e = 768\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, e]) # [b, s, e]\n weight_tv = fd.define_tensor([e, d * e])\n out = fd.ops.matmul(inp_tv, weight_tv) # [b, s, d*e]\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, out]:\n t.set_device_mesh(mesh)\n\n # Shard N for weight (K, N)\n weight_tv.outer_split(-1, d)\n weight_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n # Output of linear: {.., i{M}, i{N}, r{K}}\n # Shard N -> axis(-2)\n out.outer_split(-2, d)\n out.axis(-3).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(e, d * e)\n out_ref = torch.matmul(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n (out,) = fd.execute([inp, weight])\n\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor_1d(out_ref, 2, mesh), rtol=1.3e-6, atol=1e-3\n )\n\n\n@pytest.mark.mpi\ndef test_row_parallel_matmul(multidevice_test):\n d = multidevice_test.size\n e = 8\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, d * e], contiguity=True, dtype=DataType.Half)\n weight_tv = fd.define_tensor([d * e, e], contiguity=True, dtype=DataType.Half)\n out = fd.ops.matmul(inp_tv, weight_tv)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, out]:\n t.set_device_mesh(mesh)\n\n # Shard K for inp (M, K)\n inp_tv.outer_split(-1, d)\n inp_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_row_parallel_matmul","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_row_parallel_matmul#L241-L284","kind":"function","name":"test_row_parallel_matmul","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":241,"end_line":284,"context_start_line":221,"context_end_line":304,"code":" # Shard N -> axis(-2)\n out.outer_split(-2, d)\n out.axis(-3).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(e, d * e)\n out_ref = torch.matmul(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n (out,) = fd.execute([inp, weight])\n\n # rtol is the same as the default for fp32. atol is slightly increased.\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor_1d(out_ref, 2, mesh), rtol=1.3e-6, atol=1e-3\n )\n\n\n@pytest.mark.mpi\ndef test_row_parallel_matmul(multidevice_test):\n d = multidevice_test.size\n e = 8\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, d * e], contiguity=True, dtype=DataType.Half)\n weight_tv = fd.define_tensor([d * e, e], contiguity=True, dtype=DataType.Half)\n out = fd.ops.matmul(inp_tv, weight_tv)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, out]:\n t.set_device_mesh(mesh)\n\n # Shard K for inp (M, K)\n inp_tv.outer_split(-1, d)\n inp_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n # Shard K for weight (K, N)\n weight_tv.outer_split(0, d)\n weight_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n # I don't think the manual rFactor is necessary any more.\n # DecomposeReshardingsPass should handle it.\n #\n # [i{M}, i{N}, r{K}]\n out.outer_split(-1, d)\n # [i{M}, i{N}, r{d}, r{K//d}]\n local_out = out.rfactor(axes=[-1])\n # local_out = [i{M}, i{N}, i{d}, r{K//d}]\n # out = [i{M}, i{N}, r{d}]\n local_out.set_device_mesh(mesh)\n local_out.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 1, 4\n inp_ref = torch.randn(b * s, d * e, dtype=torch.half)\n weight_ref = torch.randn(d * e, e, dtype=torch.half)\n out_ref = torch.matmul(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n (out,) = fd.execute([inp, weight])\n\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1e-3, atol=1e-2)\n\n\n@pytest.mark.mpi\ndef test_column_parallel_grouped_mm(multidevice_test):\n d = multidevice_test.size\n g = 4\n k = 16\n n = 64 * d\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, k], dtype=DataType.BFloat16, contiguity=True)\n w_tv = fd.define_tensor([g, n, k], dtype=DataType.BFloat16, contiguity=True)\n w_t = fd.ops.permute(w_tv, [0, 2, 1])\n offsets_tv = fd.define_tensor([g], dtype=DataType.Int32, contiguity=True)\n out = fd.ops.grouped_mm(inp_tv, w_t, offsets_tv)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, w_tv, offsets_tv]:\n t.set_device_mesh(mesh)","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_column_parallel_grouped_mm","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_column_parallel_grouped_mm#L288-L325","kind":"function","name":"test_column_parallel_grouped_mm","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":288,"end_line":325,"context_start_line":268,"context_end_line":345,"code":" # [i{M}, i{N}, r{d}, r{K//d}]\n local_out = out.rfactor(axes=[-1])\n # local_out = [i{M}, i{N}, i{d}, r{K//d}]\n # out = [i{M}, i{N}, r{d}]\n local_out.set_device_mesh(mesh)\n local_out.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 1, 4\n inp_ref = torch.randn(b * s, d * e, dtype=torch.half)\n weight_ref = torch.randn(d * e, e, dtype=torch.half)\n out_ref = torch.matmul(inp_ref, weight_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n (out,) = fd.execute([inp, weight])\n\n torch.testing.assert_close(out.cpu(), out_ref, rtol=1e-3, atol=1e-2)\n\n\n@pytest.mark.mpi\ndef test_column_parallel_grouped_mm(multidevice_test):\n d = multidevice_test.size\n g = 4\n k = 16\n n = 64 * d\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, k], dtype=DataType.BFloat16, contiguity=True)\n w_tv = fd.define_tensor([g, n, k], dtype=DataType.BFloat16, contiguity=True)\n w_t = fd.ops.permute(w_tv, [0, 2, 1])\n offsets_tv = fd.define_tensor([g], dtype=DataType.Int32, contiguity=True)\n out = fd.ops.grouped_mm(inp_tv, w_t, offsets_tv)\n fd.add_output(out)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, w_tv, offsets_tv]:\n t.set_device_mesh(mesh)\n\n w_tv.outer_split(1, d)\n w_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 32\n inp_ref = torch.randn(m, k, dtype=torch.bfloat16)\n w_ref = torch.randn(g, n, k, dtype=torch.bfloat16)\n group_sizes = [5, 7, 9, 11]\n assert sum(group_sizes) == m\n group_outs = [\n group_in @ group_w.T\n for group_in, group_w in zip(inp_ref.split(group_sizes), w_ref.unbind())\n ]\n out_ref = torch.cat(group_outs, dim=0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n w = multidevice_test.shard_tensor(w_ref, w_tv)\n offsets = torch.cumsum(torch.tensor(group_sizes), 0, dtype=torch.int32).cuda()\n (out,) = fd.execute([inp, w, offsets])\n\n torch.testing.assert_close(out, multidevice_test.shard_tensor_1d(out_ref, 1, mesh))\n\n\n@pytest.mark.mpi\ndef test_row_parallel_grouped_mm(multidevice_test):\n d = multidevice_test.size\n g = 4\n k = 16 * d\n n = 64\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, k], dtype=DataType.BFloat16, contiguity=True)\n w_tv = fd.define_tensor([g, n, k], dtype=DataType.BFloat16, contiguity=True)\n w_t = fd.ops.permute(w_tv, [0, 2, 1])\n offsets_tv = fd.define_tensor([g], dtype=DataType.Int32, contiguity=True)\n out_tv = fd.ops.grouped_mm(inp_tv, w_t, offsets_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, w_tv, offsets_tv]:\n t.set_device_mesh(mesh)","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_row_parallel_grouped_mm","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_row_parallel_grouped_mm#L329-L369","kind":"function","name":"test_row_parallel_grouped_mm","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":329,"end_line":369,"context_start_line":309,"context_end_line":389,"code":" m = 32\n inp_ref = torch.randn(m, k, dtype=torch.bfloat16)\n w_ref = torch.randn(g, n, k, dtype=torch.bfloat16)\n group_sizes = [5, 7, 9, 11]\n assert sum(group_sizes) == m\n group_outs = [\n group_in @ group_w.T\n for group_in, group_w in zip(inp_ref.split(group_sizes), w_ref.unbind())\n ]\n out_ref = torch.cat(group_outs, dim=0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n w = multidevice_test.shard_tensor(w_ref, w_tv)\n offsets = torch.cumsum(torch.tensor(group_sizes), 0, dtype=torch.int32).cuda()\n (out,) = fd.execute([inp, w, offsets])\n\n torch.testing.assert_close(out, multidevice_test.shard_tensor_1d(out_ref, 1, mesh))\n\n\n@pytest.mark.mpi\ndef test_row_parallel_grouped_mm(multidevice_test):\n d = multidevice_test.size\n g = 4\n k = 16 * d\n n = 64\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, k], dtype=DataType.BFloat16, contiguity=True)\n w_tv = fd.define_tensor([g, n, k], dtype=DataType.BFloat16, contiguity=True)\n w_t = fd.ops.permute(w_tv, [0, 2, 1])\n offsets_tv = fd.define_tensor([g], dtype=DataType.Int32, contiguity=True)\n out_tv = fd.ops.grouped_mm(inp_tv, w_t, offsets_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, w_tv, offsets_tv]:\n t.set_device_mesh(mesh)\n\n inp_tv.outer_split(-1, d)\n inp_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n w_tv.outer_split(-1, d)\n w_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n m = 32\n inp_ref = torch.randint(-2, 3, (m, k), dtype=torch.bfloat16)\n w_ref = torch.randint(-2, 3, (g, n, k), dtype=torch.bfloat16)\n group_sizes = [5, 7, 9, 11]\n assert sum(group_sizes) == m\n group_outs = [\n group_in @ group_w.T\n for group_in, group_w in zip(inp_ref.split(group_sizes), w_ref.unbind())\n ]\n out_ref = torch.cat(group_outs, dim=0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n w = multidevice_test.shard_tensor(w_ref, w_tv)\n offsets = torch.cumsum(torch.tensor(group_sizes), 0, dtype=torch.int32).cuda()\n (out,) = fd.execute([inp, w, offsets])\n\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_issue4729(multidevice_test):\n d = multidevice_test.size\n\n with FusionDefinition() as fd:\n x_tv = fd.define_tensor([1, 1, d * 3], dtype=DataType.BFloat16, contiguity=True)\n y_tv = fd.define_tensor([1, 1, d * 3], dtype=DataType.BFloat16, contiguity=True)\n w_tv = fd.define_tensor([-1, d * 3], dtype=DataType.BFloat16, contiguity=True)\n x = fd.ops.cast(x_tv, DataType.Float)\n y = fd.ops.cast(y_tv, DataType.Float)\n xy = fd.ops.mul(x, y)\n xy = fd.ops.cast(xy, DataType.BFloat16)\n z = fd.ops.linear(xy, w_tv)\n fd.add_output(z)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [x_tv, y_tv, w_tv]:\n t.set_device_mesh(mesh)","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_issue4729","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_issue4729#L373-L403","kind":"function","name":"test_issue4729","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":373,"end_line":403,"context_start_line":353,"context_end_line":423,"code":" m = 32\n inp_ref = torch.randint(-2, 3, (m, k), dtype=torch.bfloat16)\n w_ref = torch.randint(-2, 3, (g, n, k), dtype=torch.bfloat16)\n group_sizes = [5, 7, 9, 11]\n assert sum(group_sizes) == m\n group_outs = [\n group_in @ group_w.T\n for group_in, group_w in zip(inp_ref.split(group_sizes), w_ref.unbind())\n ]\n out_ref = torch.cat(group_outs, dim=0)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n w = multidevice_test.shard_tensor(w_ref, w_tv)\n offsets = torch.cumsum(torch.tensor(group_sizes), 0, dtype=torch.int32).cuda()\n (out,) = fd.execute([inp, w, offsets])\n\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_issue4729(multidevice_test):\n d = multidevice_test.size\n\n with FusionDefinition() as fd:\n x_tv = fd.define_tensor([1, 1, d * 3], dtype=DataType.BFloat16, contiguity=True)\n y_tv = fd.define_tensor([1, 1, d * 3], dtype=DataType.BFloat16, contiguity=True)\n w_tv = fd.define_tensor([-1, d * 3], dtype=DataType.BFloat16, contiguity=True)\n x = fd.ops.cast(x_tv, DataType.Float)\n y = fd.ops.cast(y_tv, DataType.Float)\n xy = fd.ops.mul(x, y)\n xy = fd.ops.cast(xy, DataType.BFloat16)\n z = fd.ops.linear(xy, w_tv)\n fd.add_output(z)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [x_tv, y_tv, w_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n x_ref = torch.randint(-2, 3, (1, 1, d * 3), dtype=torch.bfloat16)\n y_ref = torch.randint(-2, 3, (1, 1, d * 3), dtype=torch.bfloat16)\n w_ref = torch.randint(-2, 3, (2, d * 3), dtype=torch.bfloat16)\n z_ref = torch.nn.functional.linear(x_ref * y_ref, w_ref)\n\n x = multidevice_test.shard_tensor(x_ref, x_tv)\n y = multidevice_test.shard_tensor(y_ref, y_tv)\n w = multidevice_test.shard_tensor(w_ref, w_tv)\n (z,) = fd.execute([x, y, w])\n\n torch.testing.assert_close(z.cpu(), z_ref)\n\n\n@pytest.mark.mpi\ndef test_sequence_parallel_linear(multidevice_test):\n d = multidevice_test.size\n b, s, e = 2, 1024, 768\n assert (\n s % d == 0\n ), f\"Sequence length {s} must be divisible by the number of devices {d}\"\n assert e % d == 0, f\"Hidden size {e} must be divisible by the number of devices {d}\"\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(shape=[-1, -1, -1], contiguity=True) # [b, s, e]\n weight_tv = fd.define_tensor(shape=[-1, -1], contiguity=True) # [e, e]\n bias_tv = fd.define_tensor(shape=[-1], contiguity=True) # [e]\n out_tv = fd.ops.linear(inp_tv, weight_tv, bias_tv) # [b, s, e]\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, bias_tv, out_tv]:","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_sequence_parallel_linear","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_sequence_parallel_linear#L407-L446","kind":"function","name":"test_sequence_parallel_linear","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":407,"end_line":446,"context_start_line":387,"context_end_line":466,"code":" mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [x_tv, y_tv, w_tv]:\n t.set_device_mesh(mesh)\n t.outer_split(-1, d)\n t.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n x_ref = torch.randint(-2, 3, (1, 1, d * 3), dtype=torch.bfloat16)\n y_ref = torch.randint(-2, 3, (1, 1, d * 3), dtype=torch.bfloat16)\n w_ref = torch.randint(-2, 3, (2, d * 3), dtype=torch.bfloat16)\n z_ref = torch.nn.functional.linear(x_ref * y_ref, w_ref)\n\n x = multidevice_test.shard_tensor(x_ref, x_tv)\n y = multidevice_test.shard_tensor(y_ref, y_tv)\n w = multidevice_test.shard_tensor(w_ref, w_tv)\n (z,) = fd.execute([x, y, w])\n\n torch.testing.assert_close(z.cpu(), z_ref)\n\n\n@pytest.mark.mpi\ndef test_sequence_parallel_linear(multidevice_test):\n d = multidevice_test.size\n b, s, e = 2, 1024, 768\n assert (\n s % d == 0\n ), f\"Sequence length {s} must be divisible by the number of devices {d}\"\n assert e % d == 0, f\"Hidden size {e} must be divisible by the number of devices {d}\"\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(shape=[-1, -1, -1], contiguity=True) # [b, s, e]\n weight_tv = fd.define_tensor(shape=[-1, -1], contiguity=True) # [e, e]\n bias_tv = fd.define_tensor(shape=[-1], contiguity=True) # [e]\n out_tv = fd.ops.linear(inp_tv, weight_tv, bias_tv) # [b, s, e]\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in [inp_tv, weight_tv, bias_tv, out_tv]:\n t.set_device_mesh(mesh)\n\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n weight_tv.outer_split(0, d)\n weight_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n bias_tv.outer_split(0, d)\n bias_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n out_tv.outer_split(1, d)\n out_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(e, e)\n bias_ref = torch.randn(e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n (out,) = fd.execute([inp, weight, bias])\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor(out_ref, out_tv), rtol=1e-3, atol=1e-2\n )\n\n\n@pytest.mark.mpi\ndef test_data_and_tensor_parallel_mlp(multidevice_test):\n # Build a GPT-3 style MLP with data and tensor parallelism.\n d = multidevice_test.size\n tp_size = 2\n\n if d % tp_size != 0:\n pytest.skip(f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\")\n\n dp_size = d // tp_size\n\n e = 3\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, e], contiguity=True)\n up_w_tv = fd.define_tensor([4 * e, e], contiguity=True)\n down_w_tv = fd.define_tensor([e, 4 * e], contiguity=True)\n up_out = fd.ops.linear(inp_tv, up_w_tv)\n down_out = fd.ops.linear(up_out, down_w_tv)","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_matmul.test_data_and_tensor_parallel_mlp","uri":"program://Fuser/function/tests.python.multidevice.test_matmul.test_data_and_tensor_parallel_mlp#L450-L505","kind":"function","name":"test_data_and_tensor_parallel_mlp","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":450,"end_line":505,"context_start_line":430,"context_end_line":505,"code":" bias_tv.outer_split(0, d)\n bias_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n out_tv.outer_split(1, d)\n out_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(b, s, e)\n weight_ref = torch.randn(e, e)\n bias_ref = torch.randn(e)\n out_ref = torch.nn.functional.linear(inp_ref, weight_ref, bias_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n weight = multidevice_test.shard_tensor(weight_ref, weight_tv)\n bias = multidevice_test.shard_tensor(bias_ref, bias_tv)\n (out,) = fd.execute([inp, weight, bias])\n torch.testing.assert_close(\n out, multidevice_test.shard_tensor(out_ref, out_tv), rtol=1e-3, atol=1e-2\n )\n\n\n@pytest.mark.mpi\ndef test_data_and_tensor_parallel_mlp(multidevice_test):\n # Build a GPT-3 style MLP with data and tensor parallelism.\n d = multidevice_test.size\n tp_size = 2\n\n if d % tp_size != 0:\n pytest.skip(f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\")\n\n dp_size = d // tp_size\n\n e = 3\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1, e], contiguity=True)\n up_w_tv = fd.define_tensor([4 * e, e], contiguity=True)\n down_w_tv = fd.define_tensor([e, 4 * e], contiguity=True)\n up_out = fd.ops.linear(inp_tv, up_w_tv)\n down_out = fd.ops.linear(up_out, down_w_tv)\n fd.add_output(down_out)\n\n # mesh_y (dim 0) for data parallelism, mesh_x (dim 1) for tensor parallelism\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d).reshape(dp_size, tp_size))\n for t in [inp_tv, up_w_tv, down_w_tv]:\n t.set_device_mesh(mesh)\n\n inp_tv.outer_split(0, dp_size)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n up_w_tv.outer_split(0, tp_size)\n up_w_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n down_w_tv.outer_split(-1, tp_size)\n down_w_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n batch_per_rank = 7\n b, s = dp_size * batch_per_rank, 5\n\n inp_ref = torch.testing.make_tensor(b, s, e, dtype=torch.int32, device=\"cpu\").to(\n torch.float\n )\n up_w_ref = torch.testing.make_tensor(4 * e, e, dtype=torch.int32, device=\"cpu\").to(\n torch.float\n )\n down_w_ref = torch.testing.make_tensor(\n e, 4 * e, dtype=torch.int32, device=\"cpu\"\n ).to(torch.float)\n up_out_ref = torch.nn.functional.linear(inp_ref, up_w_ref)\n down_out_ref = torch.nn.functional.linear(up_out_ref, down_w_ref)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n up_w = multidevice_test.shard_tensor(up_w_ref, up_w_tv)\n down_w = multidevice_test.shard_tensor(down_w_ref, down_w_tv)\n (out,) = fd.execute([inp, up_w, down_w])\n\n dp_rank = multidevice_test.rank // tp_size\n torch.testing.assert_close(\n out.cpu(),\n down_out_ref[dp_rank * batch_per_rank : (dp_rank + 1) * batch_per_rank],\n )","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.benchmark_utils","uri":"program://Fuser/module/tests.python.multidevice.benchmark_utils#L1-L37","kind":"module","name":"tests.python.multidevice.benchmark_utils","path":"tests/python/multidevice/benchmark_utils.py","language":"python","start_line":1,"end_line":37,"context_start_line":1,"context_end_line":37,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\n\n\ndef get_benchmark_fn(func, /, profile: bool):\n def wrapper(*args, **kwargs):\n if profile:\n torch.cuda.cudart().cudaProfilerStart()\n result = func(*args, **kwargs)\n torch.cuda.synchronize()\n if profile:\n torch.cuda.cudart().cudaProfilerStop()\n return result\n\n return wrapper\n\n\n# Returns two functors, the first with profiler off and the second with profiler\n# on. The first functor is usually used for warmup and the second for actual\n# benchmarking. This way, one can collect stats of non-warmup\n# benchmark iterations using `nsys profile --capture-range=cudaProfilerApi`.\n#\n# https://docs.nvidia.com/nsight-systems/UserGuide/index.html#handling-application-launchers-mpirun-deepspeed-etc\n# has described several ways to profile multi-process applications.\n#\n# For single-node profiling, I recommend putting `nsys profile` before\n# `mpirun`, e.g., `nsys profile ... mpirun -np 8 ...` instead of `mpirun -np 8\n# nsys profile ...` or `mpirun -np 1 nsys profile ... : -np 7 ...`. This config\n# tries to collect and align traces on different GPUs so it gives the most\n# complete picture. See\n# https://github.com/NVIDIA/Fuser/pull/5751/files#r2663586669 for my\n# experiment.\ndef get_benchmark_fns(func):\n return get_benchmark_fn(func, profile=False), get_benchmark_fn(func, profile=True)","source_hash":"00d4c27aaf09229131f2f2e054be25637ebb5cac813a489a9051c1b8d743a2dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.benchmark_utils.get_benchmark_fn","uri":"program://Fuser/function/tests.python.multidevice.benchmark_utils.get_benchmark_fn#L8-L18","kind":"function","name":"get_benchmark_fn","path":"tests/python/multidevice/benchmark_utils.py","language":"python","start_line":8,"end_line":18,"context_start_line":1,"context_end_line":37,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\n\n\ndef get_benchmark_fn(func, /, profile: bool):\n def wrapper(*args, **kwargs):\n if profile:\n torch.cuda.cudart().cudaProfilerStart()\n result = func(*args, **kwargs)\n torch.cuda.synchronize()\n if profile:\n torch.cuda.cudart().cudaProfilerStop()\n return result\n\n return wrapper\n\n\n# Returns two functors, the first with profiler off and the second with profiler\n# on. The first functor is usually used for warmup and the second for actual\n# benchmarking. This way, one can collect stats of non-warmup\n# benchmark iterations using `nsys profile --capture-range=cudaProfilerApi`.\n#\n# https://docs.nvidia.com/nsight-systems/UserGuide/index.html#handling-application-launchers-mpirun-deepspeed-etc\n# has described several ways to profile multi-process applications.\n#\n# For single-node profiling, I recommend putting `nsys profile` before\n# `mpirun`, e.g., `nsys profile ... mpirun -np 8 ...` instead of `mpirun -np 8\n# nsys profile ...` or `mpirun -np 1 nsys profile ... : -np 7 ...`. This config\n# tries to collect and align traces on different GPUs so it gives the most\n# complete picture. See\n# https://github.com/NVIDIA/Fuser/pull/5751/files#r2663586669 for my\n# experiment.\ndef get_benchmark_fns(func):\n return get_benchmark_fn(func, profile=False), get_benchmark_fn(func, profile=True)","source_hash":"00d4c27aaf09229131f2f2e054be25637ebb5cac813a489a9051c1b8d743a2dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.benchmark_utils.get_benchmark_fns","uri":"program://Fuser/function/tests.python.multidevice.benchmark_utils.get_benchmark_fns#L36-L37","kind":"function","name":"get_benchmark_fns","path":"tests/python/multidevice/benchmark_utils.py","language":"python","start_line":36,"end_line":37,"context_start_line":16,"context_end_line":37,"code":" return result\n\n return wrapper\n\n\n# Returns two functors, the first with profiler off and the second with profiler\n# on. The first functor is usually used for warmup and the second for actual\n# benchmarking. This way, one can collect stats of non-warmup\n# benchmark iterations using `nsys profile --capture-range=cudaProfilerApi`.\n#\n# https://docs.nvidia.com/nsight-systems/UserGuide/index.html#handling-application-launchers-mpirun-deepspeed-etc\n# has described several ways to profile multi-process applications.\n#\n# For single-node profiling, I recommend putting `nsys profile` before\n# `mpirun`, e.g., `nsys profile ... mpirun -np 8 ...` instead of `mpirun -np 8\n# nsys profile ...` or `mpirun -np 1 nsys profile ... : -np 7 ...`. This config\n# tries to collect and align traces on different GPUs so it gives the most\n# complete picture. See\n# https://github.com/NVIDIA/Fuser/pull/5751/files#r2663586669 for my\n# experiment.\ndef get_benchmark_fns(func):\n return get_benchmark_fn(func, profile=False), get_benchmark_fn(func, profile=True)","source_hash":"00d4c27aaf09229131f2f2e054be25637ebb5cac813a489a9051c1b8d743a2dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.benchmark_utils.wrapper","uri":"program://Fuser/function/tests.python.multidevice.benchmark_utils.wrapper#L9-L16","kind":"function","name":"wrapper","path":"tests/python/multidevice/benchmark_utils.py","language":"python","start_line":9,"end_line":16,"context_start_line":1,"context_end_line":36,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\n\n\ndef get_benchmark_fn(func, /, profile: bool):\n def wrapper(*args, **kwargs):\n if profile:\n torch.cuda.cudart().cudaProfilerStart()\n result = func(*args, **kwargs)\n torch.cuda.synchronize()\n if profile:\n torch.cuda.cudart().cudaProfilerStop()\n return result\n\n return wrapper\n\n\n# Returns two functors, the first with profiler off and the second with profiler\n# on. The first functor is usually used for warmup and the second for actual\n# benchmarking. This way, one can collect stats of non-warmup\n# benchmark iterations using `nsys profile --capture-range=cudaProfilerApi`.\n#\n# https://docs.nvidia.com/nsight-systems/UserGuide/index.html#handling-application-launchers-mpirun-deepspeed-etc\n# has described several ways to profile multi-process applications.\n#\n# For single-node profiling, I recommend putting `nsys profile` before\n# `mpirun`, e.g., `nsys profile ... mpirun -np 8 ...` instead of `mpirun -np 8\n# nsys profile ...` or `mpirun -np 1 nsys profile ... : -np 7 ...`. This config\n# tries to collect and align traces on different GPUs so it gives the most\n# complete picture. See\n# https://github.com/NVIDIA/Fuser/pull/5751/files#r2663586669 for my\n# experiment.\ndef get_benchmark_fns(func):","source_hash":"00d4c27aaf09229131f2f2e054be25637ebb5cac813a489a9051c1b8d743a2dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice","uri":"program://Fuser/module/tests.python.multidevice.test_multidevice#L1-L514","kind":"module","name":"tests.python.multidevice.test_multidevice","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":1,"end_line":514,"context_start_line":1,"context_end_line":514,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\nfrom enum import Enum, auto\nfrom torch.nn.attention import SDPBackend\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom python.direct_utils import is_pre_ampere\n\n\n@pytest.mark.mpi\ndef test_sizes_and_ranks(multidevice_test):\n size, rank, local_size, local_rank = (\n multidevice_test.size,\n multidevice_test.rank,\n multidevice_test.local_size,\n multidevice_test.local_rank,\n )\n assert size > 0\n assert rank >= 0 and rank < size\n assert local_size > 0\n assert local_rank >= 0 and local_rank < local_size\n\n\n@pytest.mark.mpi\ndef test_pointwise(multidevice_test):\n num_devices = multidevice_test.size\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), contiguity=False, dtype=DataType.Float)\n tv1 = fd.ops.relu(inp_tv)\n tv2 = fd.ops.add(tv1, tv1)\n fd.add_output(tv2)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n for tv in [inp_tv, tv1, tv2]:\n tv.set_device_mesh(mesh)\n\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(num_devices, 4)\n out_ref = inp_ref.relu() * 2\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_pointwise_vectorization(multidevice_test):\n # Repro for https://github.com/NVIDIA/Fuser/issues/5920\n d = multidevice_test.size\n cp_size = 2\n if d % (cp_size * cp_size) != 0:\n pytest.skip(\n f\"We only support even split, so {d=} has to be divisible by {cp_size * cp_size} for {cp_size=}.\"\n )\n dp_size = d // (cp_size * cp_size)\n\n c = 128\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(\n (-1, c, -1, -1, cp_size), contiguity=True, dtype=DataType.BFloat16\n )\n out_tv = fd.ops.set(inp_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, cp_size, cp_size)\n )\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n\n inp_tv.axis(4).parallelize(nvfuser.ParallelType.mesh_y)\n inp_tv.outer_split(3, cp_size)\n inp_tv.axis(3).parallelize(nvfuser.ParallelType.mesh_x)\n inp_tv.outer_split(0, dp_size)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_z)\n\n out_tv.axis(4).parallelize(nvfuser.ParallelType.mesh_y)\n out_tv.outer_split(3, cp_size)\n out_tv.axis(3).parallelize(nvfuser.ParallelType.mesh_x)\n out_tv.outer_split(0, dp_size)\n out_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_z)\n out_tv.set_allocation_domain(\n (\n out_tv.axis(3),\n out_tv.axis(0),\n out_tv.axis(1),\n out_tv.axis(2),\n out_tv.axis(4),\n out_tv.axis(5),\n out_tv.axis(6),\n ),\n True,\n )\n\n b = dp_size * 3\n s = cp_size * 5\n inp_ref = torch.randn(b, c, s, s, cp_size, dtype=torch.bfloat16)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\nclass QkvFormat(Enum):\n BHSE = auto()\n BSHE = auto()\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"qkv_format\", [QkvFormat.BHSE, QkvFormat.BSHE])\n@pytest.mark.mpi\ndef test_sdpa(multidevice_test, qkv_format: QkvFormat):\n d, b, s, h, e = multidevice_test.size, 2, 1024, 12, 768\n\n if h % d != 0:\n pytest.skip(f\"We only support even split, so {h} has to be divisible by {d}.\")\n\n def _definition(fd: FusionDefinition, qkv_format: QkvFormat) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n stride_order = [4, 3, 2, 1, 0]\n case QkvFormat.BSHE:\n stride_order = [4, 3, 1, 2, 0]\n\n q, k, v, out_grad = [\n fd.define_tensor(\n shape=[d, b, h // d, s, e // h],\n contiguity=True,\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n for _ in range(4)\n ]\n\n # TODO(#3123): support sharded dropout and change this to a\n # positive probability.\n dropout_p = fd.define_scalar(0.0, dtype=DataType.Double)\n is_causal = fd.define_scalar(True, dtype=DataType.Bool)\n attn, logsumexp, seed, offset = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal\n )\n\n q_grad, k_grad, v_grad = fd.ops.sdpfa_bwd(\n out_grad,\n q,\n k,\n v,\n attn,\n logsumexp,\n dropout_p,\n is_causal,\n seed,\n offset,\n scale=None,\n )\n\n fd.add_output(attn)\n for grad in [q_grad, k_grad, v_grad]:\n fd.add_output(grad)\n\n def _multidevice_schedule(fd: FusionDefinition) -> None:\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in fd.fusion.inputs():\n t.set_device_mesh(mesh)\n t.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n def make_unsharded_tensor() -> torch.Tensor:\n return torch.randn(b, h, s, e // h, dtype=torch.bfloat16, device=\"cuda\")\n\n q, k, v = [make_unsharded_tensor().requires_grad_() for _ in range(3)]\n out_grad = make_unsharded_tensor()\n\n with torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n expected_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, dropout_p=0.0, is_causal=True, scale=None\n )\n expected_out.backward(out_grad)\n expected_q_grad, expected_k_grad, expected_v_grad = q.grad, k.grad, v.grad\n\n rank = multidevice_test.rank\n\n # Head-parallelize Q, K, V or the attention output of an SDPA.\n def head_parallelize(t: torch.Tensor) -> torch.Tensor:\n assert t.shape == torch.Size([b, h, s, e // h])\n # The input `t` may require gradient. We .detach() so the new `t`\n # doesn't require gradient.\n t = t.detach().view([b, d, h // d, s, e // h]).narrow(1, rank, 1)\n match qkv_format:\n case QkvFormat.BHSE:\n return t.transpose(0, 1).contiguous()\n case QkvFormat.BSHE:\n return t.permute(1, 0, 3, 2, 4).contiguous().transpose(2, 3)\n\n with FusionDefinition() as fd:\n _definition(fd, qkv_format)\n _multidevice_schedule(fd)\n\n out, q_grad, k_grad, v_grad = fd.execute(\n [\n head_parallelize(q).requires_grad_(),\n head_parallelize(k).requires_grad_(),\n head_parallelize(v).requires_grad_(),\n head_parallelize(out_grad),\n ]\n )\n\n def assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n assert actual.is_contiguous()\n case QkvFormat.BSHE:\n assert actual.transpose(2, 3).is_contiguous()\n\n # Use the default rtol for bfloat16 and a relaxed atol.\n torch.testing.assert_close(actual, expected, rtol=1.6e-2, atol=1e-2)\n\n assert_close(out, head_parallelize(expected_out))\n assert_close(q_grad, head_parallelize(expected_q_grad))\n assert_close(k_grad, head_parallelize(expected_k_grad))\n assert_close(v_grad, head_parallelize(expected_v_grad))\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"qkv_format\", [QkvFormat.BHSE, QkvFormat.BSHE])\n@pytest.mark.mpi\ndef test_sdpa_loop_split(multidevice_test, qkv_format: QkvFormat):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n h, e = 12, 768\n if h % d != 0:\n pytest.skip(f\"We only support even split, so {h} has to be divisible by {d}.\")\n\n def _definition(fd: FusionDefinition, qkv_format: QkvFormat) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n stride_order = [3, 2, 1, 0]\n case QkvFormat.BSHE:\n stride_order = [3, 1, 2, 0]\n\n q, k, v, out_grad = [\n fd.define_tensor(\n shape=[-1, h, -1, e // h],\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n for _ in range(4)\n ]\n\n # TODO(#3123): support sharded dropout and change this to a\n # positive probability.\n dropout_p = fd.define_scalar(0.0, dtype=DataType.Double)\n is_causal = fd.define_scalar(True, dtype=DataType.Bool)\n attn, logsumexp, seed, offset = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal\n )\n\n q_grad, k_grad, v_grad = fd.ops.sdpfa_bwd(\n out_grad,\n q,\n k,\n v,\n attn,\n logsumexp,\n dropout_p,\n is_causal,\n seed,\n offset,\n scale=None,\n )\n\n fd.add_output(attn)\n for grad in [q_grad, k_grad, v_grad]:\n fd.add_output(grad)\n\n def _multidevice_schedule(fd: FusionDefinition) -> None:\n for t in fd.fusion.inputs():\n t.set_device_mesh(mesh)\n t.outer_split(1, d)\n t.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n\n def make_unsharded_tensor() -> torch.Tensor:\n return torch.randn(b, h, s, e // h, dtype=torch.bfloat16, device=\"cpu\")\n\n q, k, v = [make_unsharded_tensor().requires_grad_() for _ in range(3)]\n out_grad = make_unsharded_tensor()\n sharded_q, sharded_k, sharded_v, sharded_out_grad = [\n multidevice_test.shard_tensor_1d(t, 1, mesh) for t in [q, k, v, out_grad]\n ]\n\n with torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n expected_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, dropout_p=0.0, is_causal=True, scale=None\n )\n expected_out.backward(out_grad)\n expected_q_grad, expected_k_grad, expected_v_grad = q.grad, k.grad, v.grad\n\n with FusionDefinition() as fd:\n _definition(fd, qkv_format)\n _multidevice_schedule(fd)\n\n def reformat_tensor(t: torch.Tensor) -> torch.Tensor:\n match qkv_format:\n case QkvFormat.BHSE:\n return t\n case QkvFormat.BSHE:\n return t.transpose(1, 2).contiguous().transpose(1, 2)\n\n attn, q_grad, k_grad, v_grad = fd.execute(\n [\n reformat_tensor(sharded_q).requires_grad_(),\n reformat_tensor(sharded_k).requires_grad_(),\n reformat_tensor(sharded_v).requires_grad_(),\n reformat_tensor(sharded_out_grad),\n ]\n )\n\n def assert_close(actual, expected):\n match qkv_format:\n case QkvFormat.BHSE:\n assert actual.is_contiguous()\n case QkvFormat.BSHE:\n assert actual.transpose(1, 2).is_contiguous()\n\n # Use the default rtol for bfloat16 and a relaxed atol.\n torch.testing.assert_close(\n actual,\n multidevice_test.shard_tensor_1d(expected, 1, mesh),\n rtol=1.6e-2,\n atol=1e-2,\n )\n\n for actual, expected in zip(\n [attn, q_grad, k_grad, v_grad],\n [expected_out, expected_q_grad, expected_k_grad, expected_v_grad],\n ):\n assert_close(actual, expected)\n\n\n@pytest.mark.mpi\ndef test_privatize_squeeze(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1, -1), dtype=DataType.BFloat16)\n tv1 = fd.ops.broadcast(inp_tv, [True, False, False, False])\n tv2 = fd.ops.squeeze(tv1, dims=[0])\n tv3 = fd.ops.cast(tv2, dtype=DataType.Float)\n tv4 = fd.ops.sum(tv3, dims=[0])\n tv5 = fd.ops.sum(tv3, dims=[1])\n fd.add_output(tv4)\n fd.add_output(tv5)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d * 3, 5, 6, dtype=torch.bfloat16)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n\n out1, out2 = fd.execute([inp])\n torch.testing.assert_close(out1.cpu(), inp_ref.to(torch.float).sum(0))\n torch.testing.assert_close(out2, inp.to(torch.float).sum(1))\n\n\n@pytest.mark.mpi\ndef test_inner_reduction(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), dtype=DataType.Float)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.ones(d * 3, 5)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, inp.sum(1))\n\n\n@pytest.mark.mpi\ndef test_insert_resharding_after(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), contiguity=True)\n out = fd.ops.relu(inp_tv)\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out.set_device_mesh(mesh)\n\n inp_ref = torch.randn(d * 3, 5)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), inp_ref.relu())\n\n\n@pytest.mark.mpi\ndef test_welford(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n b, s, e = 1, 2048, 12288\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(shape=[b, s, e], contiguity=True)\n var, mean = fd.ops.var_mean(inp_tv, dims=[2], correction=0, keepdim=False)\n fd.add_output(var)\n fd.add_output(mean)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(b, s, e)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n\n var, mean = fd.execute([inp])\n\n torch.testing.assert_close(var, inp.var(2), rtol=1e-3, atol=1e-3)\n torch.testing.assert_close(mean, inp.mean(2), rtol=1e-3, atol=1e-3)\n\n\n@pytest.mark.mpi\ndef test_binary(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n x_tv = fd.define_tensor((-1, -1), contiguity=True, dtype=DataType.Half)\n y_tv = fd.define_tensor((-1, -1), contiguity=True, dtype=DataType.Half)\n z = fd.ops.add(x_tv, y_tv)\n fd.add_output(z)\n\n x_tv.set_device_mesh(mesh)\n y_tv.set_device_mesh(mesh)\n y_tv.outer_split(0, d)\n y_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n x_ref = torch.randn(d * 2, 3, dtype=torch.float16)\n y_ref = torch.randn(d * 2, 3, dtype=torch.float16)\n z_ref = x_ref.float() + y_ref.float()\n\n x = multidevice_test.shard_tensor(x_ref, x_tv)\n y = multidevice_test.shard_tensor(y_ref, y_tv)\n (z,) = fd.execute([x, y])\n\n torch.testing.assert_close(z, multidevice_test.shard_tensor_1d(z_ref, 0, mesh))\n\n\n@pytest.mark.mpi\ndef test_reduction_with_2d_mesh(multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n\n # Skip if d is not divisible by tp_size\n if d % tp_size != 0:\n pytest.skip(f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\")\n\n dp_size = d // tp_size\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d).reshape(dp_size, tp_size))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1], dtype=DataType.Float, contiguity=True)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, dp_size)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n inp_tv.outer_split(-1, tp_size)\n inp_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n rank = multidevice_test.rank\n rows_per_rank, cols_per_rank = 2, 3\n rows, cols = dp_size * rows_per_rank, tp_size * cols_per_rank\n\n inp_ref = torch.arange(rows * cols, dtype=torch.float).reshape(rows, cols)\n out_ref = inp_ref.sum([-1])\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n\n dp_rank = rank // tp_size\n torch.testing.assert_close(\n out.cpu(), out_ref[dp_rank * rows_per_rank : (dp_rank + 1) * rows_per_rank]\n )","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_sizes_and_ranks","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_sizes_and_ranks#L16-L26","kind":"function","name":"test_sizes_and_ranks","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":16,"end_line":26,"context_start_line":1,"context_end_line":46,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\nfrom enum import Enum, auto\nfrom torch.nn.attention import SDPBackend\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom python.direct_utils import is_pre_ampere\n\n\n@pytest.mark.mpi\ndef test_sizes_and_ranks(multidevice_test):\n size, rank, local_size, local_rank = (\n multidevice_test.size,\n multidevice_test.rank,\n multidevice_test.local_size,\n multidevice_test.local_rank,\n )\n assert size > 0\n assert rank >= 0 and rank < size\n assert local_size > 0\n assert local_rank >= 0 and local_rank < local_size\n\n\n@pytest.mark.mpi\ndef test_pointwise(multidevice_test):\n num_devices = multidevice_test.size\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), contiguity=False, dtype=DataType.Float)\n tv1 = fd.ops.relu(inp_tv)\n tv2 = fd.ops.add(tv1, tv1)\n fd.add_output(tv2)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n for tv in [inp_tv, tv1, tv2]:\n tv.set_device_mesh(mesh)\n\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(num_devices, 4)\n out_ref = inp_ref.relu() * 2","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_pointwise","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_pointwise#L30-L50","kind":"function","name":"test_pointwise","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":30,"end_line":50,"context_start_line":10,"context_end_line":70,"code":"import nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom python.direct_utils import is_pre_ampere\n\n\n@pytest.mark.mpi\ndef test_sizes_and_ranks(multidevice_test):\n size, rank, local_size, local_rank = (\n multidevice_test.size,\n multidevice_test.rank,\n multidevice_test.local_size,\n multidevice_test.local_rank,\n )\n assert size > 0\n assert rank >= 0 and rank < size\n assert local_size > 0\n assert local_rank >= 0 and local_rank < local_size\n\n\n@pytest.mark.mpi\ndef test_pointwise(multidevice_test):\n num_devices = multidevice_test.size\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), contiguity=False, dtype=DataType.Float)\n tv1 = fd.ops.relu(inp_tv)\n tv2 = fd.ops.add(tv1, tv1)\n fd.add_output(tv2)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n for tv in [inp_tv, tv1, tv2]:\n tv.set_device_mesh(mesh)\n\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(num_devices, 4)\n out_ref = inp_ref.relu() * 2\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_pointwise_vectorization(multidevice_test):\n # Repro for https://github.com/NVIDIA/Fuser/issues/5920\n d = multidevice_test.size\n cp_size = 2\n if d % (cp_size * cp_size) != 0:\n pytest.skip(\n f\"We only support even split, so {d=} has to be divisible by {cp_size * cp_size} for {cp_size=}.\"\n )\n dp_size = d // (cp_size * cp_size)\n\n c = 128\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(\n (-1, c, -1, -1, cp_size), contiguity=True, dtype=DataType.BFloat16\n )\n out_tv = fd.ops.set(inp_tv)\n fd.add_output(out_tv)","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_pointwise_vectorization","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_pointwise_vectorization#L54-L109","kind":"function","name":"test_pointwise_vectorization","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":54,"end_line":109,"context_start_line":34,"context_end_line":129,"code":" inp_tv = fd.define_tensor((-1, -1), contiguity=False, dtype=DataType.Float)\n tv1 = fd.ops.relu(inp_tv)\n tv2 = fd.ops.add(tv1, tv1)\n fd.add_output(tv2)\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(num_devices))\n for tv in [inp_tv, tv1, tv2]:\n tv.set_device_mesh(mesh)\n\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(num_devices, 4)\n out_ref = inp_ref.relu() * 2\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), out_ref)\n\n\n@pytest.mark.mpi\ndef test_pointwise_vectorization(multidevice_test):\n # Repro for https://github.com/NVIDIA/Fuser/issues/5920\n d = multidevice_test.size\n cp_size = 2\n if d % (cp_size * cp_size) != 0:\n pytest.skip(\n f\"We only support even split, so {d=} has to be divisible by {cp_size * cp_size} for {cp_size=}.\"\n )\n dp_size = d // (cp_size * cp_size)\n\n c = 128\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(\n (-1, c, -1, -1, cp_size), contiguity=True, dtype=DataType.BFloat16\n )\n out_tv = fd.ops.set(inp_tv)\n fd.add_output(out_tv)\n\n mesh = nvfuser.multidevice.DeviceMesh(\n torch.arange(d).reshape(dp_size, cp_size, cp_size)\n )\n for tv in [inp_tv, out_tv]:\n tv.set_device_mesh(mesh)\n\n inp_tv.axis(4).parallelize(nvfuser.ParallelType.mesh_y)\n inp_tv.outer_split(3, cp_size)\n inp_tv.axis(3).parallelize(nvfuser.ParallelType.mesh_x)\n inp_tv.outer_split(0, dp_size)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_z)\n\n out_tv.axis(4).parallelize(nvfuser.ParallelType.mesh_y)\n out_tv.outer_split(3, cp_size)\n out_tv.axis(3).parallelize(nvfuser.ParallelType.mesh_x)\n out_tv.outer_split(0, dp_size)\n out_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_z)\n out_tv.set_allocation_domain(\n (\n out_tv.axis(3),\n out_tv.axis(0),\n out_tv.axis(1),\n out_tv.axis(2),\n out_tv.axis(4),\n out_tv.axis(5),\n out_tv.axis(6),\n ),\n True,\n )\n\n b = dp_size * 3\n s = cp_size * 5\n inp_ref = torch.randn(b, c, s, s, cp_size, dtype=torch.bfloat16)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\nclass QkvFormat(Enum):\n BHSE = auto()\n BSHE = auto()\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"qkv_format\", [QkvFormat.BHSE, QkvFormat.BSHE])\n@pytest.mark.mpi\ndef test_sdpa(multidevice_test, qkv_format: QkvFormat):\n d, b, s, h, e = multidevice_test.size, 2, 1024, 12, 768\n\n if h % d != 0:\n pytest.skip(f\"We only support even split, so {h} has to be divisible by {d}.\")\n\n def _definition(fd: FusionDefinition, qkv_format: QkvFormat) -> None:","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.QkvFormat","uri":"program://Fuser/class/tests.python.multidevice.test_multidevice.QkvFormat#L112-L114","kind":"class","name":"QkvFormat","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":112,"end_line":114,"context_start_line":92,"context_end_line":134,"code":" out_tv.axis(0),\n out_tv.axis(1),\n out_tv.axis(2),\n out_tv.axis(4),\n out_tv.axis(5),\n out_tv.axis(6),\n ),\n True,\n )\n\n b = dp_size * 3\n s = cp_size * 5\n inp_ref = torch.randn(b, c, s, s, cp_size, dtype=torch.bfloat16)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\nclass QkvFormat(Enum):\n BHSE = auto()\n BSHE = auto()\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"qkv_format\", [QkvFormat.BHSE, QkvFormat.BSHE])\n@pytest.mark.mpi\ndef test_sdpa(multidevice_test, qkv_format: QkvFormat):\n d, b, s, h, e = multidevice_test.size, 2, 1024, 12, 768\n\n if h % d != 0:\n pytest.skip(f\"We only support even split, so {h} has to be divisible by {d}.\")\n\n def _definition(fd: FusionDefinition, qkv_format: QkvFormat) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n stride_order = [4, 3, 2, 1, 0]\n case QkvFormat.BSHE:\n stride_order = [4, 3, 1, 2, 0]","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_sdpa","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_sdpa#L123-L231","kind":"function","name":"test_sdpa","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":123,"end_line":231,"context_start_line":103,"context_end_line":251,"code":" s = cp_size * 5\n inp_ref = torch.randn(b, c, s, s, cp_size, dtype=torch.bfloat16)\n out_ref = inp_ref\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, multidevice_test.shard_tensor(out_ref, out_tv))\n\n\nclass QkvFormat(Enum):\n BHSE = auto()\n BSHE = auto()\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"qkv_format\", [QkvFormat.BHSE, QkvFormat.BSHE])\n@pytest.mark.mpi\ndef test_sdpa(multidevice_test, qkv_format: QkvFormat):\n d, b, s, h, e = multidevice_test.size, 2, 1024, 12, 768\n\n if h % d != 0:\n pytest.skip(f\"We only support even split, so {h} has to be divisible by {d}.\")\n\n def _definition(fd: FusionDefinition, qkv_format: QkvFormat) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n stride_order = [4, 3, 2, 1, 0]\n case QkvFormat.BSHE:\n stride_order = [4, 3, 1, 2, 0]\n\n q, k, v, out_grad = [\n fd.define_tensor(\n shape=[d, b, h // d, s, e // h],\n contiguity=True,\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n for _ in range(4)\n ]\n\n # TODO(#3123): support sharded dropout and change this to a\n # positive probability.\n dropout_p = fd.define_scalar(0.0, dtype=DataType.Double)\n is_causal = fd.define_scalar(True, dtype=DataType.Bool)\n attn, logsumexp, seed, offset = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal\n )\n\n q_grad, k_grad, v_grad = fd.ops.sdpfa_bwd(\n out_grad,\n q,\n k,\n v,\n attn,\n logsumexp,\n dropout_p,\n is_causal,\n seed,\n offset,\n scale=None,\n )\n\n fd.add_output(attn)\n for grad in [q_grad, k_grad, v_grad]:\n fd.add_output(grad)\n\n def _multidevice_schedule(fd: FusionDefinition) -> None:\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n for t in fd.fusion.inputs():\n t.set_device_mesh(mesh)\n t.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n def make_unsharded_tensor() -> torch.Tensor:\n return torch.randn(b, h, s, e // h, dtype=torch.bfloat16, device=\"cuda\")\n\n q, k, v = [make_unsharded_tensor().requires_grad_() for _ in range(3)]\n out_grad = make_unsharded_tensor()\n\n with torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n expected_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, dropout_p=0.0, is_causal=True, scale=None\n )\n expected_out.backward(out_grad)\n expected_q_grad, expected_k_grad, expected_v_grad = q.grad, k.grad, v.grad\n\n rank = multidevice_test.rank\n\n # Head-parallelize Q, K, V or the attention output of an SDPA.\n def head_parallelize(t: torch.Tensor) -> torch.Tensor:\n assert t.shape == torch.Size([b, h, s, e // h])\n # The input `t` may require gradient. We .detach() so the new `t`\n # doesn't require gradient.\n t = t.detach().view([b, d, h // d, s, e // h]).narrow(1, rank, 1)\n match qkv_format:\n case QkvFormat.BHSE:\n return t.transpose(0, 1).contiguous()\n case QkvFormat.BSHE:\n return t.permute(1, 0, 3, 2, 4).contiguous().transpose(2, 3)\n\n with FusionDefinition() as fd:\n _definition(fd, qkv_format)\n _multidevice_schedule(fd)\n\n out, q_grad, k_grad, v_grad = fd.execute(\n [\n head_parallelize(q).requires_grad_(),\n head_parallelize(k).requires_grad_(),\n head_parallelize(v).requires_grad_(),\n head_parallelize(out_grad),\n ]\n )\n\n def assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n assert actual.is_contiguous()\n case QkvFormat.BSHE:\n assert actual.transpose(2, 3).is_contiguous()\n\n # Use the default rtol for bfloat16 and a relaxed atol.\n torch.testing.assert_close(actual, expected, rtol=1.6e-2, atol=1e-2)\n\n assert_close(out, head_parallelize(expected_out))\n assert_close(q_grad, head_parallelize(expected_q_grad))\n assert_close(k_grad, head_parallelize(expected_k_grad))\n assert_close(v_grad, head_parallelize(expected_v_grad))\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"qkv_format\", [QkvFormat.BHSE, QkvFormat.BSHE])\n@pytest.mark.mpi\ndef test_sdpa_loop_split(multidevice_test, qkv_format: QkvFormat):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n h, e = 12, 768\n if h % d != 0:\n pytest.skip(f\"We only support even split, so {h} has to be divisible by {d}.\")\n\n def _definition(fd: FusionDefinition, qkv_format: QkvFormat) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n stride_order = [3, 2, 1, 0]\n case QkvFormat.BSHE:","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_sdpa_loop_split","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_sdpa_loop_split#L240-L352","kind":"function","name":"test_sdpa_loop_split","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":240,"end_line":352,"context_start_line":220,"context_end_line":372,"code":" case QkvFormat.BHSE:\n assert actual.is_contiguous()\n case QkvFormat.BSHE:\n assert actual.transpose(2, 3).is_contiguous()\n\n # Use the default rtol for bfloat16 and a relaxed atol.\n torch.testing.assert_close(actual, expected, rtol=1.6e-2, atol=1e-2)\n\n assert_close(out, head_parallelize(expected_out))\n assert_close(q_grad, head_parallelize(expected_q_grad))\n assert_close(k_grad, head_parallelize(expected_k_grad))\n assert_close(v_grad, head_parallelize(expected_v_grad))\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"qkv_format\", [QkvFormat.BHSE, QkvFormat.BSHE])\n@pytest.mark.mpi\ndef test_sdpa_loop_split(multidevice_test, qkv_format: QkvFormat):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n h, e = 12, 768\n if h % d != 0:\n pytest.skip(f\"We only support even split, so {h} has to be divisible by {d}.\")\n\n def _definition(fd: FusionDefinition, qkv_format: QkvFormat) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n stride_order = [3, 2, 1, 0]\n case QkvFormat.BSHE:\n stride_order = [3, 1, 2, 0]\n\n q, k, v, out_grad = [\n fd.define_tensor(\n shape=[-1, h, -1, e // h],\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n for _ in range(4)\n ]\n\n # TODO(#3123): support sharded dropout and change this to a\n # positive probability.\n dropout_p = fd.define_scalar(0.0, dtype=DataType.Double)\n is_causal = fd.define_scalar(True, dtype=DataType.Bool)\n attn, logsumexp, seed, offset = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal\n )\n\n q_grad, k_grad, v_grad = fd.ops.sdpfa_bwd(\n out_grad,\n q,\n k,\n v,\n attn,\n logsumexp,\n dropout_p,\n is_causal,\n seed,\n offset,\n scale=None,\n )\n\n fd.add_output(attn)\n for grad in [q_grad, k_grad, v_grad]:\n fd.add_output(grad)\n\n def _multidevice_schedule(fd: FusionDefinition) -> None:\n for t in fd.fusion.inputs():\n t.set_device_mesh(mesh)\n t.outer_split(1, d)\n t.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n\n def make_unsharded_tensor() -> torch.Tensor:\n return torch.randn(b, h, s, e // h, dtype=torch.bfloat16, device=\"cpu\")\n\n q, k, v = [make_unsharded_tensor().requires_grad_() for _ in range(3)]\n out_grad = make_unsharded_tensor()\n sharded_q, sharded_k, sharded_v, sharded_out_grad = [\n multidevice_test.shard_tensor_1d(t, 1, mesh) for t in [q, k, v, out_grad]\n ]\n\n with torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n expected_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, dropout_p=0.0, is_causal=True, scale=None\n )\n expected_out.backward(out_grad)\n expected_q_grad, expected_k_grad, expected_v_grad = q.grad, k.grad, v.grad\n\n with FusionDefinition() as fd:\n _definition(fd, qkv_format)\n _multidevice_schedule(fd)\n\n def reformat_tensor(t: torch.Tensor) -> torch.Tensor:\n match qkv_format:\n case QkvFormat.BHSE:\n return t\n case QkvFormat.BSHE:\n return t.transpose(1, 2).contiguous().transpose(1, 2)\n\n attn, q_grad, k_grad, v_grad = fd.execute(\n [\n reformat_tensor(sharded_q).requires_grad_(),\n reformat_tensor(sharded_k).requires_grad_(),\n reformat_tensor(sharded_v).requires_grad_(),\n reformat_tensor(sharded_out_grad),\n ]\n )\n\n def assert_close(actual, expected):\n match qkv_format:\n case QkvFormat.BHSE:\n assert actual.is_contiguous()\n case QkvFormat.BSHE:\n assert actual.transpose(1, 2).is_contiguous()\n\n # Use the default rtol for bfloat16 and a relaxed atol.\n torch.testing.assert_close(\n actual,\n multidevice_test.shard_tensor_1d(expected, 1, mesh),\n rtol=1.6e-2,\n atol=1e-2,\n )\n\n for actual, expected in zip(\n [attn, q_grad, k_grad, v_grad],\n [expected_out, expected_q_grad, expected_k_grad, expected_v_grad],\n ):\n assert_close(actual, expected)\n\n\n@pytest.mark.mpi\ndef test_privatize_squeeze(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1, -1), dtype=DataType.BFloat16)\n tv1 = fd.ops.broadcast(inp_tv, [True, False, False, False])\n tv2 = fd.ops.squeeze(tv1, dims=[0])\n tv3 = fd.ops.cast(tv2, dtype=DataType.Float)\n tv4 = fd.ops.sum(tv3, dims=[0])\n tv5 = fd.ops.sum(tv3, dims=[1])\n fd.add_output(tv4)\n fd.add_output(tv5)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_privatize_squeeze","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_privatize_squeeze#L356-L379","kind":"function","name":"test_privatize_squeeze","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":356,"end_line":379,"context_start_line":336,"context_end_line":399,"code":" assert actual.is_contiguous()\n case QkvFormat.BSHE:\n assert actual.transpose(1, 2).is_contiguous()\n\n # Use the default rtol for bfloat16 and a relaxed atol.\n torch.testing.assert_close(\n actual,\n multidevice_test.shard_tensor_1d(expected, 1, mesh),\n rtol=1.6e-2,\n atol=1e-2,\n )\n\n for actual, expected in zip(\n [attn, q_grad, k_grad, v_grad],\n [expected_out, expected_q_grad, expected_k_grad, expected_v_grad],\n ):\n assert_close(actual, expected)\n\n\n@pytest.mark.mpi\ndef test_privatize_squeeze(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1, -1), dtype=DataType.BFloat16)\n tv1 = fd.ops.broadcast(inp_tv, [True, False, False, False])\n tv2 = fd.ops.squeeze(tv1, dims=[0])\n tv3 = fd.ops.cast(tv2, dtype=DataType.Float)\n tv4 = fd.ops.sum(tv3, dims=[0])\n tv5 = fd.ops.sum(tv3, dims=[1])\n fd.add_output(tv4)\n fd.add_output(tv5)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d * 3, 5, 6, dtype=torch.bfloat16)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n\n out1, out2 = fd.execute([inp])\n torch.testing.assert_close(out1.cpu(), inp_ref.to(torch.float).sum(0))\n torch.testing.assert_close(out2, inp.to(torch.float).sum(1))\n\n\n@pytest.mark.mpi\ndef test_inner_reduction(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), dtype=DataType.Float)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.ones(d * 3, 5)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, inp.sum(1))","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_inner_reduction","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_inner_reduction#L383-L399","kind":"function","name":"test_inner_reduction","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":383,"end_line":399,"context_start_line":363,"context_end_line":419,"code":" tv2 = fd.ops.squeeze(tv1, dims=[0])\n tv3 = fd.ops.cast(tv2, dtype=DataType.Float)\n tv4 = fd.ops.sum(tv3, dims=[0])\n tv5 = fd.ops.sum(tv3, dims=[1])\n fd.add_output(tv4)\n fd.add_output(tv5)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(d * 3, 5, 6, dtype=torch.bfloat16)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n\n out1, out2 = fd.execute([inp])\n torch.testing.assert_close(out1.cpu(), inp_ref.to(torch.float).sum(0))\n torch.testing.assert_close(out2, inp.to(torch.float).sum(1))\n\n\n@pytest.mark.mpi\ndef test_inner_reduction(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), dtype=DataType.Float)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.ones(d * 3, 5)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, inp.sum(1))\n\n\n@pytest.mark.mpi\ndef test_insert_resharding_after(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), contiguity=True)\n out = fd.ops.relu(inp_tv)\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out.set_device_mesh(mesh)\n\n inp_ref = torch.randn(d * 3, 5)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_insert_resharding_after","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_insert_resharding_after#L403-L422","kind":"function","name":"test_insert_resharding_after","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":403,"end_line":422,"context_start_line":383,"context_end_line":442,"code":"def test_inner_reduction(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), dtype=DataType.Float)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.ones(d * 3, 5)\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out, inp.sum(1))\n\n\n@pytest.mark.mpi\ndef test_insert_resharding_after(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), contiguity=True)\n out = fd.ops.relu(inp_tv)\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out.set_device_mesh(mesh)\n\n inp_ref = torch.randn(d * 3, 5)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), inp_ref.relu())\n\n\n@pytest.mark.mpi\ndef test_welford(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n b, s, e = 1, 2048, 12288\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(shape=[b, s, e], contiguity=True)\n var, mean = fd.ops.var_mean(inp_tv, dims=[2], correction=0, keepdim=False)\n fd.add_output(var)\n fd.add_output(mean)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(b, s, e)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_welford","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_welford#L426-L447","kind":"function","name":"test_welford","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":426,"end_line":447,"context_start_line":406,"context_end_line":467,"code":"\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1), contiguity=True)\n out = fd.ops.relu(inp_tv)\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, d)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n out.set_device_mesh(mesh)\n\n inp_ref = torch.randn(d * 3, 5)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n\n (out,) = fd.execute([inp])\n torch.testing.assert_close(out.cpu(), inp_ref.relu())\n\n\n@pytest.mark.mpi\ndef test_welford(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n b, s, e = 1, 2048, 12288\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(shape=[b, s, e], contiguity=True)\n var, mean = fd.ops.var_mean(inp_tv, dims=[2], correction=0, keepdim=False)\n fd.add_output(var)\n fd.add_output(mean)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(b, s, e)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n\n var, mean = fd.execute([inp])\n\n torch.testing.assert_close(var, inp.var(2), rtol=1e-3, atol=1e-3)\n torch.testing.assert_close(mean, inp.mean(2), rtol=1e-3, atol=1e-3)\n\n\n@pytest.mark.mpi\ndef test_binary(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n x_tv = fd.define_tensor((-1, -1), contiguity=True, dtype=DataType.Half)\n y_tv = fd.define_tensor((-1, -1), contiguity=True, dtype=DataType.Half)\n z = fd.ops.add(x_tv, y_tv)\n fd.add_output(z)\n\n x_tv.set_device_mesh(mesh)\n y_tv.set_device_mesh(mesh)\n y_tv.outer_split(0, d)\n y_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n x_ref = torch.randn(d * 2, 3, dtype=torch.float16)\n y_ref = torch.randn(d * 2, 3, dtype=torch.float16)","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_binary","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_binary#L451-L474","kind":"function","name":"test_binary","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":451,"end_line":474,"context_start_line":431,"context_end_line":494,"code":" with FusionDefinition() as fd:\n inp_tv = fd.define_tensor(shape=[b, s, e], contiguity=True)\n var, mean = fd.ops.var_mean(inp_tv, dims=[2], correction=0, keepdim=False)\n fd.add_output(var)\n fd.add_output(mean)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(1, d)\n inp_tv.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n inp_ref = torch.randn(b, s, e)\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n\n var, mean = fd.execute([inp])\n\n torch.testing.assert_close(var, inp.var(2), rtol=1e-3, atol=1e-3)\n torch.testing.assert_close(mean, inp.mean(2), rtol=1e-3, atol=1e-3)\n\n\n@pytest.mark.mpi\ndef test_binary(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n x_tv = fd.define_tensor((-1, -1), contiguity=True, dtype=DataType.Half)\n y_tv = fd.define_tensor((-1, -1), contiguity=True, dtype=DataType.Half)\n z = fd.ops.add(x_tv, y_tv)\n fd.add_output(z)\n\n x_tv.set_device_mesh(mesh)\n y_tv.set_device_mesh(mesh)\n y_tv.outer_split(0, d)\n y_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n x_ref = torch.randn(d * 2, 3, dtype=torch.float16)\n y_ref = torch.randn(d * 2, 3, dtype=torch.float16)\n z_ref = x_ref.float() + y_ref.float()\n\n x = multidevice_test.shard_tensor(x_ref, x_tv)\n y = multidevice_test.shard_tensor(y_ref, y_tv)\n (z,) = fd.execute([x, y])\n\n torch.testing.assert_close(z, multidevice_test.shard_tensor_1d(z_ref, 0, mesh))\n\n\n@pytest.mark.mpi\ndef test_reduction_with_2d_mesh(multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n\n # Skip if d is not divisible by tp_size\n if d % tp_size != 0:\n pytest.skip(f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\")\n\n dp_size = d // tp_size\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d).reshape(dp_size, tp_size))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1], dtype=DataType.Float, contiguity=True)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.test_reduction_with_2d_mesh","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.test_reduction_with_2d_mesh#L478-L514","kind":"function","name":"test_reduction_with_2d_mesh","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":478,"end_line":514,"context_start_line":458,"context_end_line":514,"code":" z = fd.ops.add(x_tv, y_tv)\n fd.add_output(z)\n\n x_tv.set_device_mesh(mesh)\n y_tv.set_device_mesh(mesh)\n y_tv.outer_split(0, d)\n y_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n x_ref = torch.randn(d * 2, 3, dtype=torch.float16)\n y_ref = torch.randn(d * 2, 3, dtype=torch.float16)\n z_ref = x_ref.float() + y_ref.float()\n\n x = multidevice_test.shard_tensor(x_ref, x_tv)\n y = multidevice_test.shard_tensor(y_ref, y_tv)\n (z,) = fd.execute([x, y])\n\n torch.testing.assert_close(z, multidevice_test.shard_tensor_1d(z_ref, 0, mesh))\n\n\n@pytest.mark.mpi\ndef test_reduction_with_2d_mesh(multidevice_test):\n d = multidevice_test.size\n tp_size = 2\n\n # Skip if d is not divisible by tp_size\n if d % tp_size != 0:\n pytest.skip(f\"Number of devices ({d}) must be divisible by tp_size ({tp_size})\")\n\n dp_size = d // tp_size\n\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d).reshape(dp_size, tp_size))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor([-1, -1], dtype=DataType.Float, contiguity=True)\n out = fd.ops.sum(inp_tv, [1])\n fd.add_output(out)\n\n inp_tv.set_device_mesh(mesh)\n inp_tv.outer_split(0, dp_size)\n inp_tv.axis(0).parallelize(nvfuser.ParallelType.mesh_y)\n inp_tv.outer_split(-1, tp_size)\n inp_tv.axis(-2).parallelize(nvfuser.ParallelType.mesh_x)\n\n rank = multidevice_test.rank\n rows_per_rank, cols_per_rank = 2, 3\n rows, cols = dp_size * rows_per_rank, tp_size * cols_per_rank\n\n inp_ref = torch.arange(rows * cols, dtype=torch.float).reshape(rows, cols)\n out_ref = inp_ref.sum([-1])\n\n inp = multidevice_test.shard_tensor(inp_ref, inp_tv)\n (out,) = fd.execute([inp])\n\n dp_rank = rank // tp_size\n torch.testing.assert_close(\n out.cpu(), out_ref[dp_rank * rows_per_rank : (dp_rank + 1) * rows_per_rank]\n )","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice._definition","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice._definition#L247-L287","kind":"function","name":"_definition","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":247,"end_line":287,"context_start_line":227,"context_end_line":307,"code":"\n assert_close(out, head_parallelize(expected_out))\n assert_close(q_grad, head_parallelize(expected_q_grad))\n assert_close(k_grad, head_parallelize(expected_k_grad))\n assert_close(v_grad, head_parallelize(expected_v_grad))\n\n\n@pytest.mark.skipif(\n is_pre_ampere(),\n reason=\"Flash Attention is only supported on Ampere and newer devices.\",\n)\n@pytest.mark.parametrize(\"qkv_format\", [QkvFormat.BHSE, QkvFormat.BSHE])\n@pytest.mark.mpi\ndef test_sdpa_loop_split(multidevice_test, qkv_format: QkvFormat):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n h, e = 12, 768\n if h % d != 0:\n pytest.skip(f\"We only support even split, so {h} has to be divisible by {d}.\")\n\n def _definition(fd: FusionDefinition, qkv_format: QkvFormat) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n stride_order = [3, 2, 1, 0]\n case QkvFormat.BSHE:\n stride_order = [3, 1, 2, 0]\n\n q, k, v, out_grad = [\n fd.define_tensor(\n shape=[-1, h, -1, e // h],\n dtype=DataType.BFloat16,\n stride_order=stride_order,\n )\n for _ in range(4)\n ]\n\n # TODO(#3123): support sharded dropout and change this to a\n # positive probability.\n dropout_p = fd.define_scalar(0.0, dtype=DataType.Double)\n is_causal = fd.define_scalar(True, dtype=DataType.Bool)\n attn, logsumexp, seed, offset = fd.ops.sdpfa_fwd(\n q, k, v, dropout_p=dropout_p, is_causal=is_causal\n )\n\n q_grad, k_grad, v_grad = fd.ops.sdpfa_bwd(\n out_grad,\n q,\n k,\n v,\n attn,\n logsumexp,\n dropout_p,\n is_causal,\n seed,\n offset,\n scale=None,\n )\n\n fd.add_output(attn)\n for grad in [q_grad, k_grad, v_grad]:\n fd.add_output(grad)\n\n def _multidevice_schedule(fd: FusionDefinition) -> None:\n for t in fd.fusion.inputs():\n t.set_device_mesh(mesh)\n t.outer_split(1, d)\n t.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n\n def make_unsharded_tensor() -> torch.Tensor:\n return torch.randn(b, h, s, e // h, dtype=torch.bfloat16, device=\"cpu\")\n\n q, k, v = [make_unsharded_tensor().requires_grad_() for _ in range(3)]\n out_grad = make_unsharded_tensor()\n sharded_q, sharded_k, sharded_v, sharded_out_grad = [\n multidevice_test.shard_tensor_1d(t, 1, mesh) for t in [q, k, v, out_grad]\n ]\n\n with torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n expected_out = torch.nn.functional.scaled_dot_product_attention(","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice._multidevice_schedule","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice._multidevice_schedule#L289-L293","kind":"function","name":"_multidevice_schedule","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":289,"end_line":293,"context_start_line":269,"context_end_line":313,"code":" )\n\n q_grad, k_grad, v_grad = fd.ops.sdpfa_bwd(\n out_grad,\n q,\n k,\n v,\n attn,\n logsumexp,\n dropout_p,\n is_causal,\n seed,\n offset,\n scale=None,\n )\n\n fd.add_output(attn)\n for grad in [q_grad, k_grad, v_grad]:\n fd.add_output(grad)\n\n def _multidevice_schedule(fd: FusionDefinition) -> None:\n for t in fd.fusion.inputs():\n t.set_device_mesh(mesh)\n t.outer_split(1, d)\n t.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n\n def make_unsharded_tensor() -> torch.Tensor:\n return torch.randn(b, h, s, e // h, dtype=torch.bfloat16, device=\"cpu\")\n\n q, k, v = [make_unsharded_tensor().requires_grad_() for _ in range(3)]\n out_grad = make_unsharded_tensor()\n sharded_q, sharded_k, sharded_v, sharded_out_grad = [\n multidevice_test.shard_tensor_1d(t, 1, mesh) for t in [q, k, v, out_grad]\n ]\n\n with torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n expected_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, dropout_p=0.0, is_causal=True, scale=None\n )\n expected_out.backward(out_grad)\n expected_q_grad, expected_k_grad, expected_v_grad = q.grad, k.grad, v.grad\n\n with FusionDefinition() as fd:","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.make_unsharded_tensor","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.make_unsharded_tensor#L297-L298","kind":"function","name":"make_unsharded_tensor","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":297,"end_line":298,"context_start_line":277,"context_end_line":318,"code":" logsumexp,\n dropout_p,\n is_causal,\n seed,\n offset,\n scale=None,\n )\n\n fd.add_output(attn)\n for grad in [q_grad, k_grad, v_grad]:\n fd.add_output(grad)\n\n def _multidevice_schedule(fd: FusionDefinition) -> None:\n for t in fd.fusion.inputs():\n t.set_device_mesh(mesh)\n t.outer_split(1, d)\n t.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n\n b, s = 2, 1024\n\n def make_unsharded_tensor() -> torch.Tensor:\n return torch.randn(b, h, s, e // h, dtype=torch.bfloat16, device=\"cpu\")\n\n q, k, v = [make_unsharded_tensor().requires_grad_() for _ in range(3)]\n out_grad = make_unsharded_tensor()\n sharded_q, sharded_k, sharded_v, sharded_out_grad = [\n multidevice_test.shard_tensor_1d(t, 1, mesh) for t in [q, k, v, out_grad]\n ]\n\n with torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n expected_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, dropout_p=0.0, is_causal=True, scale=None\n )\n expected_out.backward(out_grad)\n expected_q_grad, expected_k_grad, expected_v_grad = q.grad, k.grad, v.grad\n\n with FusionDefinition() as fd:\n _definition(fd, qkv_format)\n _multidevice_schedule(fd)\n\n def reformat_tensor(t: torch.Tensor) -> torch.Tensor:\n match qkv_format:","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.head_parallelize","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.head_parallelize#L194-L203","kind":"function","name":"head_parallelize","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":194,"end_line":203,"context_start_line":174,"context_end_line":223,"code":" for t in fd.fusion.inputs():\n t.set_device_mesh(mesh)\n t.axis(0).parallelize(nvfuser.ParallelType.mesh_x)\n\n def make_unsharded_tensor() -> torch.Tensor:\n return torch.randn(b, h, s, e // h, dtype=torch.bfloat16, device=\"cuda\")\n\n q, k, v = [make_unsharded_tensor().requires_grad_() for _ in range(3)]\n out_grad = make_unsharded_tensor()\n\n with torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n expected_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, dropout_p=0.0, is_causal=True, scale=None\n )\n expected_out.backward(out_grad)\n expected_q_grad, expected_k_grad, expected_v_grad = q.grad, k.grad, v.grad\n\n rank = multidevice_test.rank\n\n # Head-parallelize Q, K, V or the attention output of an SDPA.\n def head_parallelize(t: torch.Tensor) -> torch.Tensor:\n assert t.shape == torch.Size([b, h, s, e // h])\n # The input `t` may require gradient. We .detach() so the new `t`\n # doesn't require gradient.\n t = t.detach().view([b, d, h // d, s, e // h]).narrow(1, rank, 1)\n match qkv_format:\n case QkvFormat.BHSE:\n return t.transpose(0, 1).contiguous()\n case QkvFormat.BSHE:\n return t.permute(1, 0, 3, 2, 4).contiguous().transpose(2, 3)\n\n with FusionDefinition() as fd:\n _definition(fd, qkv_format)\n _multidevice_schedule(fd)\n\n out, q_grad, k_grad, v_grad = fd.execute(\n [\n head_parallelize(q).requires_grad_(),\n head_parallelize(k).requires_grad_(),\n head_parallelize(v).requires_grad_(),\n head_parallelize(out_grad),\n ]\n )\n\n def assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None:\n match qkv_format:\n case QkvFormat.BHSE:\n assert actual.is_contiguous()\n case QkvFormat.BSHE:\n assert actual.transpose(2, 3).is_contiguous()","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.assert_close","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.assert_close#L333-L346","kind":"function","name":"assert_close","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":333,"end_line":346,"context_start_line":313,"context_end_line":366,"code":" with FusionDefinition() as fd:\n _definition(fd, qkv_format)\n _multidevice_schedule(fd)\n\n def reformat_tensor(t: torch.Tensor) -> torch.Tensor:\n match qkv_format:\n case QkvFormat.BHSE:\n return t\n case QkvFormat.BSHE:\n return t.transpose(1, 2).contiguous().transpose(1, 2)\n\n attn, q_grad, k_grad, v_grad = fd.execute(\n [\n reformat_tensor(sharded_q).requires_grad_(),\n reformat_tensor(sharded_k).requires_grad_(),\n reformat_tensor(sharded_v).requires_grad_(),\n reformat_tensor(sharded_out_grad),\n ]\n )\n\n def assert_close(actual, expected):\n match qkv_format:\n case QkvFormat.BHSE:\n assert actual.is_contiguous()\n case QkvFormat.BSHE:\n assert actual.transpose(1, 2).is_contiguous()\n\n # Use the default rtol for bfloat16 and a relaxed atol.\n torch.testing.assert_close(\n actual,\n multidevice_test.shard_tensor_1d(expected, 1, mesh),\n rtol=1.6e-2,\n atol=1e-2,\n )\n\n for actual, expected in zip(\n [attn, q_grad, k_grad, v_grad],\n [expected_out, expected_q_grad, expected_k_grad, expected_v_grad],\n ):\n assert_close(actual, expected)\n\n\n@pytest.mark.mpi\ndef test_privatize_squeeze(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((-1, -1, -1), dtype=DataType.BFloat16)\n tv1 = fd.ops.broadcast(inp_tv, [True, False, False, False])\n tv2 = fd.ops.squeeze(tv1, dims=[0])\n tv3 = fd.ops.cast(tv2, dtype=DataType.Float)\n tv4 = fd.ops.sum(tv3, dims=[0])\n tv5 = fd.ops.sum(tv3, dims=[1])","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.multidevice.test_multidevice.reformat_tensor","uri":"program://Fuser/function/tests.python.multidevice.test_multidevice.reformat_tensor#L317-L322","kind":"function","name":"reformat_tensor","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":317,"end_line":322,"context_start_line":297,"context_end_line":342,"code":" def make_unsharded_tensor() -> torch.Tensor:\n return torch.randn(b, h, s, e // h, dtype=torch.bfloat16, device=\"cpu\")\n\n q, k, v = [make_unsharded_tensor().requires_grad_() for _ in range(3)]\n out_grad = make_unsharded_tensor()\n sharded_q, sharded_k, sharded_v, sharded_out_grad = [\n multidevice_test.shard_tensor_1d(t, 1, mesh) for t in [q, k, v, out_grad]\n ]\n\n with torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n expected_out = torch.nn.functional.scaled_dot_product_attention(\n q, k, v, dropout_p=0.0, is_causal=True, scale=None\n )\n expected_out.backward(out_grad)\n expected_q_grad, expected_k_grad, expected_v_grad = q.grad, k.grad, v.grad\n\n with FusionDefinition() as fd:\n _definition(fd, qkv_format)\n _multidevice_schedule(fd)\n\n def reformat_tensor(t: torch.Tensor) -> torch.Tensor:\n match qkv_format:\n case QkvFormat.BHSE:\n return t\n case QkvFormat.BSHE:\n return t.transpose(1, 2).contiguous().transpose(1, 2)\n\n attn, q_grad, k_grad, v_grad = fd.execute(\n [\n reformat_tensor(sharded_q).requires_grad_(),\n reformat_tensor(sharded_k).requires_grad_(),\n reformat_tensor(sharded_v).requires_grad_(),\n reformat_tensor(sharded_out_grad),\n ]\n )\n\n def assert_close(actual, expected):\n match qkv_format:\n case QkvFormat.BHSE:\n assert actual.is_contiguous()\n case QkvFormat.BSHE:\n assert actual.transpose(1, 2).is_contiguous()\n\n # Use the default rtol for bfloat16 and a relaxed atol.\n torch.testing.assert_close(\n actual,","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision","uri":"program://Fuser/module/tests.python.direct_utils.narrow_precision#L1-L181","kind":"module","name":"tests.python.direct_utils.narrow_precision","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":1,"end_line":181,"context_start_line":1,"context_end_line":181,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\n\nFLOAT4_E2M1_MAX = 6.0\nFLOAT8_E4M3_EPS = torch.finfo(torch.float8_e4m3fn).tiny\nFLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n\n\n# restore swizzled on block scaling factor:\n# 1. restore swizzle\n# 2. removes padding via slicing to [:mn, :k]\ndef swizzled_to_linear_128_4(a_sf_swizzled: torch.Tensor, mn, k):\n mn_padded, sf_k_padded = a_sf_swizzled.shape\n m_tiles = mn_padded // 128\n k_tiles = sf_k_padded // 4\n tmp = torch.reshape(a_sf_swizzled, (m_tiles, k_tiles, 32, 4, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, sf_k_padded)[:mn, :k]\n\n\n# apply swizzled on block scaling factor:\n# 1. apply padding to [mn_t * 128 , k_t * 4]\n# 2. apply swizzle\ndef linear_to_swizzled_128_4(a_sf_linear: torch.Tensor):\n mn, sf_k = a_sf_linear.shape\n m_tiles = (mn + 128 - 1) // 128\n mn_padded = m_tiles * 128\n k_tiles = (sf_k + 4 - 1) // 4\n k_padded = k_tiles * 4\n if mn_padded != mn or k_padded != sf_k:\n a_sf_padded = torch.empty(\n mn_padded, k_padded, dtype=a_sf_linear.dtype, device=a_sf_linear.device\n )\n a_sf_padded[0:mn, 0:sf_k] = a_sf_linear\n else:\n a_sf_padded = a_sf_linear\n # details about layout requirement on block-wise scaling factor\n # https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#scale-factor-layouts\n tmp = torch.reshape(a_sf_padded, (m_tiles, 4, 32, k_tiles, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, k_padded)\n\n\ndef unpack_fp4(x: torch.Tensor) -> torch.Tensor:\n repeated = x.repeat_interleave(2, dim=1)\n repeated[:, 0::2] &= 0x0F\n repeated[:, 1::2] >>= 4\n return repeated\n\n\n_FP4_LUT = torch.tensor(\n [\n 0.0, # 0: 0000 - zero\n 0.5, # 1: 0001 - smallest positive normal\n 1.0, # 2: 0010\n 1.5, # 3: 0011\n 2.0, # 4: 0100\n 3.0, # 5: 0101\n 4.0, # 6: 0110\n 6.0, # 7: 0111 - largest positive normal\n -0.0, # 8: 1000 - negative zero\n -0.5, # 9: 1001 - smallest negative normal\n -1.0, # 10: 1010\n -1.5, # 11: 1011\n -2.0, # 12: 1100\n -3.0, # 13: 1101\n -4.0, # 14: 1110\n -6.0, # 15: 1111 - largest negative normal\n ],\n dtype=torch.float32,\n)\n\n\ndef fp4_to_fp32(fp4: torch.Tensor) -> torch.Tensor:\n # Convert FP4 indices to their corresponding floating point values\n # Each index (0-15) represents a 4-bit FP4 value in E2M1 format\n # Values based on the FP4 E2M1 specification\n fp4_lut = _FP4_LUT.to(fp4.device)\n return fp4_lut[fp4.to(torch.long)]\n\n\ndef dequantize_fp4(\n qx: torch.Tensor, sx: torch.Tensor, amax: torch.Tensor\n) -> torch.Tensor:\n sf = sx.repeat_interleave(16, dim=1).view(torch.float8_e4m3fn).to(torch.float32)\n dqx = fp4_to_fp32(unpack_fp4(qx))\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf * (amax / (6.0 * 448))\n return dequant\n\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This is from pytorch nvfp4 gemm tests.\ndef to_fp4(x):\n def down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n def pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n from torch.testing._internal.common_quantized import _f32_to_floatx_unpacked\n\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\ndef pytorch_nvfp4_quantize(a, a_global_scale):\n BLOCK_SIZE = 16\n assert (\n a.size(-1) % BLOCK_SIZE == 0\n ), \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n\n # Find absolute maximum along blockwise dimension\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n block_scale_fp32 = (max_abs / FLOAT4_E2M1_MAX).float()\n\n scaled_block_scale_fp32 = block_scale_fp32 * a_global_scale\n scaled_block_scale_fp32 = torch.clamp(\n scaled_block_scale_fp32, min=FLOAT8_E4M3_EPS, max=FLOAT8_E4M3_MAX\n )\n scaled_block_scale_fp8 = scaled_block_scale_fp32.to(torch.float8_e4m3fn)\n total_scale = scaled_block_scale_fp32 / a_global_scale\n a_scaled = a_fp32 / total_scale.unsqueeze(-1)\n a_scaled = torch.clamp(a_scaled, -FLOAT4_E2M1_MAX, FLOAT4_E2M1_MAX)\n a_scaled = a_scaled.view(original_shape)\n return to_fp4(a_scaled), scaled_block_scale_fp8\n\n\ndef round_up(x, y):\n return (x + y - 1) // y * y\n\n\ndef activation_scale_to_nvfp4(x, g_sf, offsets, blockscale_offsets, block_size):\n m = x.size(0)\n k = x.size(1)\n g = g_sf.size(0)\n padded_m_size = blockscale_offsets[g - 1] + round_up(m - offsets[g - 1], 128)\n block_scale = torch.empty(\n (padded_m_size, k // block_size), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n v_scaled = torch.empty((m, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\")\n for i in range(len(g_sf)):\n l = offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n l_sf = blockscale_offsets[i]\n r_sf = l_sf + (r - l + 127) // 128 * 128\n v, b_sf = pytorch_nvfp4_quantize(x[l:r], g_sf[i])\n v_scaled[l:r] = v\n block_scale[l_sf:r_sf] = linear_to_swizzled_128_4(b_sf)\n\n return v_scaled, block_scale","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.swizzled_to_linear_128_4","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.swizzled_to_linear_128_4#L16-L21","kind":"function","name":"swizzled_to_linear_128_4","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":16,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\n\nFLOAT4_E2M1_MAX = 6.0\nFLOAT8_E4M3_EPS = torch.finfo(torch.float8_e4m3fn).tiny\nFLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n\n\n# restore swizzled on block scaling factor:\n# 1. restore swizzle\n# 2. removes padding via slicing to [:mn, :k]\ndef swizzled_to_linear_128_4(a_sf_swizzled: torch.Tensor, mn, k):\n mn_padded, sf_k_padded = a_sf_swizzled.shape\n m_tiles = mn_padded // 128\n k_tiles = sf_k_padded // 4\n tmp = torch.reshape(a_sf_swizzled, (m_tiles, k_tiles, 32, 4, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, sf_k_padded)[:mn, :k]\n\n\n# apply swizzled on block scaling factor:\n# 1. apply padding to [mn_t * 128 , k_t * 4]\n# 2. apply swizzle\ndef linear_to_swizzled_128_4(a_sf_linear: torch.Tensor):\n mn, sf_k = a_sf_linear.shape\n m_tiles = (mn + 128 - 1) // 128\n mn_padded = m_tiles * 128\n k_tiles = (sf_k + 4 - 1) // 4\n k_padded = k_tiles * 4\n if mn_padded != mn or k_padded != sf_k:\n a_sf_padded = torch.empty(\n mn_padded, k_padded, dtype=a_sf_linear.dtype, device=a_sf_linear.device\n )\n a_sf_padded[0:mn, 0:sf_k] = a_sf_linear\n else:\n a_sf_padded = a_sf_linear\n # details about layout requirement on block-wise scaling factor\n # https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#scale-factor-layouts","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.linear_to_swizzled_128_4","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.linear_to_swizzled_128_4#L27-L43","kind":"function","name":"linear_to_swizzled_128_4","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":27,"end_line":43,"context_start_line":7,"context_end_line":63,"code":"\nFLOAT4_E2M1_MAX = 6.0\nFLOAT8_E4M3_EPS = torch.finfo(torch.float8_e4m3fn).tiny\nFLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n\n\n# restore swizzled on block scaling factor:\n# 1. restore swizzle\n# 2. removes padding via slicing to [:mn, :k]\ndef swizzled_to_linear_128_4(a_sf_swizzled: torch.Tensor, mn, k):\n mn_padded, sf_k_padded = a_sf_swizzled.shape\n m_tiles = mn_padded // 128\n k_tiles = sf_k_padded // 4\n tmp = torch.reshape(a_sf_swizzled, (m_tiles, k_tiles, 32, 4, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, sf_k_padded)[:mn, :k]\n\n\n# apply swizzled on block scaling factor:\n# 1. apply padding to [mn_t * 128 , k_t * 4]\n# 2. apply swizzle\ndef linear_to_swizzled_128_4(a_sf_linear: torch.Tensor):\n mn, sf_k = a_sf_linear.shape\n m_tiles = (mn + 128 - 1) // 128\n mn_padded = m_tiles * 128\n k_tiles = (sf_k + 4 - 1) // 4\n k_padded = k_tiles * 4\n if mn_padded != mn or k_padded != sf_k:\n a_sf_padded = torch.empty(\n mn_padded, k_padded, dtype=a_sf_linear.dtype, device=a_sf_linear.device\n )\n a_sf_padded[0:mn, 0:sf_k] = a_sf_linear\n else:\n a_sf_padded = a_sf_linear\n # details about layout requirement on block-wise scaling factor\n # https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#scale-factor-layouts\n tmp = torch.reshape(a_sf_padded, (m_tiles, 4, 32, k_tiles, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, k_padded)\n\n\ndef unpack_fp4(x: torch.Tensor) -> torch.Tensor:\n repeated = x.repeat_interleave(2, dim=1)\n repeated[:, 0::2] &= 0x0F\n repeated[:, 1::2] >>= 4\n return repeated\n\n\n_FP4_LUT = torch.tensor(\n [\n 0.0, # 0: 0000 - zero\n 0.5, # 1: 0001 - smallest positive normal\n 1.0, # 2: 0010\n 1.5, # 3: 0011\n 2.0, # 4: 0100\n 3.0, # 5: 0101\n 4.0, # 6: 0110\n 6.0, # 7: 0111 - largest positive normal\n -0.0, # 8: 1000 - negative zero","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.unpack_fp4","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.unpack_fp4#L46-L50","kind":"function","name":"unpack_fp4","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":46,"end_line":50,"context_start_line":26,"context_end_line":70,"code":"# 2. apply swizzle\ndef linear_to_swizzled_128_4(a_sf_linear: torch.Tensor):\n mn, sf_k = a_sf_linear.shape\n m_tiles = (mn + 128 - 1) // 128\n mn_padded = m_tiles * 128\n k_tiles = (sf_k + 4 - 1) // 4\n k_padded = k_tiles * 4\n if mn_padded != mn or k_padded != sf_k:\n a_sf_padded = torch.empty(\n mn_padded, k_padded, dtype=a_sf_linear.dtype, device=a_sf_linear.device\n )\n a_sf_padded[0:mn, 0:sf_k] = a_sf_linear\n else:\n a_sf_padded = a_sf_linear\n # details about layout requirement on block-wise scaling factor\n # https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#scale-factor-layouts\n tmp = torch.reshape(a_sf_padded, (m_tiles, 4, 32, k_tiles, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, k_padded)\n\n\ndef unpack_fp4(x: torch.Tensor) -> torch.Tensor:\n repeated = x.repeat_interleave(2, dim=1)\n repeated[:, 0::2] &= 0x0F\n repeated[:, 1::2] >>= 4\n return repeated\n\n\n_FP4_LUT = torch.tensor(\n [\n 0.0, # 0: 0000 - zero\n 0.5, # 1: 0001 - smallest positive normal\n 1.0, # 2: 0010\n 1.5, # 3: 0011\n 2.0, # 4: 0100\n 3.0, # 5: 0101\n 4.0, # 6: 0110\n 6.0, # 7: 0111 - largest positive normal\n -0.0, # 8: 1000 - negative zero\n -0.5, # 9: 1001 - smallest negative normal\n -1.0, # 10: 1010\n -1.5, # 11: 1011\n -2.0, # 12: 1100\n -3.0, # 13: 1101\n -4.0, # 14: 1110\n -6.0, # 15: 1111 - largest negative normal","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.fp4_to_fp32","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.fp4_to_fp32#L76-L81","kind":"function","name":"fp4_to_fp32","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":76,"end_line":81,"context_start_line":56,"context_end_line":101,"code":" 0.5, # 1: 0001 - smallest positive normal\n 1.0, # 2: 0010\n 1.5, # 3: 0011\n 2.0, # 4: 0100\n 3.0, # 5: 0101\n 4.0, # 6: 0110\n 6.0, # 7: 0111 - largest positive normal\n -0.0, # 8: 1000 - negative zero\n -0.5, # 9: 1001 - smallest negative normal\n -1.0, # 10: 1010\n -1.5, # 11: 1011\n -2.0, # 12: 1100\n -3.0, # 13: 1101\n -4.0, # 14: 1110\n -6.0, # 15: 1111 - largest negative normal\n ],\n dtype=torch.float32,\n)\n\n\ndef fp4_to_fp32(fp4: torch.Tensor) -> torch.Tensor:\n # Convert FP4 indices to their corresponding floating point values\n # Each index (0-15) represents a 4-bit FP4 value in E2M1 format\n # Values based on the FP4 E2M1 specification\n fp4_lut = _FP4_LUT.to(fp4.device)\n return fp4_lut[fp4.to(torch.long)]\n\n\ndef dequantize_fp4(\n qx: torch.Tensor, sx: torch.Tensor, amax: torch.Tensor\n) -> torch.Tensor:\n sf = sx.repeat_interleave(16, dim=1).view(torch.float8_e4m3fn).to(torch.float32)\n dqx = fp4_to_fp32(unpack_fp4(qx))\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf * (amax / (6.0 * 448))\n return dequant\n\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.dequantize_fp4","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.dequantize_fp4#L84-L91","kind":"function","name":"dequantize_fp4","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":84,"end_line":91,"context_start_line":64,"context_end_line":111,"code":" -0.5, # 9: 1001 - smallest negative normal\n -1.0, # 10: 1010\n -1.5, # 11: 1011\n -2.0, # 12: 1100\n -3.0, # 13: 1101\n -4.0, # 14: 1110\n -6.0, # 15: 1111 - largest negative normal\n ],\n dtype=torch.float32,\n)\n\n\ndef fp4_to_fp32(fp4: torch.Tensor) -> torch.Tensor:\n # Convert FP4 indices to their corresponding floating point values\n # Each index (0-15) represents a 4-bit FP4 value in E2M1 format\n # Values based on the FP4 E2M1 specification\n fp4_lut = _FP4_LUT.to(fp4.device)\n return fp4_lut[fp4.to(torch.long)]\n\n\ndef dequantize_fp4(\n qx: torch.Tensor, sx: torch.Tensor, amax: torch.Tensor\n) -> torch.Tensor:\n sf = sx.repeat_interleave(16, dim=1).view(torch.float8_e4m3fn).to(torch.float32)\n dqx = fp4_to_fp32(unpack_fp4(qx))\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf * (amax / (6.0 * 448))\n return dequant\n\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This is from pytorch nvfp4 gemm tests.\ndef to_fp4(x):\n def down_size(size):","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.dequantize_to_dtype","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.dequantize_to_dtype#L94-L106","kind":"function","name":"dequantize_to_dtype","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":94,"end_line":106,"context_start_line":74,"context_end_line":126,"code":"\n\ndef fp4_to_fp32(fp4: torch.Tensor) -> torch.Tensor:\n # Convert FP4 indices to their corresponding floating point values\n # Each index (0-15) represents a 4-bit FP4 value in E2M1 format\n # Values based on the FP4 E2M1 specification\n fp4_lut = _FP4_LUT.to(fp4.device)\n return fp4_lut[fp4.to(torch.long)]\n\n\ndef dequantize_fp4(\n qx: torch.Tensor, sx: torch.Tensor, amax: torch.Tensor\n) -> torch.Tensor:\n sf = sx.repeat_interleave(16, dim=1).view(torch.float8_e4m3fn).to(torch.float32)\n dqx = fp4_to_fp32(unpack_fp4(qx))\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf * (amax / (6.0 * 448))\n return dequant\n\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This is from pytorch nvfp4 gemm tests.\ndef to_fp4(x):\n def down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n def pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n from torch.testing._internal.common_quantized import _f32_to_floatx_unpacked\n\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.to_fp4","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.to_fp4#L110-L127","kind":"function","name":"to_fp4","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":110,"end_line":127,"context_start_line":90,"context_end_line":147,"code":" dequant = dqx * sf * (amax / (6.0 * 448))\n return dequant\n\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This is from pytorch nvfp4 gemm tests.\ndef to_fp4(x):\n def down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n def pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n from torch.testing._internal.common_quantized import _f32_to_floatx_unpacked\n\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\ndef pytorch_nvfp4_quantize(a, a_global_scale):\n BLOCK_SIZE = 16\n assert (\n a.size(-1) % BLOCK_SIZE == 0\n ), \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n\n # Find absolute maximum along blockwise dimension\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n block_scale_fp32 = (max_abs / FLOAT4_E2M1_MAX).float()\n\n scaled_block_scale_fp32 = block_scale_fp32 * a_global_scale\n scaled_block_scale_fp32 = torch.clamp(\n scaled_block_scale_fp32, min=FLOAT8_E4M3_EPS, max=FLOAT8_E4M3_MAX\n )","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.pytorch_nvfp4_quantize","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.pytorch_nvfp4_quantize#L130-L153","kind":"function","name":"pytorch_nvfp4_quantize","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":130,"end_line":153,"context_start_line":110,"context_end_line":173,"code":"def to_fp4(x):\n def down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n def pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n from torch.testing._internal.common_quantized import _f32_to_floatx_unpacked\n\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\ndef pytorch_nvfp4_quantize(a, a_global_scale):\n BLOCK_SIZE = 16\n assert (\n a.size(-1) % BLOCK_SIZE == 0\n ), \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n\n # Find absolute maximum along blockwise dimension\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n block_scale_fp32 = (max_abs / FLOAT4_E2M1_MAX).float()\n\n scaled_block_scale_fp32 = block_scale_fp32 * a_global_scale\n scaled_block_scale_fp32 = torch.clamp(\n scaled_block_scale_fp32, min=FLOAT8_E4M3_EPS, max=FLOAT8_E4M3_MAX\n )\n scaled_block_scale_fp8 = scaled_block_scale_fp32.to(torch.float8_e4m3fn)\n total_scale = scaled_block_scale_fp32 / a_global_scale\n a_scaled = a_fp32 / total_scale.unsqueeze(-1)\n a_scaled = torch.clamp(a_scaled, -FLOAT4_E2M1_MAX, FLOAT4_E2M1_MAX)\n a_scaled = a_scaled.view(original_shape)\n return to_fp4(a_scaled), scaled_block_scale_fp8\n\n\ndef round_up(x, y):\n return (x + y - 1) // y * y\n\n\ndef activation_scale_to_nvfp4(x, g_sf, offsets, blockscale_offsets, block_size):\n m = x.size(0)\n k = x.size(1)\n g = g_sf.size(0)\n padded_m_size = blockscale_offsets[g - 1] + round_up(m - offsets[g - 1], 128)\n block_scale = torch.empty(\n (padded_m_size, k // block_size), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n v_scaled = torch.empty((m, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\")\n for i in range(len(g_sf)):\n l = offsets[i]\n if i == g - 1:\n r = m\n else:","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.round_up","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.round_up#L156-L157","kind":"function","name":"round_up","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":156,"end_line":157,"context_start_line":136,"context_end_line":177,"code":"\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n\n # Find absolute maximum along blockwise dimension\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n block_scale_fp32 = (max_abs / FLOAT4_E2M1_MAX).float()\n\n scaled_block_scale_fp32 = block_scale_fp32 * a_global_scale\n scaled_block_scale_fp32 = torch.clamp(\n scaled_block_scale_fp32, min=FLOAT8_E4M3_EPS, max=FLOAT8_E4M3_MAX\n )\n scaled_block_scale_fp8 = scaled_block_scale_fp32.to(torch.float8_e4m3fn)\n total_scale = scaled_block_scale_fp32 / a_global_scale\n a_scaled = a_fp32 / total_scale.unsqueeze(-1)\n a_scaled = torch.clamp(a_scaled, -FLOAT4_E2M1_MAX, FLOAT4_E2M1_MAX)\n a_scaled = a_scaled.view(original_shape)\n return to_fp4(a_scaled), scaled_block_scale_fp8\n\n\ndef round_up(x, y):\n return (x + y - 1) // y * y\n\n\ndef activation_scale_to_nvfp4(x, g_sf, offsets, blockscale_offsets, block_size):\n m = x.size(0)\n k = x.size(1)\n g = g_sf.size(0)\n padded_m_size = blockscale_offsets[g - 1] + round_up(m - offsets[g - 1], 128)\n block_scale = torch.empty(\n (padded_m_size, k // block_size), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n v_scaled = torch.empty((m, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\")\n for i in range(len(g_sf)):\n l = offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n l_sf = blockscale_offsets[i]\n r_sf = l_sf + (r - l + 127) // 128 * 128\n v, b_sf = pytorch_nvfp4_quantize(x[l:r], g_sf[i])","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.activation_scale_to_nvfp4","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.activation_scale_to_nvfp4#L160-L181","kind":"function","name":"activation_scale_to_nvfp4","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":160,"end_line":181,"context_start_line":140,"context_end_line":181,"code":" # Find absolute maximum along blockwise dimension\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n block_scale_fp32 = (max_abs / FLOAT4_E2M1_MAX).float()\n\n scaled_block_scale_fp32 = block_scale_fp32 * a_global_scale\n scaled_block_scale_fp32 = torch.clamp(\n scaled_block_scale_fp32, min=FLOAT8_E4M3_EPS, max=FLOAT8_E4M3_MAX\n )\n scaled_block_scale_fp8 = scaled_block_scale_fp32.to(torch.float8_e4m3fn)\n total_scale = scaled_block_scale_fp32 / a_global_scale\n a_scaled = a_fp32 / total_scale.unsqueeze(-1)\n a_scaled = torch.clamp(a_scaled, -FLOAT4_E2M1_MAX, FLOAT4_E2M1_MAX)\n a_scaled = a_scaled.view(original_shape)\n return to_fp4(a_scaled), scaled_block_scale_fp8\n\n\ndef round_up(x, y):\n return (x + y - 1) // y * y\n\n\ndef activation_scale_to_nvfp4(x, g_sf, offsets, blockscale_offsets, block_size):\n m = x.size(0)\n k = x.size(1)\n g = g_sf.size(0)\n padded_m_size = blockscale_offsets[g - 1] + round_up(m - offsets[g - 1], 128)\n block_scale = torch.empty(\n (padded_m_size, k // block_size), dtype=torch.float8_e4m3fn, device=\"cuda:0\"\n )\n v_scaled = torch.empty((m, k // 2), dtype=torch.float4_e2m1fn_x2, device=\"cuda:0\")\n for i in range(len(g_sf)):\n l = offsets[i]\n if i == g - 1:\n r = m\n else:\n r = offsets[i + 1]\n l_sf = blockscale_offsets[i]\n r_sf = l_sf + (r - l + 127) // 128 * 128\n v, b_sf = pytorch_nvfp4_quantize(x[l:r], g_sf[i])\n v_scaled[l:r] = v\n block_scale[l_sf:r_sf] = linear_to_swizzled_128_4(b_sf)\n\n return v_scaled, block_scale","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.down_size","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.down_size#L111-L113","kind":"function","name":"down_size","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":111,"end_line":113,"context_start_line":91,"context_end_line":133,"code":" return dequant\n\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This is from pytorch nvfp4 gemm tests.\ndef to_fp4(x):\n def down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n def pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n from torch.testing._internal.common_quantized import _f32_to_floatx_unpacked\n\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\ndef pytorch_nvfp4_quantize(a, a_global_scale):\n BLOCK_SIZE = 16\n assert (\n a.size(-1) % BLOCK_SIZE == 0","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.narrow_precision.pack_uint4","uri":"program://Fuser/function/tests.python.direct_utils.narrow_precision.pack_uint4#L115-L120","kind":"function","name":"pack_uint4","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":115,"end_line":120,"context_start_line":95,"context_end_line":140,"code":" tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This is from pytorch nvfp4 gemm tests.\ndef to_fp4(x):\n def down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n def pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n from torch.testing._internal.common_quantized import _f32_to_floatx_unpacked\n\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\ndef pytorch_nvfp4_quantize(a, a_global_scale):\n BLOCK_SIZE = 16\n assert (\n a.size(-1) % BLOCK_SIZE == 0\n ), \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n\n # Find absolute maximum along blockwise dimension","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils","uri":"program://Fuser/module/tests.python.direct_utils.utils#L1-L154","kind":"module","name":"tests.python.direct_utils.utils","path":"tests/python/direct_utils/utils.py","language":"python","start_line":1,"end_line":154,"context_start_line":1,"context_end_line":154,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\nfrom looseversion import LooseVersion\n\n\ndef microarchitecture_is(major, minor):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major == major and prop.minor == minor\n\n\ndef microarchitecture_is_pre(major):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major < major\n\n\ndef is_pre_volta():\n return microarchitecture_is_pre(7)\n\n\ndef is_pre_ampere():\n return microarchitecture_is_pre(8)\n\n\ndef is_pre_hopper():\n return microarchitecture_is_pre(9)\n\n\ndef is_pre_blackwell():\n return microarchitecture_is_pre(10)\n\n\n# Get string representation for FusionDefinition\n# Run captured python definition\n# Check that the result of captured python definition matches original results\ndef check_captured_python_definition(\n reference_outputs,\n fd,\n inputs,\n device=None,\n enable_options=None,\n disable_options=None,\n):\n try:\n fd_str = fd.__repr__()\n func_name = \"nvfuser_fusion\"\n exec(fd_str)\n\n # Execute the python definition that was captured\n with FusionDefinition() as fd_cap:\n eval(func_name)(fd_cap)\n\n torch.manual_seed(0)\n if enable_options is None:\n enable_options = []\n if disable_options is None:\n disable_options = []\n captured_outputs = fd_cap.execute(\n inputs,\n device=device,\n _enable_options=enable_options,\n _disable_options=disable_options,\n )\n\n if len(reference_outputs) != len(captured_outputs):\n return False\n\n # Check that the values of all outputs match\n for ref_out, cap_out in zip(reference_outputs, captured_outputs):\n # torch.allclose does not work with fp8 datatype, so cast to fp64.\n # However, casting complex values to real discards the imaginary\n # part, so skip complex dtypes.\n # Similarly, packed fp4 dtype cannot be compared neither, we view\n # it as int8 and run comparison as-is.\n if ref_out.dtype == torch.float4_e2m1fn_x2:\n ref_out = ref_out.view(torch.int8)\n elif not ref_out.dtype.is_complex:\n ref_out = ref_out.to(torch.float64)\n if cap_out.dtype == torch.float4_e2m1fn_x2:\n cap_out = cap_out.view(torch.int8)\n elif not cap_out.dtype.is_complex:\n cap_out = cap_out.to(torch.float64)\n if not torch.allclose(ref_out, cap_out, equal_nan=True):\n return False\n\n # Check that the stride of all outputs match\n return all(\n [\n ref_out.stride() == cap_out.stride()\n for ref_out, cap_out in zip(reference_outputs, captured_outputs)\n ]\n )\n except Exception as err:\n print(\"\\nException For Printed FusionDefinition:\")\n print(\n \"(A failure here suggests a mismatch in functionality between the original definition and the printed definition.)\"\n )\n if \"fd_str\" in locals():\n print(fd_str)\n raise err\n\n\ndef verify_stride_order(output_strides, stride_order):\n sorted_stride = list(output_strides)\n rank = len(output_strides)\n for idx, axis in enumerate(stride_order):\n sorted_stride[rank - 1 - axis] = output_strides[idx]\n assert sorted(sorted_stride, reverse=True) == sorted_stride\n\n\nUPDATED_SDPA = LooseVersion(torch.__version__) >= LooseVersion(\"2.7.0\")\n\n\ndef define_sdpa_rng_state(fd: FusionDefinition) -> tuple[TensorView, TensorView]:\n dtype = DataType.UInt64 if UPDATED_SDPA else DataType.Int\n is_cpu = False if UPDATED_SDPA else True\n philox_shape = [2] if UPDATED_SDPA else []\n philox_seed = fd.define_tensor(\n shape=philox_shape,\n dtype=dtype,\n is_cpu=is_cpu,\n )\n philox_offset = fd.define_tensor(\n shape=[],\n dtype=dtype,\n is_cpu=is_cpu,\n )\n return philox_seed, philox_offset\n\n\ndef create_sdpa_rng_tensors() -> tuple[torch.Tensor, torch.Tensor]:\n dtype = torch.uint64 if UPDATED_SDPA else torch.int64\n device = \"cuda\" if UPDATED_SDPA else \"cpu\"\n philox_shape = (2,) if UPDATED_SDPA else ()\n philox_seed = torch.testing.make_tensor(philox_shape, device=device, dtype=dtype)\n philox_offset = torch.testing.make_tensor((), device=device, dtype=dtype)\n return philox_seed, philox_offset\n\n\ndef skip_if_global_memory_below_gb(min_gb: int, gpu_id: int = 0):\n device_properties = torch.cuda.get_device_properties(gpu_id)\n total_memory_bytes = device_properties.total_memory\n min_bytes = min_gb * (1024**3)\n\n if total_memory_bytes < min_bytes:\n pytest.skip(\n f\"Insufficient GPU global memory: requires ~{min_bytes} B, \"\n f\"but only {total_memory_bytes} B available\"\n )","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.microarchitecture_is","uri":"program://Fuser/function/tests.python.direct_utils.utils.microarchitecture_is#L12-L14","kind":"function","name":"microarchitecture_is","path":"tests/python/direct_utils/utils.py","language":"python","start_line":12,"end_line":14,"context_start_line":1,"context_end_line":34,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\nfrom looseversion import LooseVersion\n\n\ndef microarchitecture_is(major, minor):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major == major and prop.minor == minor\n\n\ndef microarchitecture_is_pre(major):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major < major\n\n\ndef is_pre_volta():\n return microarchitecture_is_pre(7)\n\n\ndef is_pre_ampere():\n return microarchitecture_is_pre(8)\n\n\ndef is_pre_hopper():\n return microarchitecture_is_pre(9)\n\n\ndef is_pre_blackwell():","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.microarchitecture_is_pre","uri":"program://Fuser/function/tests.python.direct_utils.utils.microarchitecture_is_pre#L17-L19","kind":"function","name":"microarchitecture_is_pre","path":"tests/python/direct_utils/utils.py","language":"python","start_line":17,"end_line":19,"context_start_line":1,"context_end_line":39,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\nfrom looseversion import LooseVersion\n\n\ndef microarchitecture_is(major, minor):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major == major and prop.minor == minor\n\n\ndef microarchitecture_is_pre(major):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major < major\n\n\ndef is_pre_volta():\n return microarchitecture_is_pre(7)\n\n\ndef is_pre_ampere():\n return microarchitecture_is_pre(8)\n\n\ndef is_pre_hopper():\n return microarchitecture_is_pre(9)\n\n\ndef is_pre_blackwell():\n return microarchitecture_is_pre(10)\n\n\n# Get string representation for FusionDefinition\n# Run captured python definition","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.is_pre_volta","uri":"program://Fuser/function/tests.python.direct_utils.utils.is_pre_volta#L22-L23","kind":"function","name":"is_pre_volta","path":"tests/python/direct_utils/utils.py","language":"python","start_line":22,"end_line":23,"context_start_line":2,"context_end_line":43,"code":"# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\nfrom looseversion import LooseVersion\n\n\ndef microarchitecture_is(major, minor):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major == major and prop.minor == minor\n\n\ndef microarchitecture_is_pre(major):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major < major\n\n\ndef is_pre_volta():\n return microarchitecture_is_pre(7)\n\n\ndef is_pre_ampere():\n return microarchitecture_is_pre(8)\n\n\ndef is_pre_hopper():\n return microarchitecture_is_pre(9)\n\n\ndef is_pre_blackwell():\n return microarchitecture_is_pre(10)\n\n\n# Get string representation for FusionDefinition\n# Run captured python definition\n# Check that the result of captured python definition matches original results\ndef check_captured_python_definition(\n reference_outputs,\n fd,","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.is_pre_ampere","uri":"program://Fuser/function/tests.python.direct_utils.utils.is_pre_ampere#L26-L27","kind":"function","name":"is_pre_ampere","path":"tests/python/direct_utils/utils.py","language":"python","start_line":26,"end_line":27,"context_start_line":6,"context_end_line":47,"code":"import torch\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\nfrom looseversion import LooseVersion\n\n\ndef microarchitecture_is(major, minor):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major == major and prop.minor == minor\n\n\ndef microarchitecture_is_pre(major):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major < major\n\n\ndef is_pre_volta():\n return microarchitecture_is_pre(7)\n\n\ndef is_pre_ampere():\n return microarchitecture_is_pre(8)\n\n\ndef is_pre_hopper():\n return microarchitecture_is_pre(9)\n\n\ndef is_pre_blackwell():\n return microarchitecture_is_pre(10)\n\n\n# Get string representation for FusionDefinition\n# Run captured python definition\n# Check that the result of captured python definition matches original results\ndef check_captured_python_definition(\n reference_outputs,\n fd,\n inputs,\n device=None,\n enable_options=None,\n disable_options=None,","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.is_pre_hopper","uri":"program://Fuser/function/tests.python.direct_utils.utils.is_pre_hopper#L30-L31","kind":"function","name":"is_pre_hopper","path":"tests/python/direct_utils/utils.py","language":"python","start_line":30,"end_line":31,"context_start_line":10,"context_end_line":51,"code":"\n\ndef microarchitecture_is(major, minor):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major == major and prop.minor == minor\n\n\ndef microarchitecture_is_pre(major):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major < major\n\n\ndef is_pre_volta():\n return microarchitecture_is_pre(7)\n\n\ndef is_pre_ampere():\n return microarchitecture_is_pre(8)\n\n\ndef is_pre_hopper():\n return microarchitecture_is_pre(9)\n\n\ndef is_pre_blackwell():\n return microarchitecture_is_pre(10)\n\n\n# Get string representation for FusionDefinition\n# Run captured python definition\n# Check that the result of captured python definition matches original results\ndef check_captured_python_definition(\n reference_outputs,\n fd,\n inputs,\n device=None,\n enable_options=None,\n disable_options=None,\n):\n try:\n fd_str = fd.__repr__()\n func_name = \"nvfuser_fusion\"","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.is_pre_blackwell","uri":"program://Fuser/function/tests.python.direct_utils.utils.is_pre_blackwell#L34-L35","kind":"function","name":"is_pre_blackwell","path":"tests/python/direct_utils/utils.py","language":"python","start_line":34,"end_line":35,"context_start_line":14,"context_end_line":55,"code":" return prop.major == major and prop.minor == minor\n\n\ndef microarchitecture_is_pre(major):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major < major\n\n\ndef is_pre_volta():\n return microarchitecture_is_pre(7)\n\n\ndef is_pre_ampere():\n return microarchitecture_is_pre(8)\n\n\ndef is_pre_hopper():\n return microarchitecture_is_pre(9)\n\n\ndef is_pre_blackwell():\n return microarchitecture_is_pre(10)\n\n\n# Get string representation for FusionDefinition\n# Run captured python definition\n# Check that the result of captured python definition matches original results\ndef check_captured_python_definition(\n reference_outputs,\n fd,\n inputs,\n device=None,\n enable_options=None,\n disable_options=None,\n):\n try:\n fd_str = fd.__repr__()\n func_name = \"nvfuser_fusion\"\n exec(fd_str)\n\n # Execute the python definition that was captured\n with FusionDefinition() as fd_cap:","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.check_captured_python_definition","uri":"program://Fuser/function/tests.python.direct_utils.utils.check_captured_python_definition#L41-L105","kind":"function","name":"check_captured_python_definition","path":"tests/python/direct_utils/utils.py","language":"python","start_line":41,"end_line":105,"context_start_line":21,"context_end_line":125,"code":"\ndef is_pre_volta():\n return microarchitecture_is_pre(7)\n\n\ndef is_pre_ampere():\n return microarchitecture_is_pre(8)\n\n\ndef is_pre_hopper():\n return microarchitecture_is_pre(9)\n\n\ndef is_pre_blackwell():\n return microarchitecture_is_pre(10)\n\n\n# Get string representation for FusionDefinition\n# Run captured python definition\n# Check that the result of captured python definition matches original results\ndef check_captured_python_definition(\n reference_outputs,\n fd,\n inputs,\n device=None,\n enable_options=None,\n disable_options=None,\n):\n try:\n fd_str = fd.__repr__()\n func_name = \"nvfuser_fusion\"\n exec(fd_str)\n\n # Execute the python definition that was captured\n with FusionDefinition() as fd_cap:\n eval(func_name)(fd_cap)\n\n torch.manual_seed(0)\n if enable_options is None:\n enable_options = []\n if disable_options is None:\n disable_options = []\n captured_outputs = fd_cap.execute(\n inputs,\n device=device,\n _enable_options=enable_options,\n _disable_options=disable_options,\n )\n\n if len(reference_outputs) != len(captured_outputs):\n return False\n\n # Check that the values of all outputs match\n for ref_out, cap_out in zip(reference_outputs, captured_outputs):\n # torch.allclose does not work with fp8 datatype, so cast to fp64.\n # However, casting complex values to real discards the imaginary\n # part, so skip complex dtypes.\n # Similarly, packed fp4 dtype cannot be compared neither, we view\n # it as int8 and run comparison as-is.\n if ref_out.dtype == torch.float4_e2m1fn_x2:\n ref_out = ref_out.view(torch.int8)\n elif not ref_out.dtype.is_complex:\n ref_out = ref_out.to(torch.float64)\n if cap_out.dtype == torch.float4_e2m1fn_x2:\n cap_out = cap_out.view(torch.int8)\n elif not cap_out.dtype.is_complex:\n cap_out = cap_out.to(torch.float64)\n if not torch.allclose(ref_out, cap_out, equal_nan=True):\n return False\n\n # Check that the stride of all outputs match\n return all(\n [\n ref_out.stride() == cap_out.stride()\n for ref_out, cap_out in zip(reference_outputs, captured_outputs)\n ]\n )\n except Exception as err:\n print(\"\\nException For Printed FusionDefinition:\")\n print(\n \"(A failure here suggests a mismatch in functionality between the original definition and the printed definition.)\"\n )\n if \"fd_str\" in locals():\n print(fd_str)\n raise err\n\n\ndef verify_stride_order(output_strides, stride_order):\n sorted_stride = list(output_strides)\n rank = len(output_strides)\n for idx, axis in enumerate(stride_order):\n sorted_stride[rank - 1 - axis] = output_strides[idx]\n assert sorted(sorted_stride, reverse=True) == sorted_stride\n\n\nUPDATED_SDPA = LooseVersion(torch.__version__) >= LooseVersion(\"2.7.0\")\n\n\ndef define_sdpa_rng_state(fd: FusionDefinition) -> tuple[TensorView, TensorView]:\n dtype = DataType.UInt64 if UPDATED_SDPA else DataType.Int\n is_cpu = False if UPDATED_SDPA else True\n philox_shape = [2] if UPDATED_SDPA else []\n philox_seed = fd.define_tensor(\n shape=philox_shape,\n dtype=dtype,","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.verify_stride_order","uri":"program://Fuser/function/tests.python.direct_utils.utils.verify_stride_order#L108-L113","kind":"function","name":"verify_stride_order","path":"tests/python/direct_utils/utils.py","language":"python","start_line":108,"end_line":113,"context_start_line":88,"context_end_line":133,"code":" if not torch.allclose(ref_out, cap_out, equal_nan=True):\n return False\n\n # Check that the stride of all outputs match\n return all(\n [\n ref_out.stride() == cap_out.stride()\n for ref_out, cap_out in zip(reference_outputs, captured_outputs)\n ]\n )\n except Exception as err:\n print(\"\\nException For Printed FusionDefinition:\")\n print(\n \"(A failure here suggests a mismatch in functionality between the original definition and the printed definition.)\"\n )\n if \"fd_str\" in locals():\n print(fd_str)\n raise err\n\n\ndef verify_stride_order(output_strides, stride_order):\n sorted_stride = list(output_strides)\n rank = len(output_strides)\n for idx, axis in enumerate(stride_order):\n sorted_stride[rank - 1 - axis] = output_strides[idx]\n assert sorted(sorted_stride, reverse=True) == sorted_stride\n\n\nUPDATED_SDPA = LooseVersion(torch.__version__) >= LooseVersion(\"2.7.0\")\n\n\ndef define_sdpa_rng_state(fd: FusionDefinition) -> tuple[TensorView, TensorView]:\n dtype = DataType.UInt64 if UPDATED_SDPA else DataType.Int\n is_cpu = False if UPDATED_SDPA else True\n philox_shape = [2] if UPDATED_SDPA else []\n philox_seed = fd.define_tensor(\n shape=philox_shape,\n dtype=dtype,\n is_cpu=is_cpu,\n )\n philox_offset = fd.define_tensor(\n shape=[],\n dtype=dtype,\n is_cpu=is_cpu,\n )\n return philox_seed, philox_offset","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.define_sdpa_rng_state","uri":"program://Fuser/function/tests.python.direct_utils.utils.define_sdpa_rng_state#L119-L133","kind":"function","name":"define_sdpa_rng_state","path":"tests/python/direct_utils/utils.py","language":"python","start_line":119,"end_line":133,"context_start_line":99,"context_end_line":153,"code":" print(\"\\nException For Printed FusionDefinition:\")\n print(\n \"(A failure here suggests a mismatch in functionality between the original definition and the printed definition.)\"\n )\n if \"fd_str\" in locals():\n print(fd_str)\n raise err\n\n\ndef verify_stride_order(output_strides, stride_order):\n sorted_stride = list(output_strides)\n rank = len(output_strides)\n for idx, axis in enumerate(stride_order):\n sorted_stride[rank - 1 - axis] = output_strides[idx]\n assert sorted(sorted_stride, reverse=True) == sorted_stride\n\n\nUPDATED_SDPA = LooseVersion(torch.__version__) >= LooseVersion(\"2.7.0\")\n\n\ndef define_sdpa_rng_state(fd: FusionDefinition) -> tuple[TensorView, TensorView]:\n dtype = DataType.UInt64 if UPDATED_SDPA else DataType.Int\n is_cpu = False if UPDATED_SDPA else True\n philox_shape = [2] if UPDATED_SDPA else []\n philox_seed = fd.define_tensor(\n shape=philox_shape,\n dtype=dtype,\n is_cpu=is_cpu,\n )\n philox_offset = fd.define_tensor(\n shape=[],\n dtype=dtype,\n is_cpu=is_cpu,\n )\n return philox_seed, philox_offset\n\n\ndef create_sdpa_rng_tensors() -> tuple[torch.Tensor, torch.Tensor]:\n dtype = torch.uint64 if UPDATED_SDPA else torch.int64\n device = \"cuda\" if UPDATED_SDPA else \"cpu\"\n philox_shape = (2,) if UPDATED_SDPA else ()\n philox_seed = torch.testing.make_tensor(philox_shape, device=device, dtype=dtype)\n philox_offset = torch.testing.make_tensor((), device=device, dtype=dtype)\n return philox_seed, philox_offset\n\n\ndef skip_if_global_memory_below_gb(min_gb: int, gpu_id: int = 0):\n device_properties = torch.cuda.get_device_properties(gpu_id)\n total_memory_bytes = device_properties.total_memory\n min_bytes = min_gb * (1024**3)\n\n if total_memory_bytes < min_bytes:\n pytest.skip(\n f\"Insufficient GPU global memory: requires ~{min_bytes} B, \"\n f\"but only {total_memory_bytes} B available\"","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.create_sdpa_rng_tensors","uri":"program://Fuser/function/tests.python.direct_utils.utils.create_sdpa_rng_tensors#L136-L142","kind":"function","name":"create_sdpa_rng_tensors","path":"tests/python/direct_utils/utils.py","language":"python","start_line":136,"end_line":142,"context_start_line":116,"context_end_line":154,"code":"UPDATED_SDPA = LooseVersion(torch.__version__) >= LooseVersion(\"2.7.0\")\n\n\ndef define_sdpa_rng_state(fd: FusionDefinition) -> tuple[TensorView, TensorView]:\n dtype = DataType.UInt64 if UPDATED_SDPA else DataType.Int\n is_cpu = False if UPDATED_SDPA else True\n philox_shape = [2] if UPDATED_SDPA else []\n philox_seed = fd.define_tensor(\n shape=philox_shape,\n dtype=dtype,\n is_cpu=is_cpu,\n )\n philox_offset = fd.define_tensor(\n shape=[],\n dtype=dtype,\n is_cpu=is_cpu,\n )\n return philox_seed, philox_offset\n\n\ndef create_sdpa_rng_tensors() -> tuple[torch.Tensor, torch.Tensor]:\n dtype = torch.uint64 if UPDATED_SDPA else torch.int64\n device = \"cuda\" if UPDATED_SDPA else \"cpu\"\n philox_shape = (2,) if UPDATED_SDPA else ()\n philox_seed = torch.testing.make_tensor(philox_shape, device=device, dtype=dtype)\n philox_offset = torch.testing.make_tensor((), device=device, dtype=dtype)\n return philox_seed, philox_offset\n\n\ndef skip_if_global_memory_below_gb(min_gb: int, gpu_id: int = 0):\n device_properties = torch.cuda.get_device_properties(gpu_id)\n total_memory_bytes = device_properties.total_memory\n min_bytes = min_gb * (1024**3)\n\n if total_memory_bytes < min_bytes:\n pytest.skip(\n f\"Insufficient GPU global memory: requires ~{min_bytes} B, \"\n f\"but only {total_memory_bytes} B available\"\n )","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:tests.python.direct_utils.utils.skip_if_global_memory_below_gb","uri":"program://Fuser/function/tests.python.direct_utils.utils.skip_if_global_memory_below_gb#L145-L154","kind":"function","name":"skip_if_global_memory_below_gb","path":"tests/python/direct_utils/utils.py","language":"python","start_line":145,"end_line":154,"context_start_line":125,"context_end_line":154,"code":" dtype=dtype,\n is_cpu=is_cpu,\n )\n philox_offset = fd.define_tensor(\n shape=[],\n dtype=dtype,\n is_cpu=is_cpu,\n )\n return philox_seed, philox_offset\n\n\ndef create_sdpa_rng_tensors() -> tuple[torch.Tensor, torch.Tensor]:\n dtype = torch.uint64 if UPDATED_SDPA else torch.int64\n device = \"cuda\" if UPDATED_SDPA else \"cpu\"\n philox_shape = (2,) if UPDATED_SDPA else ()\n philox_seed = torch.testing.make_tensor(philox_shape, device=device, dtype=dtype)\n philox_offset = torch.testing.make_tensor((), device=device, dtype=dtype)\n return philox_seed, philox_offset\n\n\ndef skip_if_global_memory_below_gb(min_gb: int, gpu_id: int = 0):\n device_properties = torch.cuda.get_device_properties(gpu_id)\n total_memory_bytes = device_properties.total_memory\n min_bytes = min_gb * (1024**3)\n\n if total_memory_bytes < min_bytes:\n pytest.skip(\n f\"Insufficient GPU global memory: requires ~{min_bytes} B, \"\n f\"but only {total_memory_bytes} B available\"\n )","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"py:examples.sinh_extension.setup","uri":"program://Fuser/module/examples.sinh_extension.setup#L1-L89","kind":"module","name":"examples.sinh_extension.setup","path":"examples/sinh_extension/setup.py","language":"python","start_line":1,"end_line":89,"context_start_line":1,"context_end_line":89,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport os\nimport pathlib\nimport importlib.util\nfrom setuptools import setup\n\ntry:\n from torch.utils.cpp_extension import BuildExtension, CUDAExtension\nexcept ImportError:\n raise RuntimeError(\"PyTorch cpp_extension is required for building this package.\")\n\nnvfuser_csrc_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"..\", \"..\", \"csrc\"\n)\ndynamic_type_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"..\", \"..\", \"lib\", \"dynamic_type\", \"src\"\n)\nflatbuffers_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n \"..\",\n \"..\",\n \"third_party\",\n \"flatbuffers\",\n \"include\",\n)\n\n# Ensure nvfuser is installed before trying to find its path\ntry:\n nvfuser_spec = importlib.util.find_spec(\"nvfuser_common\")\n if nvfuser_spec is None or nvfuser_spec.origin is None:\n raise ImportError(\"Could not find nvfuser. Is it installed?\")\n nvfuser_lib_dir = str(pathlib.Path(nvfuser_spec.origin).parent / \"lib\")\nexcept ImportError as e:\n print(f\"Error finding nvfuser path: {e}\")\n print(\"Ensure 'nvfuser' is installed in the build environment.\")\n raise e\n\n\n# Inherit from PyTorch BuildExtension\n# Modify build_extension from setuptools.command.build_ext to move shared\n# library to nvfuser_extension package\nclass custom_build_ext(BuildExtension):\n def build_extension(self, ext):\n # Handle different os and cpu arch\n def _find_library_path():\n for item in os.listdir(\"build\"):\n if item.startswith(\"lib\"):\n return item\n raise RuntimeException(\"Cannot find lib in build directory\")\n\n # Call PyTorch BuildExtension first that overloads\n # setuptools.command.build_ext\n super().build_extension(ext)\n if ext.name == \"nvfuser_extension\":\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n extension_path = os.path.join(\"./build/\", _find_library_path(), filename)\n assert os.path.exists(extension_path)\n\n install_dst = os.path.join(\"nvfuser_extension\", filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))\n self.copy_file(extension_path, install_dst)\n\n\nsetup(\n # Name is now in pyproject.toml\n # Version is now in pyproject.toml\n ext_modules=[\n CUDAExtension(\n name=\"nvfuser_extension\", # The name of the *compiled* module\n # pkg tells setuptools where the compiled module should go.\n # Assumes you have a Python package directory named 'nvfuser_extension'\n pkg=\"nvfuser_extension\",\n include_dirs=[nvfuser_csrc_dir, dynamic_type_dir, flatbuffers_dir],\n libraries=[\"nvfuser_codegen\"],\n library_dirs=[nvfuser_lib_dir],\n extra_link_args=[f\"-Wl,-rpath,{nvfuser_lib_dir}\"],\n sources=[\"main.cpp\"],\n extra_compile_args={\"cxx\": [\"-std=c++20\"]},\n )\n ],\n # Keep cmdclass to use custom build extension logic\n cmdclass={\"build_ext\": custom_build_ext},\n)","source_hash":"0e8be3e7fda8cd103652cb76b5f82bb9d5f16ac1f15fcfcd6dd3910569dbe7ca","truncated":false} {"repo_id":"Fuser","entity_id":"py:examples.sinh_extension.setup.custom_build_ext","uri":"program://Fuser/class/examples.sinh_extension.setup.custom_build_ext#L44-L67","kind":"class","name":"custom_build_ext","path":"examples/sinh_extension/setup.py","language":"python","start_line":44,"end_line":67,"context_start_line":24,"context_end_line":87,"code":" \"third_party\",\n \"flatbuffers\",\n \"include\",\n)\n\n# Ensure nvfuser is installed before trying to find its path\ntry:\n nvfuser_spec = importlib.util.find_spec(\"nvfuser_common\")\n if nvfuser_spec is None or nvfuser_spec.origin is None:\n raise ImportError(\"Could not find nvfuser. Is it installed?\")\n nvfuser_lib_dir = str(pathlib.Path(nvfuser_spec.origin).parent / \"lib\")\nexcept ImportError as e:\n print(f\"Error finding nvfuser path: {e}\")\n print(\"Ensure 'nvfuser' is installed in the build environment.\")\n raise e\n\n\n# Inherit from PyTorch BuildExtension\n# Modify build_extension from setuptools.command.build_ext to move shared\n# library to nvfuser_extension package\nclass custom_build_ext(BuildExtension):\n def build_extension(self, ext):\n # Handle different os and cpu arch\n def _find_library_path():\n for item in os.listdir(\"build\"):\n if item.startswith(\"lib\"):\n return item\n raise RuntimeException(\"Cannot find lib in build directory\")\n\n # Call PyTorch BuildExtension first that overloads\n # setuptools.command.build_ext\n super().build_extension(ext)\n if ext.name == \"nvfuser_extension\":\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n extension_path = os.path.join(\"./build/\", _find_library_path(), filename)\n assert os.path.exists(extension_path)\n\n install_dst = os.path.join(\"nvfuser_extension\", filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))\n self.copy_file(extension_path, install_dst)\n\n\nsetup(\n # Name is now in pyproject.toml\n # Version is now in pyproject.toml\n ext_modules=[\n CUDAExtension(\n name=\"nvfuser_extension\", # The name of the *compiled* module\n # pkg tells setuptools where the compiled module should go.\n # Assumes you have a Python package directory named 'nvfuser_extension'\n pkg=\"nvfuser_extension\",\n include_dirs=[nvfuser_csrc_dir, dynamic_type_dir, flatbuffers_dir],\n libraries=[\"nvfuser_codegen\"],\n library_dirs=[nvfuser_lib_dir],\n extra_link_args=[f\"-Wl,-rpath,{nvfuser_lib_dir}\"],\n sources=[\"main.cpp\"],\n extra_compile_args={\"cxx\": [\"-std=c++20\"]},\n )\n ],\n # Keep cmdclass to use custom build extension logic","source_hash":"0e8be3e7fda8cd103652cb76b5f82bb9d5f16ac1f15fcfcd6dd3910569dbe7ca","truncated":false} {"repo_id":"Fuser","entity_id":"py:examples.sinh_extension.setup.build_extension","uri":"program://Fuser/function/examples.sinh_extension.setup.build_extension#L45-L67","kind":"function","name":"build_extension","path":"examples/sinh_extension/setup.py","language":"python","start_line":45,"end_line":67,"context_start_line":25,"context_end_line":87,"code":" \"flatbuffers\",\n \"include\",\n)\n\n# Ensure nvfuser is installed before trying to find its path\ntry:\n nvfuser_spec = importlib.util.find_spec(\"nvfuser_common\")\n if nvfuser_spec is None or nvfuser_spec.origin is None:\n raise ImportError(\"Could not find nvfuser. Is it installed?\")\n nvfuser_lib_dir = str(pathlib.Path(nvfuser_spec.origin).parent / \"lib\")\nexcept ImportError as e:\n print(f\"Error finding nvfuser path: {e}\")\n print(\"Ensure 'nvfuser' is installed in the build environment.\")\n raise e\n\n\n# Inherit from PyTorch BuildExtension\n# Modify build_extension from setuptools.command.build_ext to move shared\n# library to nvfuser_extension package\nclass custom_build_ext(BuildExtension):\n def build_extension(self, ext):\n # Handle different os and cpu arch\n def _find_library_path():\n for item in os.listdir(\"build\"):\n if item.startswith(\"lib\"):\n return item\n raise RuntimeException(\"Cannot find lib in build directory\")\n\n # Call PyTorch BuildExtension first that overloads\n # setuptools.command.build_ext\n super().build_extension(ext)\n if ext.name == \"nvfuser_extension\":\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n extension_path = os.path.join(\"./build/\", _find_library_path(), filename)\n assert os.path.exists(extension_path)\n\n install_dst = os.path.join(\"nvfuser_extension\", filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))\n self.copy_file(extension_path, install_dst)\n\n\nsetup(\n # Name is now in pyproject.toml\n # Version is now in pyproject.toml\n ext_modules=[\n CUDAExtension(\n name=\"nvfuser_extension\", # The name of the *compiled* module\n # pkg tells setuptools where the compiled module should go.\n # Assumes you have a Python package directory named 'nvfuser_extension'\n pkg=\"nvfuser_extension\",\n include_dirs=[nvfuser_csrc_dir, dynamic_type_dir, flatbuffers_dir],\n libraries=[\"nvfuser_codegen\"],\n library_dirs=[nvfuser_lib_dir],\n extra_link_args=[f\"-Wl,-rpath,{nvfuser_lib_dir}\"],\n sources=[\"main.cpp\"],\n extra_compile_args={\"cxx\": [\"-std=c++20\"]},\n )\n ],\n # Keep cmdclass to use custom build extension logic","source_hash":"0e8be3e7fda8cd103652cb76b5f82bb9d5f16ac1f15fcfcd6dd3910569dbe7ca","truncated":false} {"repo_id":"Fuser","entity_id":"py:examples.sinh_extension.setup._find_library_path","uri":"program://Fuser/function/examples.sinh_extension.setup._find_library_path#L47-L51","kind":"function","name":"_find_library_path","path":"examples/sinh_extension/setup.py","language":"python","start_line":47,"end_line":51,"context_start_line":27,"context_end_line":71,"code":")\n\n# Ensure nvfuser is installed before trying to find its path\ntry:\n nvfuser_spec = importlib.util.find_spec(\"nvfuser_common\")\n if nvfuser_spec is None or nvfuser_spec.origin is None:\n raise ImportError(\"Could not find nvfuser. Is it installed?\")\n nvfuser_lib_dir = str(pathlib.Path(nvfuser_spec.origin).parent / \"lib\")\nexcept ImportError as e:\n print(f\"Error finding nvfuser path: {e}\")\n print(\"Ensure 'nvfuser' is installed in the build environment.\")\n raise e\n\n\n# Inherit from PyTorch BuildExtension\n# Modify build_extension from setuptools.command.build_ext to move shared\n# library to nvfuser_extension package\nclass custom_build_ext(BuildExtension):\n def build_extension(self, ext):\n # Handle different os and cpu arch\n def _find_library_path():\n for item in os.listdir(\"build\"):\n if item.startswith(\"lib\"):\n return item\n raise RuntimeException(\"Cannot find lib in build directory\")\n\n # Call PyTorch BuildExtension first that overloads\n # setuptools.command.build_ext\n super().build_extension(ext)\n if ext.name == \"nvfuser_extension\":\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n extension_path = os.path.join(\"./build/\", _find_library_path(), filename)\n assert os.path.exists(extension_path)\n\n install_dst = os.path.join(\"nvfuser_extension\", filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))\n self.copy_file(extension_path, install_dst)\n\n\nsetup(\n # Name is now in pyproject.toml","source_hash":"0e8be3e7fda8cd103652cb76b5f82bb9d5f16ac1f15fcfcd6dd3910569dbe7ca","truncated":false} {"repo_id":"Fuser","entity_id":"py:examples.sinh_extension.test","uri":"program://Fuser/module/examples.sinh_extension.test#L1-L16","kind":"module","name":"examples.sinh_extension.test","path":"examples/sinh_extension/test.py","language":"python","start_line":1,"end_line":16,"context_start_line":1,"context_end_line":16,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\nimport nvfuser_extension # noqa: F401\n\ntorch.manual_seed(0)\nt = torch.randn((5, 5), device=\"cuda\")\nexpected = torch.sinh(t)\noutput = torch.ops.myop.sinh_nvfuser(t)\n\nprint(\"Expected:\", expected)\nprint(\"Output:\", output)\n\nassert torch.allclose(output, expected)\nprint(\"They match!\")","source_hash":"41650d83aa89d625e16066824aa0630b11d8572662a8451655ab14c4e4fc924b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul","uri":"program://Fuser/module/doc.dev.python_scheduling.profile_matmul#L1-L211","kind":"module","name":"doc.dev.python_scheduling.profile_matmul","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":1,"end_line":211,"context_start_line":1,"context_end_line":211,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import (\n FusionDefinition,\n SchedulerType,\n ClusterDims,\n MatMulTileOptions,\n GemmTile,\n MmaMacroEncode,\n MmaMacroArch,\n MatmulTileRasterizationOrder,\n MatmulCircularBufferingStrategy,\n)\nimport torch\nfrom torch.autograd import DeviceType\nfrom torch.profiler import profile, record_function, ProfilerActivity\nimport math\nimport itertools\nfrom enum import IntEnum\n\n\nclass Layout(IntEnum):\n NN = 0\n NT = 1\n TN = 2\n TT = 3\n\n\ndef estimate_matmul_size(config, dtype):\n def _estimate_size(shape, dtype):\n return math.prod(shape) * dtype.itemsize\n\n m, n, k, layout = config\n total_in_gbs = 0\n for shape in [[m, k], [n, k], [m, n]]:\n total_in_gbs += _estimate_size(shape, dtype)\n return total_in_gbs\n\n\ndef get_kernel_time(prof_averages: torch.autograd.profiler_util.EventList):\n elapsed_cuda_time = 0\n has_cuda_event = False\n for event in prof_averages:\n if event.device_type != DeviceType.CUDA:\n continue\n has_cuda_event = True\n elapsed_cuda_time = (\n elapsed_cuda_time + event.self_device_time_total\n if hasattr(event, \"self_device_time_total\")\n else event.self_cuda_time_total\n )\n assert has_cuda_event, \"No CUDA events found\"\n return elapsed_cuda_time / 1e3\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\nclass MatmulDefinition(FusionDefinition):\n def __init__(self, inputs, config, verbose=False):\n super().__init__()\n self.inputs = inputs\n self.config = config\n self.verbose = verbose\n\n def definition(self):\n matmul_fusion(self, self.inputs)\n\n def schedule(self):\n assert self.config is not None\n status, error = self.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = self.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n tile_sizes, macro, tile_order, cluster_dims, stages = self.config\n schedule_params.tile_sizes = tile_sizes\n schedule_params.mma_macro = macro.mma_macro()\n schedule_params.cta_order = tile_order\n schedule_params.cluster_dims = cluster_dims\n schedule_params.circular_buffering_strategy = (\n MatmulCircularBufferingStrategy.warp_specialized\n )\n schedule_params.circular_buffer_options.circular_buffer_smem_write = stages > 1\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n if self.verbose:\n print(schedule_params)\n\n # Schedule fusion\n self.sched.schedule()\n\n\ndef test_matmul_nvf(\n problem_config: tuple,\n schedule_config: tuple,\n verbose: bool = False,\n validate: bool = False,\n):\n m, n, k, layout = problem_config\n dtype = torch.bfloat16\n\n # NOTE reduced precision accumulation is not supported in nvFuser\n torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False\n torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False\n\n a = torch.randn(m, k, device=\"cuda\", dtype=dtype)\n b = torch.randn(k, n, device=\"cuda\", dtype=dtype)\n\n if layout == \"NT\" or layout == \"NN\":\n a = a.as_strided(size=[m, k], stride=[1, m])\n if layout == \"TN\" or layout == \"NN\":\n b = b.as_strided(size=[k, n], stride=[1, k])\n\n scheduled_fd = MatmulDefinition([a, b], schedule_config, verbose)\n\n try:\n nvf_outputs = scheduled_fd.execute([a, b], profile=True)\n except Exception as e:\n if verbose:\n print(e)\n return -1\n\n with profile(activities=[ProfilerActivity.CUDA], record_shapes=True) as prof:\n with record_function(\"matmul\"):\n baseline_output = torch.matmul(a, b)\n baseline_time = get_kernel_time(prof.key_averages())\n\n if validate:\n tolerance = k * 1e-6\n assert torch.allclose(\n nvf_outputs[0], baseline_output, atol=tolerance, rtol=tolerance\n )\n\n prof = scheduled_fd.profile()\n nvf_time = prof.kernel_profiles[0].time_ms\n return baseline_time, nvf_time\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser(\n description=\"\"\"Run through a combination of matmul parameters and compare relative performance against nvjet for a single problem.\"\"\",\n epilog=\"\"\"How to run script: NVFUSER_ENABLE=fuse_matmul NVFUSER_DISABLE=matmul_expr_eval python single_matmul.py nvjet_pybench.json 1752 4720 584 NN --verbose --validate\"\"\",\n )\n parser.add_argument(\"m\", type=int, help=\"The size of M dimension\")\n parser.add_argument(\"n\", type=int, help=\"The size of N dimension\")\n parser.add_argument(\"k\", type=int, help=\"The size of K dimension\")\n parser.add_argument(\n \"layout\",\n type=str,\n choices=[layout.name for layout in Layout],\n help=\"The layout for matmul problem.\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"Print matmul parameters and exceptions.\",\n )\n parser.add_argument(\n \"--validate\",\n action=\"store_true\",\n help=\"Validate nvfuser against pytorch matmul.\",\n )\n args = parser.parse_args()\n\n problem_config = (args.m, args.n, args.k, args.layout)\n device_properties = torch.cuda.get_device_properties(0)\n # short-circuit: problem does not fit on device\n if (\n estimate_matmul_size(problem_config, torch.bfloat16)\n >= device_properties.total_memory\n ):\n assert False\n\n # These are the parameters we'll optimize\n parameter_configurations = {\n \"tile_sizes\": [\n MatMulTileOptions(GemmTile(128, 256, 64), GemmTile(64, 256, 64))\n ],\n \"mma_macro\": [MmaMacroEncode(MmaMacroArch.hopper, 64, 256, 16)],\n \"tile_order\": [MatmulTileRasterizationOrder.column_major],\n \"cluster_dims\": [ClusterDims(1, 1, 1)],\n \"circular_buffer_stages\": [4],\n }\n\n print(\n f\"problem configuration, m: {args.m}, n: {args.n}, k: {args.k}, layout: {args.layout}\"\n )\n for idx, scheduler_config in enumerate(\n itertools.product(*parameter_configurations.values())\n ):\n baseline_result, nvf_result = test_matmul_nvf(\n problem_config, scheduler_config, args.verbose, args.validate\n )\n normalized_result = baseline_result / nvf_result\n print(\n f\"index: {idx}, baseline(us): {baseline_result: .3e}, \"\n f\"nvfuser(us): {nvf_result: 3e}, normalized(us): {normalized_result: 2f}\"\n )\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.Layout","uri":"program://Fuser/class/doc.dev.python_scheduling.profile_matmul.Layout#L24-L28","kind":"class","name":"Layout","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":24,"end_line":28,"context_start_line":4,"context_end_line":48,"code":"# TODO Update script to use nvfuser_direct module\nfrom nvfuser import (\n FusionDefinition,\n SchedulerType,\n ClusterDims,\n MatMulTileOptions,\n GemmTile,\n MmaMacroEncode,\n MmaMacroArch,\n MatmulTileRasterizationOrder,\n MatmulCircularBufferingStrategy,\n)\nimport torch\nfrom torch.autograd import DeviceType\nfrom torch.profiler import profile, record_function, ProfilerActivity\nimport math\nimport itertools\nfrom enum import IntEnum\n\n\nclass Layout(IntEnum):\n NN = 0\n NT = 1\n TN = 2\n TT = 3\n\n\ndef estimate_matmul_size(config, dtype):\n def _estimate_size(shape, dtype):\n return math.prod(shape) * dtype.itemsize\n\n m, n, k, layout = config\n total_in_gbs = 0\n for shape in [[m, k], [n, k], [m, n]]:\n total_in_gbs += _estimate_size(shape, dtype)\n return total_in_gbs\n\n\ndef get_kernel_time(prof_averages: torch.autograd.profiler_util.EventList):\n elapsed_cuda_time = 0\n has_cuda_event = False\n for event in prof_averages:\n if event.device_type != DeviceType.CUDA:\n continue\n has_cuda_event = True","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.estimate_matmul_size","uri":"program://Fuser/function/doc.dev.python_scheduling.profile_matmul.estimate_matmul_size#L31-L39","kind":"function","name":"estimate_matmul_size","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":31,"end_line":39,"context_start_line":11,"context_end_line":59,"code":" MmaMacroEncode,\n MmaMacroArch,\n MatmulTileRasterizationOrder,\n MatmulCircularBufferingStrategy,\n)\nimport torch\nfrom torch.autograd import DeviceType\nfrom torch.profiler import profile, record_function, ProfilerActivity\nimport math\nimport itertools\nfrom enum import IntEnum\n\n\nclass Layout(IntEnum):\n NN = 0\n NT = 1\n TN = 2\n TT = 3\n\n\ndef estimate_matmul_size(config, dtype):\n def _estimate_size(shape, dtype):\n return math.prod(shape) * dtype.itemsize\n\n m, n, k, layout = config\n total_in_gbs = 0\n for shape in [[m, k], [n, k], [m, n]]:\n total_in_gbs += _estimate_size(shape, dtype)\n return total_in_gbs\n\n\ndef get_kernel_time(prof_averages: torch.autograd.profiler_util.EventList):\n elapsed_cuda_time = 0\n has_cuda_event = False\n for event in prof_averages:\n if event.device_type != DeviceType.CUDA:\n continue\n has_cuda_event = True\n elapsed_cuda_time = (\n elapsed_cuda_time + event.self_device_time_total\n if hasattr(event, \"self_device_time_total\")\n else event.self_cuda_time_total\n )\n assert has_cuda_event, \"No CUDA events found\"\n return elapsed_cuda_time / 1e3\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.get_kernel_time","uri":"program://Fuser/function/doc.dev.python_scheduling.profile_matmul.get_kernel_time#L42-L55","kind":"function","name":"get_kernel_time","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":42,"end_line":55,"context_start_line":22,"context_end_line":75,"code":"\n\nclass Layout(IntEnum):\n NN = 0\n NT = 1\n TN = 2\n TT = 3\n\n\ndef estimate_matmul_size(config, dtype):\n def _estimate_size(shape, dtype):\n return math.prod(shape) * dtype.itemsize\n\n m, n, k, layout = config\n total_in_gbs = 0\n for shape in [[m, k], [n, k], [m, n]]:\n total_in_gbs += _estimate_size(shape, dtype)\n return total_in_gbs\n\n\ndef get_kernel_time(prof_averages: torch.autograd.profiler_util.EventList):\n elapsed_cuda_time = 0\n has_cuda_event = False\n for event in prof_averages:\n if event.device_type != DeviceType.CUDA:\n continue\n has_cuda_event = True\n elapsed_cuda_time = (\n elapsed_cuda_time + event.self_device_time_total\n if hasattr(event, \"self_device_time_total\")\n else event.self_cuda_time_total\n )\n assert has_cuda_event, \"No CUDA events found\"\n return elapsed_cuda_time / 1e3\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\nclass MatmulDefinition(FusionDefinition):\n def __init__(self, inputs, config, verbose=False):\n super().__init__()\n self.inputs = inputs\n self.config = config\n self.verbose = verbose\n\n def definition(self):\n matmul_fusion(self, self.inputs)\n\n def schedule(self):","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.matmul_fusion","uri":"program://Fuser/function/doc.dev.python_scheduling.profile_matmul.matmul_fusion#L58-L62","kind":"function","name":"matmul_fusion","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":58,"end_line":62,"context_start_line":38,"context_end_line":82,"code":" total_in_gbs += _estimate_size(shape, dtype)\n return total_in_gbs\n\n\ndef get_kernel_time(prof_averages: torch.autograd.profiler_util.EventList):\n elapsed_cuda_time = 0\n has_cuda_event = False\n for event in prof_averages:\n if event.device_type != DeviceType.CUDA:\n continue\n has_cuda_event = True\n elapsed_cuda_time = (\n elapsed_cuda_time + event.self_device_time_total\n if hasattr(event, \"self_device_time_total\")\n else event.self_cuda_time_total\n )\n assert has_cuda_event, \"No CUDA events found\"\n return elapsed_cuda_time / 1e3\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\nclass MatmulDefinition(FusionDefinition):\n def __init__(self, inputs, config, verbose=False):\n super().__init__()\n self.inputs = inputs\n self.config = config\n self.verbose = verbose\n\n def definition(self):\n matmul_fusion(self, self.inputs)\n\n def schedule(self):\n assert self.config is not None\n status, error = self.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = self.sched.compute_matmul_heuristics()\n\n # Modify original parameters","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.MatmulDefinition","uri":"program://Fuser/class/doc.dev.python_scheduling.profile_matmul.MatmulDefinition#L65-L97","kind":"class","name":"MatmulDefinition","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":65,"end_line":97,"context_start_line":45,"context_end_line":117,"code":" for event in prof_averages:\n if event.device_type != DeviceType.CUDA:\n continue\n has_cuda_event = True\n elapsed_cuda_time = (\n elapsed_cuda_time + event.self_device_time_total\n if hasattr(event, \"self_device_time_total\")\n else event.self_cuda_time_total\n )\n assert has_cuda_event, \"No CUDA events found\"\n return elapsed_cuda_time / 1e3\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\nclass MatmulDefinition(FusionDefinition):\n def __init__(self, inputs, config, verbose=False):\n super().__init__()\n self.inputs = inputs\n self.config = config\n self.verbose = verbose\n\n def definition(self):\n matmul_fusion(self, self.inputs)\n\n def schedule(self):\n assert self.config is not None\n status, error = self.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = self.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n tile_sizes, macro, tile_order, cluster_dims, stages = self.config\n schedule_params.tile_sizes = tile_sizes\n schedule_params.mma_macro = macro.mma_macro()\n schedule_params.cta_order = tile_order\n schedule_params.cluster_dims = cluster_dims\n schedule_params.circular_buffering_strategy = (\n MatmulCircularBufferingStrategy.warp_specialized\n )\n schedule_params.circular_buffer_options.circular_buffer_smem_write = stages > 1\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n if self.verbose:\n print(schedule_params)\n\n # Schedule fusion\n self.sched.schedule()\n\n\ndef test_matmul_nvf(\n problem_config: tuple,\n schedule_config: tuple,\n verbose: bool = False,\n validate: bool = False,\n):\n m, n, k, layout = problem_config\n dtype = torch.bfloat16\n\n # NOTE reduced precision accumulation is not supported in nvFuser\n torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False\n torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False\n\n a = torch.randn(m, k, device=\"cuda\", dtype=dtype)\n b = torch.randn(k, n, device=\"cuda\", dtype=dtype)\n\n if layout == \"NT\" or layout == \"NN\":\n a = a.as_strided(size=[m, k], stride=[1, m])","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.test_matmul_nvf","uri":"program://Fuser/function/doc.dev.python_scheduling.profile_matmul.test_matmul_nvf#L100-L143","kind":"function","name":"test_matmul_nvf","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":100,"end_line":143,"context_start_line":80,"context_end_line":163,"code":" schedule_params = self.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n tile_sizes, macro, tile_order, cluster_dims, stages = self.config\n schedule_params.tile_sizes = tile_sizes\n schedule_params.mma_macro = macro.mma_macro()\n schedule_params.cta_order = tile_order\n schedule_params.cluster_dims = cluster_dims\n schedule_params.circular_buffering_strategy = (\n MatmulCircularBufferingStrategy.warp_specialized\n )\n schedule_params.circular_buffer_options.circular_buffer_smem_write = stages > 1\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n if self.verbose:\n print(schedule_params)\n\n # Schedule fusion\n self.sched.schedule()\n\n\ndef test_matmul_nvf(\n problem_config: tuple,\n schedule_config: tuple,\n verbose: bool = False,\n validate: bool = False,\n):\n m, n, k, layout = problem_config\n dtype = torch.bfloat16\n\n # NOTE reduced precision accumulation is not supported in nvFuser\n torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False\n torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False\n\n a = torch.randn(m, k, device=\"cuda\", dtype=dtype)\n b = torch.randn(k, n, device=\"cuda\", dtype=dtype)\n\n if layout == \"NT\" or layout == \"NN\":\n a = a.as_strided(size=[m, k], stride=[1, m])\n if layout == \"TN\" or layout == \"NN\":\n b = b.as_strided(size=[k, n], stride=[1, k])\n\n scheduled_fd = MatmulDefinition([a, b], schedule_config, verbose)\n\n try:\n nvf_outputs = scheduled_fd.execute([a, b], profile=True)\n except Exception as e:\n if verbose:\n print(e)\n return -1\n\n with profile(activities=[ProfilerActivity.CUDA], record_shapes=True) as prof:\n with record_function(\"matmul\"):\n baseline_output = torch.matmul(a, b)\n baseline_time = get_kernel_time(prof.key_averages())\n\n if validate:\n tolerance = k * 1e-6\n assert torch.allclose(\n nvf_outputs[0], baseline_output, atol=tolerance, rtol=tolerance\n )\n\n prof = scheduled_fd.profile()\n nvf_time = prof.kernel_profiles[0].time_ms\n return baseline_time, nvf_time\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser(\n description=\"\"\"Run through a combination of matmul parameters and compare relative performance against nvjet for a single problem.\"\"\",\n epilog=\"\"\"How to run script: NVFUSER_ENABLE=fuse_matmul NVFUSER_DISABLE=matmul_expr_eval python single_matmul.py nvjet_pybench.json 1752 4720 584 NN --verbose --validate\"\"\",\n )\n parser.add_argument(\"m\", type=int, help=\"The size of M dimension\")\n parser.add_argument(\"n\", type=int, help=\"The size of N dimension\")\n parser.add_argument(\"k\", type=int, help=\"The size of K dimension\")\n parser.add_argument(\n \"layout\",\n type=str,\n choices=[layout.name for layout in Layout],\n help=\"The layout for matmul problem.\",\n )\n parser.add_argument(\n \"--verbose\",","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.main","uri":"program://Fuser/function/doc.dev.python_scheduling.profile_matmul.main#L146-L207","kind":"function","name":"main","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":146,"end_line":207,"context_start_line":126,"context_end_line":211,"code":" if verbose:\n print(e)\n return -1\n\n with profile(activities=[ProfilerActivity.CUDA], record_shapes=True) as prof:\n with record_function(\"matmul\"):\n baseline_output = torch.matmul(a, b)\n baseline_time = get_kernel_time(prof.key_averages())\n\n if validate:\n tolerance = k * 1e-6\n assert torch.allclose(\n nvf_outputs[0], baseline_output, atol=tolerance, rtol=tolerance\n )\n\n prof = scheduled_fd.profile()\n nvf_time = prof.kernel_profiles[0].time_ms\n return baseline_time, nvf_time\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser(\n description=\"\"\"Run through a combination of matmul parameters and compare relative performance against nvjet for a single problem.\"\"\",\n epilog=\"\"\"How to run script: NVFUSER_ENABLE=fuse_matmul NVFUSER_DISABLE=matmul_expr_eval python single_matmul.py nvjet_pybench.json 1752 4720 584 NN --verbose --validate\"\"\",\n )\n parser.add_argument(\"m\", type=int, help=\"The size of M dimension\")\n parser.add_argument(\"n\", type=int, help=\"The size of N dimension\")\n parser.add_argument(\"k\", type=int, help=\"The size of K dimension\")\n parser.add_argument(\n \"layout\",\n type=str,\n choices=[layout.name for layout in Layout],\n help=\"The layout for matmul problem.\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"Print matmul parameters and exceptions.\",\n )\n parser.add_argument(\n \"--validate\",\n action=\"store_true\",\n help=\"Validate nvfuser against pytorch matmul.\",\n )\n args = parser.parse_args()\n\n problem_config = (args.m, args.n, args.k, args.layout)\n device_properties = torch.cuda.get_device_properties(0)\n # short-circuit: problem does not fit on device\n if (\n estimate_matmul_size(problem_config, torch.bfloat16)\n >= device_properties.total_memory\n ):\n assert False\n\n # These are the parameters we'll optimize\n parameter_configurations = {\n \"tile_sizes\": [\n MatMulTileOptions(GemmTile(128, 256, 64), GemmTile(64, 256, 64))\n ],\n \"mma_macro\": [MmaMacroEncode(MmaMacroArch.hopper, 64, 256, 16)],\n \"tile_order\": [MatmulTileRasterizationOrder.column_major],\n \"cluster_dims\": [ClusterDims(1, 1, 1)],\n \"circular_buffer_stages\": [4],\n }\n\n print(\n f\"problem configuration, m: {args.m}, n: {args.n}, k: {args.k}, layout: {args.layout}\"\n )\n for idx, scheduler_config in enumerate(\n itertools.product(*parameter_configurations.values())\n ):\n baseline_result, nvf_result = test_matmul_nvf(\n problem_config, scheduler_config, args.verbose, args.validate\n )\n normalized_result = baseline_result / nvf_result\n print(\n f\"index: {idx}, baseline(us): {baseline_result: .3e}, \"\n f\"nvfuser(us): {nvf_result: 3e}, normalized(us): {normalized_result: 2f}\"\n )\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul._estimate_size","uri":"program://Fuser/function/doc.dev.python_scheduling.profile_matmul._estimate_size#L32-L33","kind":"function","name":"_estimate_size","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":32,"end_line":33,"context_start_line":12,"context_end_line":53,"code":" MmaMacroArch,\n MatmulTileRasterizationOrder,\n MatmulCircularBufferingStrategy,\n)\nimport torch\nfrom torch.autograd import DeviceType\nfrom torch.profiler import profile, record_function, ProfilerActivity\nimport math\nimport itertools\nfrom enum import IntEnum\n\n\nclass Layout(IntEnum):\n NN = 0\n NT = 1\n TN = 2\n TT = 3\n\n\ndef estimate_matmul_size(config, dtype):\n def _estimate_size(shape, dtype):\n return math.prod(shape) * dtype.itemsize\n\n m, n, k, layout = config\n total_in_gbs = 0\n for shape in [[m, k], [n, k], [m, n]]:\n total_in_gbs += _estimate_size(shape, dtype)\n return total_in_gbs\n\n\ndef get_kernel_time(prof_averages: torch.autograd.profiler_util.EventList):\n elapsed_cuda_time = 0\n has_cuda_event = False\n for event in prof_averages:\n if event.device_type != DeviceType.CUDA:\n continue\n has_cuda_event = True\n elapsed_cuda_time = (\n elapsed_cuda_time + event.self_device_time_total\n if hasattr(event, \"self_device_time_total\")\n else event.self_cuda_time_total\n )","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.__init__","uri":"program://Fuser/function/doc.dev.python_scheduling.profile_matmul.__init__#L66-L70","kind":"function","name":"__init__","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":66,"end_line":70,"context_start_line":46,"context_end_line":90,"code":" if event.device_type != DeviceType.CUDA:\n continue\n has_cuda_event = True\n elapsed_cuda_time = (\n elapsed_cuda_time + event.self_device_time_total\n if hasattr(event, \"self_device_time_total\")\n else event.self_cuda_time_total\n )\n assert has_cuda_event, \"No CUDA events found\"\n return elapsed_cuda_time / 1e3\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\nclass MatmulDefinition(FusionDefinition):\n def __init__(self, inputs, config, verbose=False):\n super().__init__()\n self.inputs = inputs\n self.config = config\n self.verbose = verbose\n\n def definition(self):\n matmul_fusion(self, self.inputs)\n\n def schedule(self):\n assert self.config is not None\n status, error = self.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = self.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n tile_sizes, macro, tile_order, cluster_dims, stages = self.config\n schedule_params.tile_sizes = tile_sizes\n schedule_params.mma_macro = macro.mma_macro()\n schedule_params.cta_order = tile_order\n schedule_params.cluster_dims = cluster_dims\n schedule_params.circular_buffering_strategy = (\n MatmulCircularBufferingStrategy.warp_specialized\n )","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.definition","uri":"program://Fuser/function/doc.dev.python_scheduling.profile_matmul.definition#L72-L73","kind":"function","name":"definition","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":72,"end_line":73,"context_start_line":52,"context_end_line":93,"code":" else event.self_cuda_time_total\n )\n assert has_cuda_event, \"No CUDA events found\"\n return elapsed_cuda_time / 1e3\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\nclass MatmulDefinition(FusionDefinition):\n def __init__(self, inputs, config, verbose=False):\n super().__init__()\n self.inputs = inputs\n self.config = config\n self.verbose = verbose\n\n def definition(self):\n matmul_fusion(self, self.inputs)\n\n def schedule(self):\n assert self.config is not None\n status, error = self.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = self.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n tile_sizes, macro, tile_order, cluster_dims, stages = self.config\n schedule_params.tile_sizes = tile_sizes\n schedule_params.mma_macro = macro.mma_macro()\n schedule_params.cta_order = tile_order\n schedule_params.cluster_dims = cluster_dims\n schedule_params.circular_buffering_strategy = (\n MatmulCircularBufferingStrategy.warp_specialized\n )\n schedule_params.circular_buffer_options.circular_buffer_smem_write = stages > 1\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n if self.verbose:","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.profile_matmul.schedule","uri":"program://Fuser/function/doc.dev.python_scheduling.profile_matmul.schedule#L75-L97","kind":"function","name":"schedule","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":75,"end_line":97,"context_start_line":55,"context_end_line":117,"code":" return elapsed_cuda_time / 1e3\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\nclass MatmulDefinition(FusionDefinition):\n def __init__(self, inputs, config, verbose=False):\n super().__init__()\n self.inputs = inputs\n self.config = config\n self.verbose = verbose\n\n def definition(self):\n matmul_fusion(self, self.inputs)\n\n def schedule(self):\n assert self.config is not None\n status, error = self.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = self.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n tile_sizes, macro, tile_order, cluster_dims, stages = self.config\n schedule_params.tile_sizes = tile_sizes\n schedule_params.mma_macro = macro.mma_macro()\n schedule_params.cta_order = tile_order\n schedule_params.cluster_dims = cluster_dims\n schedule_params.circular_buffering_strategy = (\n MatmulCircularBufferingStrategy.warp_specialized\n )\n schedule_params.circular_buffer_options.circular_buffer_smem_write = stages > 1\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n if self.verbose:\n print(schedule_params)\n\n # Schedule fusion\n self.sched.schedule()\n\n\ndef test_matmul_nvf(\n problem_config: tuple,\n schedule_config: tuple,\n verbose: bool = False,\n validate: bool = False,\n):\n m, n, k, layout = problem_config\n dtype = torch.bfloat16\n\n # NOTE reduced precision accumulation is not supported in nvFuser\n torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False\n torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False\n\n a = torch.randn(m, k, device=\"cuda\", dtype=dtype)\n b = torch.randn(k, n, device=\"cuda\", dtype=dtype)\n\n if layout == \"NT\" or layout == \"NN\":\n a = a.as_strided(size=[m, k], stride=[1, m])","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils","uri":"program://Fuser/module/doc.dev.python_scheduling.autotune_utils#L1-L311","kind":"module","name":"doc.dev.python_scheduling.autotune_utils","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":1,"end_line":311,"context_start_line":1,"context_end_line":311,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport math\nimport itertools\nfrom nvfuser import FusionCache, FusionDefinition\nfrom dataclasses import dataclass, astuple\n\n# ================================ Description ================================\n# This file contains the utility function for autotuning scripts.\n# =============================================================================\n\n\n# Returns the result of a/b rounded to the nearest integer in the direction of\n# positive infinity.\ndef ceil_div(a, b):\n return int(math.ceil(a / b))\n\n\n# Returns the result of a/b rounded to the nearest integer in the direction of\n# negative infinity.\ndef floor_div(a, b):\n return int(math.floor(a / b))\n\n\n@dataclass\nclass ScriptConfiguration:\n # Settings for input tensor generation\n # number of dimensions in the tensor argument\n num_dimensions: int\n\n # the data type for the tensor argument\n tensor_datatype: torch.dtype\n\n # During training, the cartesian product of outer_shapes and inner_shapes\n # is used to define the shape of the input tensor arguments.\n outer_shapes: [int]\n inner_shapes: [int]\n\n # We profile a range of input shapes with various configurations.\n # This argument determines how much of the profiled data to keep as a test\n # set.\n test_data_percentage: [float]\n\n # The selected batch size for empirical and nvfuser comparison.\n empirical_batch_size: [int]\n\n # The range of hidden sizes for empirical and nvfuser comparision.\n empirical_hidden_sizes: [int]\n\n\n# Converted DataClass to a Tuple. It flattens nested tuples. The function is\n# used for compatibility with machine learning model.\ndef flatten_configuration(scheduler_config):\n new_scheduler_config = []\n for item in astuple(scheduler_config):\n if type(item) is tuple:\n new_scheduler_config.extend(item)\n else:\n new_scheduler_config.append(item)\n return tuple(new_scheduler_config)\n\n\n# Collect data for machine learning\ndef collect_data(script_config, autotune_config):\n parameters = []\n performance = []\n\n for shape in itertools.product(\n script_config.outer_shapes, script_config.inner_shapes\n ):\n print(shape)\n inputs = autotune_config.create_inputs(shape, script_config.tensor_datatype)\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n # unroll and vectorization configurations\n for parameter_config in autotune_config.generate_scheduler_configurations(\n shape\n ):\n perf_metric, _ = run_profile(\n autotune_config, presched_fd, inputs, parameter_config\n )\n parameters.append((*shape, *flatten_configuration(parameter_config)))\n performance.append(perf_metric)\n return parameters, performance\n\n\n# Separate collected data into training and test sets\ndef separate_data(script_config, parameters, performance):\n import random\n\n train_inputs = []\n test_inputs = []\n train_perf = []\n test_perf = []\n test_shapes = set()\n all_test_scheduler_config = {} # key: input_shape, value: (scheduler_config, perf)\n\n for data, perf in zip(parameters, performance):\n shape = data[: script_config.num_dimensions]\n scheduler_config = data[script_config.num_dimensions :]\n\n if shape in all_test_scheduler_config:\n all_test_scheduler_config[shape][scheduler_config] = perf\n else:\n all_test_scheduler_config[shape] = {scheduler_config: perf}\n\n if (\n script_config.test_data_percentage > 0\n and random.random() < script_config.test_data_percentage\n ):\n test_shapes.add(shape)\n test_inputs.append(data)\n test_perf.append(perf)\n else:\n train_inputs.append(data)\n train_perf.append(perf)\n\n # key: input_shape, value: best_scheduler_config\n best_test_scheduler_config = {\n shape: argmax(all_test_scheduler_config[shape]) for shape in test_shapes\n }\n\n return (train_inputs, train_perf), (\n test_inputs,\n test_perf,\n test_shapes,\n best_test_scheduler_config,\n )\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(autotune_config, presched_fd, inputs, scheduler_config=None):\n scheduled_fd = autotune_config.custom_scheduler(presched_fd, scheduler_config)\n nvf_outputs = scheduled_fd.execute(inputs, profile=True)\n\n # validate correctness\n assert torch.allclose(\n nvf_outputs[0], autotune_config.eager_reference(inputs), atol=1e-2, rtol=1e-2\n )\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\n# Given a map from scheduler configuration to predicted performance, find the\n# configuration with the maximum predicted performance\ndef argmax(map_scheduler_config_to_perf):\n best_perf = -1\n best_scheduler_config = None\n for scheduler_config, perf in map_scheduler_config_to_perf.items():\n if perf > best_perf:\n best_perf = perf\n best_scheduler_config = scheduler_config\n return best_scheduler_config\n\n\n# Given a prediction model, input_shape, and set of parameter configurations,\n# find the best parameters\ndef find_best_parameters(clf, input_shape, scheduler_configurations):\n map_scheduler_config_to_performance = {\n scheduler_config: clf.predict(\n [[*input_shape, *flatten_configuration(scheduler_config)]]\n )\n for scheduler_config in scheduler_configurations\n }\n return argmax(map_scheduler_config_to_performance)\n\n\n# Measure model performance with RMSE\ndef test_model_rmse(clf, script_config, autotune_config, test_data):\n test_inputs, test_perf, test_shapes, best_test_scheduler_config = test_data\n test_pred = clf.predict(test_inputs)\n\n # Estimate prediction error with RMSE\n import numpy as np\n\n test_perf = np.array(test_perf)\n print(\n \"Test prediction error (RMSE)\",\n np.sqrt(np.mean(np.power(test_perf - test_pred, 2))),\n )\n print(\"Test performance\", test_perf)\n print(\"Test prediction\", test_pred)\n\n print(\"======================= compare configurations =======================\")\n # Find best configuration for test_shapes\n print(\"input shape, estimate_config, actual_config, correct\")\n correctness_count = 0\n mismatch_configs = []\n for shape in test_shapes:\n estimate_config = find_best_parameters(\n clf, shape, autotune_config.generate_scheduler_configurations(shape)\n )\n\n match_config = (\n flatten_configuration(estimate_config) == best_test_scheduler_config[shape]\n )\n if not match_config:\n mismatch_configs.append((shape, estimate_config))\n\n correctness_count += int(match_config)\n print(\n f\"{shape}, {estimate_config}, {best_test_scheduler_config[shape]}, {match_config}\"\n )\n print(\n \"% of predictions match nvfuser parameters\",\n correctness_count / len(test_shapes),\n )\n print(correctness_count, \"out of\", len(test_shapes))\n\n print(\"======================= compare performance =========================\")\n\n for shape, estimate_config in mismatch_configs:\n inputs = autotune_config.create_inputs(shape, script_config.tensor_datatype)\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n _, est_perf = run_profile(autotune_config, presched_fd, inputs, estimate_config)\n _, nvf_perf = run_profile(autotune_config, presched_fd, inputs)\n est_perf_faster = est_perf < nvf_perf\n print(\n f\"{shape} \\t estimate_perf: {est_perf: .5f} \\t nvfuser_perf: {nvf_perf: .5f} \\t is_estimated_config_faster: {est_perf_faster}\"\n )\n print(\"=====================================================================\")\n\n\n# Given a machine learning model, compare the performance of its predicted configuration\n# against nvfuser on a given fusion\ndef test_model(clf, script_config, autotune_config):\n # For a specific batch size, gather performance across a range of hidden sizes.\n # Calculate performance for best predicted and nvfuser configurations. Plot a\n # chart comparing performance using matplotlib.\n\n # NOTE: The matplotlib experiment plots the kernel runtime, which could be\n # different than the selected performance metric. Currently, the performance\n # metric is effective_bandwidth_gbs.\n\n import matplotlib.pyplot as plt\n import numpy as np\n\n FusionCache.reset()\n est_perfs = []\n for hidden_shape in script_config.empirical_hidden_sizes:\n inputs = autotune_config.create_inputs(\n (script_config.empirical_batch_size, hidden_shape),\n script_config.tensor_datatype,\n )\n\n estimate_config = find_best_parameters(\n clf,\n (script_config.empirical_batch_size, hidden_shape),\n autotune_config.generate_scheduler_configurations(\n (script_config.empirical_batch_size, hidden_shape)\n ),\n )\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n _, est_time_ms = run_profile(\n autotune_config, presched_fd, inputs, estimate_config\n )\n est_perfs.append(est_time_ms)\n print(\n f\"{script_config.empirical_batch_size}, {hidden_shape}, {estimate_config}, {est_time_ms: .3f}\"\n )\n\n FusionCache.reset()\n nvf_perfs = []\n for hidden_shape in script_config.empirical_hidden_sizes:\n inputs = autotune_config.create_inputs(\n (script_config.empirical_batch_size, hidden_shape),\n script_config.tensor_datatype,\n )\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n _, nvf_time_ms = run_profile(autotune_config, presched_fd, inputs)\n nvf_perfs.append(nvf_time_ms)\n print(\n f\"{script_config.empirical_batch_size}, {hidden_shape}, {nvf_time_ms: .3f}\"\n )\n\n # Get mean speed-up from nvfuser to empirical configurations across all input shapes.\n # Negative value mean empirical configurations are slower than nvfuser.\n print(\"Mean speed-up\", np.mean(np.array(nvf_perfs) - np.array(est_perfs)))\n\n np_hidden_size = np.array(script_config.empirical_hidden_sizes)\n plt.plot(np_hidden_size, np.array(est_perfs))\n plt.plot(np_hidden_size, np.array(nvf_perfs))\n\n plt.xlabel(\"Hidden Size\")\n plt.ylabel(\"Time(ms)\")\n plt.title(\n f\"Batch Size = {script_config.empirical_batch_size}, Compare Machine Learning Heuristic vs NvFuser\"\n )\n plt.legend([\"random_forest\", \"nvfuser\"], loc=\"lower right\")\n plt.savefig(\n f\"{autotune_config}_empirical_batch_size_{script_config.empirical_batch_size}.png\"\n )\n plt.close(\"all\")","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.ceil_div","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.ceil_div#L19-L20","kind":"function","name":"ceil_div","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":19,"end_line":20,"context_start_line":1,"context_end_line":40,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport math\nimport itertools\nfrom nvfuser import FusionCache, FusionDefinition\nfrom dataclasses import dataclass, astuple\n\n# ================================ Description ================================\n# This file contains the utility function for autotuning scripts.\n# =============================================================================\n\n\n# Returns the result of a/b rounded to the nearest integer in the direction of\n# positive infinity.\ndef ceil_div(a, b):\n return int(math.ceil(a / b))\n\n\n# Returns the result of a/b rounded to the nearest integer in the direction of\n# negative infinity.\ndef floor_div(a, b):\n return int(math.floor(a / b))\n\n\n@dataclass\nclass ScriptConfiguration:\n # Settings for input tensor generation\n # number of dimensions in the tensor argument\n num_dimensions: int\n\n # the data type for the tensor argument\n tensor_datatype: torch.dtype\n\n # During training, the cartesian product of outer_shapes and inner_shapes\n # is used to define the shape of the input tensor arguments.\n outer_shapes: [int]","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.floor_div","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.floor_div#L25-L26","kind":"function","name":"floor_div","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":25,"end_line":26,"context_start_line":5,"context_end_line":46,"code":"\nimport torch\nimport math\nimport itertools\nfrom nvfuser import FusionCache, FusionDefinition\nfrom dataclasses import dataclass, astuple\n\n# ================================ Description ================================\n# This file contains the utility function for autotuning scripts.\n# =============================================================================\n\n\n# Returns the result of a/b rounded to the nearest integer in the direction of\n# positive infinity.\ndef ceil_div(a, b):\n return int(math.ceil(a / b))\n\n\n# Returns the result of a/b rounded to the nearest integer in the direction of\n# negative infinity.\ndef floor_div(a, b):\n return int(math.floor(a / b))\n\n\n@dataclass\nclass ScriptConfiguration:\n # Settings for input tensor generation\n # number of dimensions in the tensor argument\n num_dimensions: int\n\n # the data type for the tensor argument\n tensor_datatype: torch.dtype\n\n # During training, the cartesian product of outer_shapes and inner_shapes\n # is used to define the shape of the input tensor arguments.\n outer_shapes: [int]\n inner_shapes: [int]\n\n # We profile a range of input shapes with various configurations.\n # This argument determines how much of the profiled data to keep as a test\n # set.\n test_data_percentage: [float]","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.ScriptConfiguration","uri":"program://Fuser/class/doc.dev.python_scheduling.autotune_utils.ScriptConfiguration#L30-L52","kind":"class","name":"ScriptConfiguration","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":30,"end_line":52,"context_start_line":10,"context_end_line":72,"code":"from dataclasses import dataclass, astuple\n\n# ================================ Description ================================\n# This file contains the utility function for autotuning scripts.\n# =============================================================================\n\n\n# Returns the result of a/b rounded to the nearest integer in the direction of\n# positive infinity.\ndef ceil_div(a, b):\n return int(math.ceil(a / b))\n\n\n# Returns the result of a/b rounded to the nearest integer in the direction of\n# negative infinity.\ndef floor_div(a, b):\n return int(math.floor(a / b))\n\n\n@dataclass\nclass ScriptConfiguration:\n # Settings for input tensor generation\n # number of dimensions in the tensor argument\n num_dimensions: int\n\n # the data type for the tensor argument\n tensor_datatype: torch.dtype\n\n # During training, the cartesian product of outer_shapes and inner_shapes\n # is used to define the shape of the input tensor arguments.\n outer_shapes: [int]\n inner_shapes: [int]\n\n # We profile a range of input shapes with various configurations.\n # This argument determines how much of the profiled data to keep as a test\n # set.\n test_data_percentage: [float]\n\n # The selected batch size for empirical and nvfuser comparison.\n empirical_batch_size: [int]\n\n # The range of hidden sizes for empirical and nvfuser comparision.\n empirical_hidden_sizes: [int]\n\n\n# Converted DataClass to a Tuple. It flattens nested tuples. The function is\n# used for compatibility with machine learning model.\ndef flatten_configuration(scheduler_config):\n new_scheduler_config = []\n for item in astuple(scheduler_config):\n if type(item) is tuple:\n new_scheduler_config.extend(item)\n else:\n new_scheduler_config.append(item)\n return tuple(new_scheduler_config)\n\n\n# Collect data for machine learning\ndef collect_data(script_config, autotune_config):\n parameters = []\n performance = []\n\n for shape in itertools.product(","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.flatten_configuration","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.flatten_configuration#L57-L64","kind":"function","name":"flatten_configuration","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":57,"end_line":64,"context_start_line":37,"context_end_line":84,"code":"\n # During training, the cartesian product of outer_shapes and inner_shapes\n # is used to define the shape of the input tensor arguments.\n outer_shapes: [int]\n inner_shapes: [int]\n\n # We profile a range of input shapes with various configurations.\n # This argument determines how much of the profiled data to keep as a test\n # set.\n test_data_percentage: [float]\n\n # The selected batch size for empirical and nvfuser comparison.\n empirical_batch_size: [int]\n\n # The range of hidden sizes for empirical and nvfuser comparision.\n empirical_hidden_sizes: [int]\n\n\n# Converted DataClass to a Tuple. It flattens nested tuples. The function is\n# used for compatibility with machine learning model.\ndef flatten_configuration(scheduler_config):\n new_scheduler_config = []\n for item in astuple(scheduler_config):\n if type(item) is tuple:\n new_scheduler_config.extend(item)\n else:\n new_scheduler_config.append(item)\n return tuple(new_scheduler_config)\n\n\n# Collect data for machine learning\ndef collect_data(script_config, autotune_config):\n parameters = []\n performance = []\n\n for shape in itertools.product(\n script_config.outer_shapes, script_config.inner_shapes\n ):\n print(shape)\n inputs = autotune_config.create_inputs(shape, script_config.tensor_datatype)\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n # unroll and vectorization configurations\n for parameter_config in autotune_config.generate_scheduler_configurations(\n shape\n ):","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.collect_data","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.collect_data#L68-L90","kind":"function","name":"collect_data","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":68,"end_line":90,"context_start_line":48,"context_end_line":110,"code":" # The selected batch size for empirical and nvfuser comparison.\n empirical_batch_size: [int]\n\n # The range of hidden sizes for empirical and nvfuser comparision.\n empirical_hidden_sizes: [int]\n\n\n# Converted DataClass to a Tuple. It flattens nested tuples. The function is\n# used for compatibility with machine learning model.\ndef flatten_configuration(scheduler_config):\n new_scheduler_config = []\n for item in astuple(scheduler_config):\n if type(item) is tuple:\n new_scheduler_config.extend(item)\n else:\n new_scheduler_config.append(item)\n return tuple(new_scheduler_config)\n\n\n# Collect data for machine learning\ndef collect_data(script_config, autotune_config):\n parameters = []\n performance = []\n\n for shape in itertools.product(\n script_config.outer_shapes, script_config.inner_shapes\n ):\n print(shape)\n inputs = autotune_config.create_inputs(shape, script_config.tensor_datatype)\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n # unroll and vectorization configurations\n for parameter_config in autotune_config.generate_scheduler_configurations(\n shape\n ):\n perf_metric, _ = run_profile(\n autotune_config, presched_fd, inputs, parameter_config\n )\n parameters.append((*shape, *flatten_configuration(parameter_config)))\n performance.append(perf_metric)\n return parameters, performance\n\n\n# Separate collected data into training and test sets\ndef separate_data(script_config, parameters, performance):\n import random\n\n train_inputs = []\n test_inputs = []\n train_perf = []\n test_perf = []\n test_shapes = set()\n all_test_scheduler_config = {} # key: input_shape, value: (scheduler_config, perf)\n\n for data, perf in zip(parameters, performance):\n shape = data[: script_config.num_dimensions]\n scheduler_config = data[script_config.num_dimensions :]\n\n if shape in all_test_scheduler_config:\n all_test_scheduler_config[shape][scheduler_config] = perf\n else:","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.separate_data","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.separate_data#L94-L134","kind":"function","name":"separate_data","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":94,"end_line":134,"context_start_line":74,"context_end_line":154,"code":" ):\n print(shape)\n inputs = autotune_config.create_inputs(shape, script_config.tensor_datatype)\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n # unroll and vectorization configurations\n for parameter_config in autotune_config.generate_scheduler_configurations(\n shape\n ):\n perf_metric, _ = run_profile(\n autotune_config, presched_fd, inputs, parameter_config\n )\n parameters.append((*shape, *flatten_configuration(parameter_config)))\n performance.append(perf_metric)\n return parameters, performance\n\n\n# Separate collected data into training and test sets\ndef separate_data(script_config, parameters, performance):\n import random\n\n train_inputs = []\n test_inputs = []\n train_perf = []\n test_perf = []\n test_shapes = set()\n all_test_scheduler_config = {} # key: input_shape, value: (scheduler_config, perf)\n\n for data, perf in zip(parameters, performance):\n shape = data[: script_config.num_dimensions]\n scheduler_config = data[script_config.num_dimensions :]\n\n if shape in all_test_scheduler_config:\n all_test_scheduler_config[shape][scheduler_config] = perf\n else:\n all_test_scheduler_config[shape] = {scheduler_config: perf}\n\n if (\n script_config.test_data_percentage > 0\n and random.random() < script_config.test_data_percentage\n ):\n test_shapes.add(shape)\n test_inputs.append(data)\n test_perf.append(perf)\n else:\n train_inputs.append(data)\n train_perf.append(perf)\n\n # key: input_shape, value: best_scheduler_config\n best_test_scheduler_config = {\n shape: argmax(all_test_scheduler_config[shape]) for shape in test_shapes\n }\n\n return (train_inputs, train_perf), (\n test_inputs,\n test_perf,\n test_shapes,\n best_test_scheduler_config,\n )\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(autotune_config, presched_fd, inputs, scheduler_config=None):\n scheduled_fd = autotune_config.custom_scheduler(presched_fd, scheduler_config)\n nvf_outputs = scheduled_fd.execute(inputs, profile=True)\n\n # validate correctness\n assert torch.allclose(\n nvf_outputs[0], autotune_config.eager_reference(inputs), atol=1e-2, rtol=1e-2\n )\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\n# Given a map from scheduler configuration to predicted performance, find the\n# configuration with the maximum predicted performance","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.run_profile","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.run_profile#L138-L150","kind":"function","name":"run_profile","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":138,"end_line":150,"context_start_line":118,"context_end_line":170,"code":" test_inputs.append(data)\n test_perf.append(perf)\n else:\n train_inputs.append(data)\n train_perf.append(perf)\n\n # key: input_shape, value: best_scheduler_config\n best_test_scheduler_config = {\n shape: argmax(all_test_scheduler_config[shape]) for shape in test_shapes\n }\n\n return (train_inputs, train_perf), (\n test_inputs,\n test_perf,\n test_shapes,\n best_test_scheduler_config,\n )\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(autotune_config, presched_fd, inputs, scheduler_config=None):\n scheduled_fd = autotune_config.custom_scheduler(presched_fd, scheduler_config)\n nvf_outputs = scheduled_fd.execute(inputs, profile=True)\n\n # validate correctness\n assert torch.allclose(\n nvf_outputs[0], autotune_config.eager_reference(inputs), atol=1e-2, rtol=1e-2\n )\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\n# Given a map from scheduler configuration to predicted performance, find the\n# configuration with the maximum predicted performance\ndef argmax(map_scheduler_config_to_perf):\n best_perf = -1\n best_scheduler_config = None\n for scheduler_config, perf in map_scheduler_config_to_perf.items():\n if perf > best_perf:\n best_perf = perf\n best_scheduler_config = scheduler_config\n return best_scheduler_config\n\n\n# Given a prediction model, input_shape, and set of parameter configurations,\n# find the best parameters\ndef find_best_parameters(clf, input_shape, scheduler_configurations):\n map_scheduler_config_to_performance = {\n scheduler_config: clf.predict(\n [[*input_shape, *flatten_configuration(scheduler_config)]]","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.argmax","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.argmax#L155-L162","kind":"function","name":"argmax","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":155,"end_line":162,"context_start_line":135,"context_end_line":182,"code":"\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(autotune_config, presched_fd, inputs, scheduler_config=None):\n scheduled_fd = autotune_config.custom_scheduler(presched_fd, scheduler_config)\n nvf_outputs = scheduled_fd.execute(inputs, profile=True)\n\n # validate correctness\n assert torch.allclose(\n nvf_outputs[0], autotune_config.eager_reference(inputs), atol=1e-2, rtol=1e-2\n )\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\n# Given a map from scheduler configuration to predicted performance, find the\n# configuration with the maximum predicted performance\ndef argmax(map_scheduler_config_to_perf):\n best_perf = -1\n best_scheduler_config = None\n for scheduler_config, perf in map_scheduler_config_to_perf.items():\n if perf > best_perf:\n best_perf = perf\n best_scheduler_config = scheduler_config\n return best_scheduler_config\n\n\n# Given a prediction model, input_shape, and set of parameter configurations,\n# find the best parameters\ndef find_best_parameters(clf, input_shape, scheduler_configurations):\n map_scheduler_config_to_performance = {\n scheduler_config: clf.predict(\n [[*input_shape, *flatten_configuration(scheduler_config)]]\n )\n for scheduler_config in scheduler_configurations\n }\n return argmax(map_scheduler_config_to_performance)\n\n\n# Measure model performance with RMSE\ndef test_model_rmse(clf, script_config, autotune_config, test_data):\n test_inputs, test_perf, test_shapes, best_test_scheduler_config = test_data\n test_pred = clf.predict(test_inputs)\n\n # Estimate prediction error with RMSE","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.find_best_parameters","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.find_best_parameters#L167-L174","kind":"function","name":"find_best_parameters","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":167,"end_line":174,"context_start_line":147,"context_end_line":194,"code":" prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\n# Given a map from scheduler configuration to predicted performance, find the\n# configuration with the maximum predicted performance\ndef argmax(map_scheduler_config_to_perf):\n best_perf = -1\n best_scheduler_config = None\n for scheduler_config, perf in map_scheduler_config_to_perf.items():\n if perf > best_perf:\n best_perf = perf\n best_scheduler_config = scheduler_config\n return best_scheduler_config\n\n\n# Given a prediction model, input_shape, and set of parameter configurations,\n# find the best parameters\ndef find_best_parameters(clf, input_shape, scheduler_configurations):\n map_scheduler_config_to_performance = {\n scheduler_config: clf.predict(\n [[*input_shape, *flatten_configuration(scheduler_config)]]\n )\n for scheduler_config in scheduler_configurations\n }\n return argmax(map_scheduler_config_to_performance)\n\n\n# Measure model performance with RMSE\ndef test_model_rmse(clf, script_config, autotune_config, test_data):\n test_inputs, test_perf, test_shapes, best_test_scheduler_config = test_data\n test_pred = clf.predict(test_inputs)\n\n # Estimate prediction error with RMSE\n import numpy as np\n\n test_perf = np.array(test_perf)\n print(\n \"Test prediction error (RMSE)\",\n np.sqrt(np.mean(np.power(test_perf - test_pred, 2))),\n )\n print(\"Test performance\", test_perf)\n print(\"Test prediction\", test_pred)\n\n print(\"======================= compare configurations =======================\")\n # Find best configuration for test_shapes","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.test_model_rmse","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.test_model_rmse#L178-L233","kind":"function","name":"test_model_rmse","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":178,"end_line":233,"context_start_line":158,"context_end_line":253,"code":" for scheduler_config, perf in map_scheduler_config_to_perf.items():\n if perf > best_perf:\n best_perf = perf\n best_scheduler_config = scheduler_config\n return best_scheduler_config\n\n\n# Given a prediction model, input_shape, and set of parameter configurations,\n# find the best parameters\ndef find_best_parameters(clf, input_shape, scheduler_configurations):\n map_scheduler_config_to_performance = {\n scheduler_config: clf.predict(\n [[*input_shape, *flatten_configuration(scheduler_config)]]\n )\n for scheduler_config in scheduler_configurations\n }\n return argmax(map_scheduler_config_to_performance)\n\n\n# Measure model performance with RMSE\ndef test_model_rmse(clf, script_config, autotune_config, test_data):\n test_inputs, test_perf, test_shapes, best_test_scheduler_config = test_data\n test_pred = clf.predict(test_inputs)\n\n # Estimate prediction error with RMSE\n import numpy as np\n\n test_perf = np.array(test_perf)\n print(\n \"Test prediction error (RMSE)\",\n np.sqrt(np.mean(np.power(test_perf - test_pred, 2))),\n )\n print(\"Test performance\", test_perf)\n print(\"Test prediction\", test_pred)\n\n print(\"======================= compare configurations =======================\")\n # Find best configuration for test_shapes\n print(\"input shape, estimate_config, actual_config, correct\")\n correctness_count = 0\n mismatch_configs = []\n for shape in test_shapes:\n estimate_config = find_best_parameters(\n clf, shape, autotune_config.generate_scheduler_configurations(shape)\n )\n\n match_config = (\n flatten_configuration(estimate_config) == best_test_scheduler_config[shape]\n )\n if not match_config:\n mismatch_configs.append((shape, estimate_config))\n\n correctness_count += int(match_config)\n print(\n f\"{shape}, {estimate_config}, {best_test_scheduler_config[shape]}, {match_config}\"\n )\n print(\n \"% of predictions match nvfuser parameters\",\n correctness_count / len(test_shapes),\n )\n print(correctness_count, \"out of\", len(test_shapes))\n\n print(\"======================= compare performance =========================\")\n\n for shape, estimate_config in mismatch_configs:\n inputs = autotune_config.create_inputs(shape, script_config.tensor_datatype)\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n _, est_perf = run_profile(autotune_config, presched_fd, inputs, estimate_config)\n _, nvf_perf = run_profile(autotune_config, presched_fd, inputs)\n est_perf_faster = est_perf < nvf_perf\n print(\n f\"{shape} \\t estimate_perf: {est_perf: .5f} \\t nvfuser_perf: {nvf_perf: .5f} \\t is_estimated_config_faster: {est_perf_faster}\"\n )\n print(\"=====================================================================\")\n\n\n# Given a machine learning model, compare the performance of its predicted configuration\n# against nvfuser on a given fusion\ndef test_model(clf, script_config, autotune_config):\n # For a specific batch size, gather performance across a range of hidden sizes.\n # Calculate performance for best predicted and nvfuser configurations. Plot a\n # chart comparing performance using matplotlib.\n\n # NOTE: The matplotlib experiment plots the kernel runtime, which could be\n # different than the selected performance metric. Currently, the performance\n # metric is effective_bandwidth_gbs.\n\n import matplotlib.pyplot as plt\n import numpy as np\n\n FusionCache.reset()\n est_perfs = []\n for hidden_shape in script_config.empirical_hidden_sizes:\n inputs = autotune_config.create_inputs(","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_utils.test_model","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_utils.test_model#L238-L311","kind":"function","name":"test_model","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":238,"end_line":311,"context_start_line":218,"context_end_line":311,"code":"\n print(\"======================= compare performance =========================\")\n\n for shape, estimate_config in mismatch_configs:\n inputs = autotune_config.create_inputs(shape, script_config.tensor_datatype)\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n _, est_perf = run_profile(autotune_config, presched_fd, inputs, estimate_config)\n _, nvf_perf = run_profile(autotune_config, presched_fd, inputs)\n est_perf_faster = est_perf < nvf_perf\n print(\n f\"{shape} \\t estimate_perf: {est_perf: .5f} \\t nvfuser_perf: {nvf_perf: .5f} \\t is_estimated_config_faster: {est_perf_faster}\"\n )\n print(\"=====================================================================\")\n\n\n# Given a machine learning model, compare the performance of its predicted configuration\n# against nvfuser on a given fusion\ndef test_model(clf, script_config, autotune_config):\n # For a specific batch size, gather performance across a range of hidden sizes.\n # Calculate performance for best predicted and nvfuser configurations. Plot a\n # chart comparing performance using matplotlib.\n\n # NOTE: The matplotlib experiment plots the kernel runtime, which could be\n # different than the selected performance metric. Currently, the performance\n # metric is effective_bandwidth_gbs.\n\n import matplotlib.pyplot as plt\n import numpy as np\n\n FusionCache.reset()\n est_perfs = []\n for hidden_shape in script_config.empirical_hidden_sizes:\n inputs = autotune_config.create_inputs(\n (script_config.empirical_batch_size, hidden_shape),\n script_config.tensor_datatype,\n )\n\n estimate_config = find_best_parameters(\n clf,\n (script_config.empirical_batch_size, hidden_shape),\n autotune_config.generate_scheduler_configurations(\n (script_config.empirical_batch_size, hidden_shape)\n ),\n )\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n _, est_time_ms = run_profile(\n autotune_config, presched_fd, inputs, estimate_config\n )\n est_perfs.append(est_time_ms)\n print(\n f\"{script_config.empirical_batch_size}, {hidden_shape}, {estimate_config}, {est_time_ms: .3f}\"\n )\n\n FusionCache.reset()\n nvf_perfs = []\n for hidden_shape in script_config.empirical_hidden_sizes:\n inputs = autotune_config.create_inputs(\n (script_config.empirical_batch_size, hidden_shape),\n script_config.tensor_datatype,\n )\n\n with FusionDefinition() as presched_fd:\n autotune_config.create_fusion_func(inputs)(presched_fd)\n\n _, nvf_time_ms = run_profile(autotune_config, presched_fd, inputs)\n nvf_perfs.append(nvf_time_ms)\n print(\n f\"{script_config.empirical_batch_size}, {hidden_shape}, {nvf_time_ms: .3f}\"\n )\n\n # Get mean speed-up from nvfuser to empirical configurations across all input shapes.\n # Negative value mean empirical configurations are slower than nvfuser.\n print(\"Mean speed-up\", np.mean(np.array(nvf_perfs) - np.array(est_perfs)))\n\n np_hidden_size = np.array(script_config.empirical_hidden_sizes)\n plt.plot(np_hidden_size, np.array(est_perfs))\n plt.plot(np_hidden_size, np.array(nvf_perfs))\n\n plt.xlabel(\"Hidden Size\")\n plt.ylabel(\"Time(ms)\")\n plt.title(\n f\"Batch Size = {script_config.empirical_batch_size}, Compare Machine Learning Heuristic vs NvFuser\"\n )\n plt.legend([\"random_forest\", \"nvfuser\"], loc=\"lower right\")\n plt.savefig(\n f\"{autotune_config}_empirical_batch_size_{script_config.empirical_batch_size}.png\"\n )\n plt.close(\"all\")","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent","uri":"program://Fuser/module/doc.dev.python_scheduling.autotune_persistent#L1-L417","kind":"module","name":"doc.dev.python_scheduling.autotune_persistent","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":1,"end_line":417,"context_start_line":1,"context_end_line":417,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport itertools\nimport random\nfrom nvfuser import FusionCache, FusionDefinition, SchedulerType, DataType\nfrom nvfuser.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom copy import deepcopy\n\n# ============================ Description ============================\n\n# 1. Define a nvfuser fusion and its pytorch eager mode reference.\n#\n# 2. Profile the CUDA kernel performance by iterating over a set of input\n# arguments and scheduler configurations.\n#\n# 3. Train a regression model to predict the desired performance metric given\n# some input arguments and a scheduler configuration.\n#\n# 4. Measure the performance of the regression model.\n# - Calculate RMSE of predicted and actual performance on test set.\n# - Find the configuration with the best performance using regression model.\n# Then, compare against the heuristic configuration selected by nvfuser.\n# - For a specific batch size, gather performance across a range of hidden\n# sizes. Calculate performance for best predicted and nvfuser\n# configurations. Plot a chart comparing performance using matplotlib.\n\n# The selected performance metric is effective_bandwidth_gbs. The empirical\n# scheduler selects the configuration that has the highest predicted\n# effective_bandwidth_gbs.\n\n# ============================ Configurations ============================\n\n# Settings for input tensor generation\nnum_dimensions = 2\nouter_shapes = [256, 1024, 4096, 16384]\ninner_shapes = [2**i for i in range(10, 15)]\n\n# For pointwise scheduler, we test the cartesian product of vectorization and\n# cta_size factors.\nparameter_configurations = [\n vectorize_range := [1, 2, 4, 8],\n threads_per_cta_range := list(range(128, 288, 32)),\n]\n\n# We profile a range of input shapes with various configurations.\n# This argument determines how much of the profiled data to keep as a test set.\ntest_data_percentage = 0.1\n\n# The selected batch size for empirical and nvfuser comparison.\nempirical_batch_size = 512\n\n# The range of hidden sizes for empirical and nvfuser comparision.\nempirical_hidden_sizes = list(range(1024, 28672, 256))\n\n# NOTE For 24gb memory limit\n# empirical_hidden_sizes = list(range(256, 22784, 256))\n\n\ndef create_inputs(shape):\n \"\"\"Create input arguments for nvfuser fusion and eager mode\"\"\"\n a = torch.randn(*shape, dtype=torch.bfloat16, device=\"cuda\", requires_grad=True)\n grads = torch.randn(*shape, dtype=torch.bfloat16, device=\"cuda\")\n weights = torch.randn(\n shape[1], dtype=torch.bfloat16, device=\"cuda\", requires_grad=True\n )\n bias = torch.randn(\n shape[1], dtype=torch.bfloat16, device=\"cuda\", requires_grad=True\n )\n\n eps = 1e-5\n mean = a.to(torch.float).mean(dim=-1)\n variance = a.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n nvf_inputs = [a, grads, mean, invstd, weights]\n eager_inputs = [a, weights, bias, grads]\n return nvf_inputs, eager_inputs\n\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n PROMOTE_DTYPES = [DataType.BFloat16, DataType.Half]\n dtype = torch_dtype_to_nvfuser_dtype(inputs[0].dtype)\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n )\n\n T4 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n\n V8 = fd.define_vector([T0.size(0), 1], dtype=DataType.Int)\n T9 = fd.ops.broadcast_in_dim(T2, shape=V8, broadcast_dims=[0])\n V12 = T0.shape()\n T13 = fd.ops.broadcast_in_dim(T9, shape=V12, broadcast_dims=[0, 1])\n T14 = fd.ops.sub(T0, T13)\n\n T18 = fd.ops.broadcast_in_dim(T3, shape=V12, broadcast_dims=[0, 1])\n T19 = fd.ops.mul(T14, T18)\n\n T23 = fd.ops.broadcast_in_dim(T4, shape=V12, broadcast_dims=[1])\n T28 = fd.ops.sum(T1, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T30 = fd.ops.mul(T1, T23)\n T31 = fd.ops.mul(T1, T19)\n T32 = fd.ops.sum(T31, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T34 = fd.ops.mul(T30, T18)\n T35 = fd.ops.mul(T30, T14)\n T36 = fd.ops.sum(T35, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T40 = fd.ops.broadcast_in_dim(T36, shape=V8, broadcast_dims=[0])\n T41 = fd.ops.neg(T34)\n T42 = fd.ops.sum(T41, dims=[1], keepdim=False, dtype=DataType.Null)\n T46 = fd.ops.broadcast_in_dim(T42, shape=V8, broadcast_dims=[0])\n S47 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T48 = fd.ops.mul(S47, T40)\n S49 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T50 = fd.ops.pow(T3, S49)\n T51 = fd.ops.mul(T48, T50)\n T54 = fd.ops.sum(T46, dims=[1], keepdim=False, dtype=DataType.Null)\n T55 = fd.ops.sum(T51, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T59 = fd.ops.broadcast_in_dim(T55, shape=V8, broadcast_dims=[0])\n T63 = fd.ops.broadcast_in_dim(T59, shape=V12, broadcast_dims=[0, 1])\n T67 = fd.ops.broadcast_in_dim(T2, shape=V8, broadcast_dims=[0])\n T71 = fd.ops.broadcast_in_dim(T67, shape=V12, broadcast_dims=[0, 1])\n\n S72 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T73 = fd.ops.mul(S72, T63)\n T74 = fd.ops.sub(T0, T71)\n T75 = fd.ops.mul(T73, T74)\n\n S77 = fd.ops.reciprocal(T0.size(1))\n T78 = fd.ops.mul(T75, S77)\n T82 = fd.ops.broadcast_in_dim(T54, shape=V8, broadcast_dims=[0])\n T86 = fd.ops.broadcast_in_dim(T82, shape=V12, broadcast_dims=[0, 1])\n T88 = fd.ops.mul(S77, T86)\n T89 = fd.ops.add(T78, T88)\n T90 = fd.ops.add(T34, T89)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T90 = fd.ops.cast(T90, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T90)\n fd.add_output(T32)\n fd.add_output(T28)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n inputs_cloned = deepcopy(inputs)\n a, weights, bias, grad_output = inputs_cloned\n eager_output = torch.nn.functional.layer_norm(\n a.to(torch.double),\n a.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n grad_output = grad_output.to(torch.double)\n eager_output.backward(grad_output)\n return [a.grad, weights.grad, bias.grad]\n\n\n# ============================ Function Definitions ============================\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_persistent_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with persistent scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.inner_outer_persistent)\n assert status\n\n # Modify original parameters\n if config is not None:\n hyperparameters = fd.sched.schedule_hyperparameters()\n vectorize_factor, threads_per_block = config\n hyperparameters.vectorize_factor = vectorize_factor\n hyperparameters.threads_per_block_min = threads_per_block\n hyperparameters.threads_per_block_max = threads_per_block\n\n # Schedule fusion\n fd.sched.schedule(SchedulerType.inner_outer_persistent)\n\n fd.schedule = inner_fn\n return fd\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(presched_fd, nvf_inputs, eager_inputs, config=None):\n scheduled_fd = custom_persistent_scheduler(presched_fd, config)\n nvf_outputs = scheduled_fd.execute(nvf_inputs, profile=True)\n\n # validate correctness\n ref_outputs = eager_reference(eager_inputs)\n for nvf_out, ref_out in zip(nvf_outputs, ref_outputs):\n assert torch.allclose(nvf_out, ref_out, atol=1e-1, rtol=1e-1)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\ndef argmax(map_config_to_perf):\n best_perf = -1\n best_config = None\n for config, perf in map_config_to_perf.items():\n if perf > best_perf:\n best_perf = perf\n best_config = config\n return best_config\n\n\n# Given a prediction model, input_shape, and set of parameter configurations,\n# find the best parameters\ndef find_best_parameters(predictor, input_shape, parameter_configurations):\n map_config_to_performance = {\n config: predictor.predict([[*input_shape, *config]])\n for config in itertools.product(*parameter_configurations)\n }\n return argmax(map_config_to_performance)\n\n\n# ============================ Run Experiments ================================\n\n# Collect data for decision tree\nparameters = []\nperformance = []\n\nfor shape in itertools.product(outer_shapes, inner_shapes):\n print(shape)\n nvf_inputs, eager_inputs = create_inputs(shape)\n\n with FusionDefinition() as presched_fd:\n create_fusion_func(nvf_inputs)(presched_fd)\n\n # vectorization and threads_per_cta configurations\n for config in itertools.product(*parameter_configurations):\n perf_metric, _ = run_profile(presched_fd, nvf_inputs, eager_inputs, config)\n parameters.append((*shape, *config))\n performance.append(perf_metric)\n\n# ============================ Separate Data ==================================\n\n# Separate collected data into training and test sets\ntrain_data = []\ntest_data = []\ntrain_perf = []\ntest_perf = []\ntest_shapes = set()\nall_test_config = {} # key: input_shape, value: (config, perf)\n\nfor data, perf in zip(parameters, performance):\n shape = data[:num_dimensions]\n config = data[num_dimensions:]\n\n if shape in all_test_config:\n all_test_config[shape][config] = perf\n else:\n all_test_config[shape] = {config: perf}\n\n if random.random() < test_data_percentage:\n test_data.append(data)\n test_perf.append(perf)\n else:\n test_shapes.add(shape)\n train_data.append(data)\n train_perf.append(perf)\n\n# key: input_shape, value: best_config\nbest_test_config = {shape: argmax(all_test_config[shape]) for shape in test_shapes}\n\n# ========================= Train Regression Models ===========================\n\n# Apply decision tree regressor\n# Given input shapes and scheduler parameters, predict performance metric.\nfrom sklearn import tree\n\nclf = tree.DecisionTreeRegressor()\nclf = clf.fit(train_data, train_perf)\ntest_pred = clf.predict(test_data)\n\nprint(\"===================== measure performance rmse ========================\")\n\n# Estimate prediction error with RMSE\nimport numpy as np\n\ntest_perf = np.array(test_perf)\nprint(\n \"Test prediction error (RMSE)\",\n np.sqrt(np.mean(np.power(test_perf - test_pred, 2))),\n)\nprint(\"Test performance\", test_perf)\nprint(\"Test prediction\", test_pred)\n\nprint(\"======================= compare configurations =======================\")\n# Find best configuration for test_shapes\nprint(\n \"input shape, estimate_config:(vectorization, cta_size), actual_config:(vectorization, cta_size), correct\"\n)\ncorrectness_count = 0\nmismatch_configs = []\nfor shape in test_shapes:\n estimate_config = find_best_parameters(clf, shape, parameter_configurations)\n\n match_config = estimate_config == best_test_config[shape]\n if not match_config:\n mismatch_configs.append((shape, estimate_config))\n\n correctness_count += int(match_config)\n print(f\"{shape}, {estimate_config}, {best_test_config[shape]}, {match_config}\")\nprint(\"% of predictions match nvfuser parameters\", correctness_count / len(test_shapes))\nprint(correctness_count, \"out of\", len(test_shapes))\n\nprint(\"======================= compare performance =========================\")\n\nfor shape, estimate_config in mismatch_configs:\n nvf_inputs, eager_inputs = create_inputs(shape)\n\n with FusionDefinition() as presched_fd:\n create_fusion_func(nvf_inputs)(presched_fd)\n\n _, est_perf = run_profile(presched_fd, nvf_inputs, eager_inputs, estimate_config)\n _, nvf_perf = run_profile(presched_fd, nvf_inputs, eager_inputs)\n est_perf_faster = est_perf < nvf_perf\n print(\n f\"{shape} \\t estimate_perf:{est_perf:.5f} \\t nvfuser_perf:{nvf_perf:.5f} \\t is_estimated_config_faster:\\t{est_perf_faster}\"\n )\n\nprint(\"=====================================================================\")\n\n# For a specific batch size, gather performance across a range of hidden sizes.\n# Calculate performance for best predicted and nvfuser configurations. Plot a\n# chart comparing performance using matplotlib.\n\n# NOTE: The matplotlib experiment plots the kernel runtime, which could be\n# different than the selected performance metric. Currently, the performance\n# metric is effective_bandwidth_gbs.\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Avoid reusing any cached, user-scheduled fusions to have a clean run.\nFusionCache.reset()\nest_perfs = []\nfor hidden_shape in empirical_hidden_sizes:\n nvf_inputs, eager_inputs = create_inputs((empirical_batch_size, hidden_shape))\n estimate_config = find_best_parameters(\n clf, (empirical_batch_size, hidden_shape), parameter_configurations\n )\n\n with FusionDefinition() as presched_fd:\n create_fusion_func(nvf_inputs)(presched_fd)\n\n _, est_time_ms = run_profile(presched_fd, nvf_inputs, eager_inputs, estimate_config)\n est_perfs.append(est_time_ms)\n print(\n f\"decision tree: {empirical_batch_size}, {hidden_shape}, {estimate_config}, {est_time_ms:.3f}\"\n )\n\nFusionCache.reset()\nnvf_perfs = []\nfor hidden_shape in empirical_hidden_sizes:\n nvf_inputs, eager_inputs = create_inputs((empirical_batch_size, hidden_shape))\n estimate_config = find_best_parameters(\n clf, (empirical_batch_size, hidden_shape), parameter_configurations\n )\n\n with FusionDefinition() as presched_fd:\n create_fusion_func(nvf_inputs)(presched_fd)\n\n _, nvf_time_ms = run_profile(presched_fd, nvf_inputs, eager_inputs)\n nvf_perfs.append(nvf_time_ms)\n print(f\"nvfuser: {empirical_batch_size}, {hidden_shape}, {nvf_time_ms:.3f}\")\n\n# Get mean speed-up from nvfuser to empirical configurations across all input shapes.\n# Negative value mean empirical configurations are slower than nvfuser.\nprint(\"Mean speed-up\", np.mean(np.array(nvf_perfs) - np.array(est_perfs)))\n\nnp_hidden_size = np.array(empirical_hidden_sizes)\nplt.plot(np_hidden_size, np.array(est_perfs))\nplt.plot(np_hidden_size, np.array(nvf_perfs))\n\nplt.xlabel(\"Hidden Size\")\nplt.ylabel(\"Time(ms)\")\nplt.title(\n f\"Batch Size = {empirical_batch_size}, Compare Decision Tree Heuristic vs NvFuser\"\n)\nplt.legend([\"decision_tree\", \"nvfuser\"], loc=\"lower right\")\nplt.savefig(f\"persistent_inner_outer_empirical_batchsize{empirical_batch_size}.png\")\n\n# =============================================================================","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent.create_inputs","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_persistent.create_inputs#L63-L81","kind":"function","name":"create_inputs","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":63,"end_line":81,"context_start_line":43,"context_end_line":101,"code":"# cta_size factors.\nparameter_configurations = [\n vectorize_range := [1, 2, 4, 8],\n threads_per_cta_range := list(range(128, 288, 32)),\n]\n\n# We profile a range of input shapes with various configurations.\n# This argument determines how much of the profiled data to keep as a test set.\ntest_data_percentage = 0.1\n\n# The selected batch size for empirical and nvfuser comparison.\nempirical_batch_size = 512\n\n# The range of hidden sizes for empirical and nvfuser comparision.\nempirical_hidden_sizes = list(range(1024, 28672, 256))\n\n# NOTE For 24gb memory limit\n# empirical_hidden_sizes = list(range(256, 22784, 256))\n\n\ndef create_inputs(shape):\n \"\"\"Create input arguments for nvfuser fusion and eager mode\"\"\"\n a = torch.randn(*shape, dtype=torch.bfloat16, device=\"cuda\", requires_grad=True)\n grads = torch.randn(*shape, dtype=torch.bfloat16, device=\"cuda\")\n weights = torch.randn(\n shape[1], dtype=torch.bfloat16, device=\"cuda\", requires_grad=True\n )\n bias = torch.randn(\n shape[1], dtype=torch.bfloat16, device=\"cuda\", requires_grad=True\n )\n\n eps = 1e-5\n mean = a.to(torch.float).mean(dim=-1)\n variance = a.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n nvf_inputs = [a, grads, mean, invstd, weights]\n eager_inputs = [a, weights, bias, grads]\n return nvf_inputs, eager_inputs\n\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n PROMOTE_DTYPES = [DataType.BFloat16, DataType.Half]\n dtype = torch_dtype_to_nvfuser_dtype(inputs[0].dtype)\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent.create_fusion_func","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_persistent.create_fusion_func#L85-L170","kind":"function","name":"create_fusion_func","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":85,"end_line":170,"context_start_line":65,"context_end_line":190,"code":" a = torch.randn(*shape, dtype=torch.bfloat16, device=\"cuda\", requires_grad=True)\n grads = torch.randn(*shape, dtype=torch.bfloat16, device=\"cuda\")\n weights = torch.randn(\n shape[1], dtype=torch.bfloat16, device=\"cuda\", requires_grad=True\n )\n bias = torch.randn(\n shape[1], dtype=torch.bfloat16, device=\"cuda\", requires_grad=True\n )\n\n eps = 1e-5\n mean = a.to(torch.float).mean(dim=-1)\n variance = a.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n nvf_inputs = [a, grads, mean, invstd, weights]\n eager_inputs = [a, weights, bias, grads]\n return nvf_inputs, eager_inputs\n\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n PROMOTE_DTYPES = [DataType.BFloat16, DataType.Half]\n dtype = torch_dtype_to_nvfuser_dtype(inputs[0].dtype)\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n )\n\n T4 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n\n V8 = fd.define_vector([T0.size(0), 1], dtype=DataType.Int)\n T9 = fd.ops.broadcast_in_dim(T2, shape=V8, broadcast_dims=[0])\n V12 = T0.shape()\n T13 = fd.ops.broadcast_in_dim(T9, shape=V12, broadcast_dims=[0, 1])\n T14 = fd.ops.sub(T0, T13)\n\n T18 = fd.ops.broadcast_in_dim(T3, shape=V12, broadcast_dims=[0, 1])\n T19 = fd.ops.mul(T14, T18)\n\n T23 = fd.ops.broadcast_in_dim(T4, shape=V12, broadcast_dims=[1])\n T28 = fd.ops.sum(T1, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T30 = fd.ops.mul(T1, T23)\n T31 = fd.ops.mul(T1, T19)\n T32 = fd.ops.sum(T31, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T34 = fd.ops.mul(T30, T18)\n T35 = fd.ops.mul(T30, T14)\n T36 = fd.ops.sum(T35, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T40 = fd.ops.broadcast_in_dim(T36, shape=V8, broadcast_dims=[0])\n T41 = fd.ops.neg(T34)\n T42 = fd.ops.sum(T41, dims=[1], keepdim=False, dtype=DataType.Null)\n T46 = fd.ops.broadcast_in_dim(T42, shape=V8, broadcast_dims=[0])\n S47 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T48 = fd.ops.mul(S47, T40)\n S49 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T50 = fd.ops.pow(T3, S49)\n T51 = fd.ops.mul(T48, T50)\n T54 = fd.ops.sum(T46, dims=[1], keepdim=False, dtype=DataType.Null)\n T55 = fd.ops.sum(T51, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T59 = fd.ops.broadcast_in_dim(T55, shape=V8, broadcast_dims=[0])\n T63 = fd.ops.broadcast_in_dim(T59, shape=V12, broadcast_dims=[0, 1])\n T67 = fd.ops.broadcast_in_dim(T2, shape=V8, broadcast_dims=[0])\n T71 = fd.ops.broadcast_in_dim(T67, shape=V12, broadcast_dims=[0, 1])\n\n S72 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T73 = fd.ops.mul(S72, T63)\n T74 = fd.ops.sub(T0, T71)\n T75 = fd.ops.mul(T73, T74)\n\n S77 = fd.ops.reciprocal(T0.size(1))\n T78 = fd.ops.mul(T75, S77)\n T82 = fd.ops.broadcast_in_dim(T54, shape=V8, broadcast_dims=[0])\n T86 = fd.ops.broadcast_in_dim(T82, shape=V12, broadcast_dims=[0, 1])\n T88 = fd.ops.mul(S77, T86)\n T89 = fd.ops.add(T78, T88)\n T90 = fd.ops.add(T34, T89)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T90 = fd.ops.cast(T90, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T90)\n fd.add_output(T32)\n fd.add_output(T28)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n inputs_cloned = deepcopy(inputs)\n a, weights, bias, grad_output = inputs_cloned\n eager_output = torch.nn.functional.layer_norm(\n a.to(torch.double),\n a.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n grad_output = grad_output.to(torch.double)\n eager_output.backward(grad_output)\n return [a.grad, weights.grad, bias.grad]\n\n\n# ============================ Function Definitions ============================\n\n","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent.eager_reference","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_persistent.eager_reference#L174-L185","kind":"function","name":"eager_reference","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":174,"end_line":185,"context_start_line":154,"context_end_line":205,"code":" T78 = fd.ops.mul(T75, S77)\n T82 = fd.ops.broadcast_in_dim(T54, shape=V8, broadcast_dims=[0])\n T86 = fd.ops.broadcast_in_dim(T82, shape=V12, broadcast_dims=[0, 1])\n T88 = fd.ops.mul(S77, T86)\n T89 = fd.ops.add(T78, T88)\n T90 = fd.ops.add(T34, T89)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T90 = fd.ops.cast(T90, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T90)\n fd.add_output(T32)\n fd.add_output(T28)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n inputs_cloned = deepcopy(inputs)\n a, weights, bias, grad_output = inputs_cloned\n eager_output = torch.nn.functional.layer_norm(\n a.to(torch.double),\n a.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n grad_output = grad_output.to(torch.double)\n eager_output.backward(grad_output)\n return [a.grad, weights.grad, bias.grad]\n\n\n# ============================ Function Definitions ============================\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_persistent_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with persistent scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.inner_outer_persistent)\n assert status\n\n # Modify original parameters\n if config is not None:\n hyperparameters = fd.sched.schedule_hyperparameters()\n vectorize_factor, threads_per_block = config\n hyperparameters.vectorize_factor = vectorize_factor\n hyperparameters.threads_per_block_min = threads_per_block\n hyperparameters.threads_per_block_max = threads_per_block\n","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent.custom_persistent_scheduler","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_persistent.custom_persistent_scheduler#L192-L210","kind":"function","name":"custom_persistent_scheduler","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":192,"end_line":210,"context_start_line":172,"context_end_line":230,"code":"\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n inputs_cloned = deepcopy(inputs)\n a, weights, bias, grad_output = inputs_cloned\n eager_output = torch.nn.functional.layer_norm(\n a.to(torch.double),\n a.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n grad_output = grad_output.to(torch.double)\n eager_output.backward(grad_output)\n return [a.grad, weights.grad, bias.grad]\n\n\n# ============================ Function Definitions ============================\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_persistent_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with persistent scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.inner_outer_persistent)\n assert status\n\n # Modify original parameters\n if config is not None:\n hyperparameters = fd.sched.schedule_hyperparameters()\n vectorize_factor, threads_per_block = config\n hyperparameters.vectorize_factor = vectorize_factor\n hyperparameters.threads_per_block_min = threads_per_block\n hyperparameters.threads_per_block_max = threads_per_block\n\n # Schedule fusion\n fd.sched.schedule(SchedulerType.inner_outer_persistent)\n\n fd.schedule = inner_fn\n return fd\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(presched_fd, nvf_inputs, eager_inputs, config=None):\n scheduled_fd = custom_persistent_scheduler(presched_fd, config)\n nvf_outputs = scheduled_fd.execute(nvf_inputs, profile=True)\n\n # validate correctness\n ref_outputs = eager_reference(eager_inputs)\n for nvf_out, ref_out in zip(nvf_outputs, ref_outputs):\n assert torch.allclose(nvf_out, ref_out, atol=1e-1, rtol=1e-1)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\ndef argmax(map_config_to_perf):\n best_perf = -1","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent.run_profile","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_persistent.run_profile#L214-L226","kind":"function","name":"run_profile","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":214,"end_line":226,"context_start_line":194,"context_end_line":246,"code":" # Check if compatible with persistent scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.inner_outer_persistent)\n assert status\n\n # Modify original parameters\n if config is not None:\n hyperparameters = fd.sched.schedule_hyperparameters()\n vectorize_factor, threads_per_block = config\n hyperparameters.vectorize_factor = vectorize_factor\n hyperparameters.threads_per_block_min = threads_per_block\n hyperparameters.threads_per_block_max = threads_per_block\n\n # Schedule fusion\n fd.sched.schedule(SchedulerType.inner_outer_persistent)\n\n fd.schedule = inner_fn\n return fd\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(presched_fd, nvf_inputs, eager_inputs, config=None):\n scheduled_fd = custom_persistent_scheduler(presched_fd, config)\n nvf_outputs = scheduled_fd.execute(nvf_inputs, profile=True)\n\n # validate correctness\n ref_outputs = eager_reference(eager_inputs)\n for nvf_out, ref_out in zip(nvf_outputs, ref_outputs):\n assert torch.allclose(nvf_out, ref_out, atol=1e-1, rtol=1e-1)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\ndef argmax(map_config_to_perf):\n best_perf = -1\n best_config = None\n for config, perf in map_config_to_perf.items():\n if perf > best_perf:\n best_perf = perf\n best_config = config\n return best_config\n\n\n# Given a prediction model, input_shape, and set of parameter configurations,\n# find the best parameters\ndef find_best_parameters(predictor, input_shape, parameter_configurations):\n map_config_to_performance = {\n config: predictor.predict([[*input_shape, *config]])\n for config in itertools.product(*parameter_configurations)\n }\n return argmax(map_config_to_performance)","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent.argmax","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_persistent.argmax#L229-L236","kind":"function","name":"argmax","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":229,"end_line":236,"context_start_line":209,"context_end_line":256,"code":" fd.schedule = inner_fn\n return fd\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(presched_fd, nvf_inputs, eager_inputs, config=None):\n scheduled_fd = custom_persistent_scheduler(presched_fd, config)\n nvf_outputs = scheduled_fd.execute(nvf_inputs, profile=True)\n\n # validate correctness\n ref_outputs = eager_reference(eager_inputs)\n for nvf_out, ref_out in zip(nvf_outputs, ref_outputs):\n assert torch.allclose(nvf_out, ref_out, atol=1e-1, rtol=1e-1)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\ndef argmax(map_config_to_perf):\n best_perf = -1\n best_config = None\n for config, perf in map_config_to_perf.items():\n if perf > best_perf:\n best_perf = perf\n best_config = config\n return best_config\n\n\n# Given a prediction model, input_shape, and set of parameter configurations,\n# find the best parameters\ndef find_best_parameters(predictor, input_shape, parameter_configurations):\n map_config_to_performance = {\n config: predictor.predict([[*input_shape, *config]])\n for config in itertools.product(*parameter_configurations)\n }\n return argmax(map_config_to_performance)\n\n\n# ============================ Run Experiments ================================\n\n# Collect data for decision tree\nparameters = []\nperformance = []\n\nfor shape in itertools.product(outer_shapes, inner_shapes):\n print(shape)","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent.find_best_parameters","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_persistent.find_best_parameters#L241-L246","kind":"function","name":"find_best_parameters","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":241,"end_line":246,"context_start_line":221,"context_end_line":266,"code":" assert torch.allclose(nvf_out, ref_out, atol=1e-1, rtol=1e-1)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n\n\ndef argmax(map_config_to_perf):\n best_perf = -1\n best_config = None\n for config, perf in map_config_to_perf.items():\n if perf > best_perf:\n best_perf = perf\n best_config = config\n return best_config\n\n\n# Given a prediction model, input_shape, and set of parameter configurations,\n# find the best parameters\ndef find_best_parameters(predictor, input_shape, parameter_configurations):\n map_config_to_performance = {\n config: predictor.predict([[*input_shape, *config]])\n for config in itertools.product(*parameter_configurations)\n }\n return argmax(map_config_to_performance)\n\n\n# ============================ Run Experiments ================================\n\n# Collect data for decision tree\nparameters = []\nperformance = []\n\nfor shape in itertools.product(outer_shapes, inner_shapes):\n print(shape)\n nvf_inputs, eager_inputs = create_inputs(shape)\n\n with FusionDefinition() as presched_fd:\n create_fusion_func(nvf_inputs)(presched_fd)\n\n # vectorization and threads_per_cta configurations\n for config in itertools.product(*parameter_configurations):\n perf_metric, _ = run_profile(presched_fd, nvf_inputs, eager_inputs, config)\n parameters.append((*shape, *config))\n performance.append(perf_metric)","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent.fusion_func","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_persistent.fusion_func#L89-L168","kind":"function","name":"fusion_func","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":89,"end_line":168,"context_start_line":69,"context_end_line":188,"code":" )\n bias = torch.randn(\n shape[1], dtype=torch.bfloat16, device=\"cuda\", requires_grad=True\n )\n\n eps = 1e-5\n mean = a.to(torch.float).mean(dim=-1)\n variance = a.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n nvf_inputs = [a, grads, mean, invstd, weights]\n eager_inputs = [a, weights, bias, grads]\n return nvf_inputs, eager_inputs\n\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n PROMOTE_DTYPES = [DataType.BFloat16, DataType.Half]\n dtype = torch_dtype_to_nvfuser_dtype(inputs[0].dtype)\n\n def fusion_func(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n )\n\n T4 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n\n V8 = fd.define_vector([T0.size(0), 1], dtype=DataType.Int)\n T9 = fd.ops.broadcast_in_dim(T2, shape=V8, broadcast_dims=[0])\n V12 = T0.shape()\n T13 = fd.ops.broadcast_in_dim(T9, shape=V12, broadcast_dims=[0, 1])\n T14 = fd.ops.sub(T0, T13)\n\n T18 = fd.ops.broadcast_in_dim(T3, shape=V12, broadcast_dims=[0, 1])\n T19 = fd.ops.mul(T14, T18)\n\n T23 = fd.ops.broadcast_in_dim(T4, shape=V12, broadcast_dims=[1])\n T28 = fd.ops.sum(T1, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T30 = fd.ops.mul(T1, T23)\n T31 = fd.ops.mul(T1, T19)\n T32 = fd.ops.sum(T31, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T34 = fd.ops.mul(T30, T18)\n T35 = fd.ops.mul(T30, T14)\n T36 = fd.ops.sum(T35, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T40 = fd.ops.broadcast_in_dim(T36, shape=V8, broadcast_dims=[0])\n T41 = fd.ops.neg(T34)\n T42 = fd.ops.sum(T41, dims=[1], keepdim=False, dtype=DataType.Null)\n T46 = fd.ops.broadcast_in_dim(T42, shape=V8, broadcast_dims=[0])\n S47 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T48 = fd.ops.mul(S47, T40)\n S49 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T50 = fd.ops.pow(T3, S49)\n T51 = fd.ops.mul(T48, T50)\n T54 = fd.ops.sum(T46, dims=[1], keepdim=False, dtype=DataType.Null)\n T55 = fd.ops.sum(T51, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T59 = fd.ops.broadcast_in_dim(T55, shape=V8, broadcast_dims=[0])\n T63 = fd.ops.broadcast_in_dim(T59, shape=V12, broadcast_dims=[0, 1])\n T67 = fd.ops.broadcast_in_dim(T2, shape=V8, broadcast_dims=[0])\n T71 = fd.ops.broadcast_in_dim(T67, shape=V12, broadcast_dims=[0, 1])\n\n S72 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T73 = fd.ops.mul(S72, T63)\n T74 = fd.ops.sub(T0, T71)\n T75 = fd.ops.mul(T73, T74)\n\n S77 = fd.ops.reciprocal(T0.size(1))\n T78 = fd.ops.mul(T75, S77)\n T82 = fd.ops.broadcast_in_dim(T54, shape=V8, broadcast_dims=[0])\n T86 = fd.ops.broadcast_in_dim(T82, shape=V12, broadcast_dims=[0, 1])\n T88 = fd.ops.mul(S77, T86)\n T89 = fd.ops.add(T78, T88)\n T90 = fd.ops.add(T34, T89)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T90 = fd.ops.cast(T90, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T90)\n fd.add_output(T32)\n fd.add_output(T28)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n inputs_cloned = deepcopy(inputs)\n a, weights, bias, grad_output = inputs_cloned\n eager_output = torch.nn.functional.layer_norm(\n a.to(torch.double),\n a.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n grad_output = grad_output.to(torch.double)\n eager_output.backward(grad_output)\n return [a.grad, weights.grad, bias.grad]\n\n\n# ============================ Function Definitions ============================","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_persistent.inner_fn","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_persistent.inner_fn#L193-L207","kind":"function","name":"inner_fn","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":193,"end_line":207,"context_start_line":173,"context_end_line":227,"code":"# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n inputs_cloned = deepcopy(inputs)\n a, weights, bias, grad_output = inputs_cloned\n eager_output = torch.nn.functional.layer_norm(\n a.to(torch.double),\n a.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n grad_output = grad_output.to(torch.double)\n eager_output.backward(grad_output)\n return [a.grad, weights.grad, bias.grad]\n\n\n# ============================ Function Definitions ============================\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_persistent_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with persistent scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.inner_outer_persistent)\n assert status\n\n # Modify original parameters\n if config is not None:\n hyperparameters = fd.sched.schedule_hyperparameters()\n vectorize_factor, threads_per_block = config\n hyperparameters.vectorize_factor = vectorize_factor\n hyperparameters.threads_per_block_min = threads_per_block\n hyperparameters.threads_per_block_max = threads_per_block\n\n # Schedule fusion\n fd.sched.schedule(SchedulerType.inner_outer_persistent)\n\n fd.schedule = inner_fn\n return fd\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(presched_fd, nvf_inputs, eager_inputs, config=None):\n scheduled_fd = custom_persistent_scheduler(presched_fd, config)\n nvf_outputs = scheduled_fd.execute(nvf_inputs, profile=True)\n\n # validate correctness\n ref_outputs = eager_reference(eager_inputs)\n for nvf_out, ref_out in zip(nvf_outputs, ref_outputs):\n assert torch.allclose(nvf_out, ref_out, atol=1e-1, rtol=1e-1)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n return bandwidth, time\n","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise","uri":"program://Fuser/module/doc.dev.python_scheduling.autotune_pointwise#L1-L374","kind":"module","name":"doc.dev.python_scheduling.autotune_pointwise","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":1,"end_line":374,"context_start_line":1,"context_end_line":374,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport itertools\nimport math\n\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import FusionDefinition, SchedulerType, DataType\nfrom dataclasses import dataclass\nfrom enum import Enum\n\nfrom autotune_utils import (\n ScriptConfiguration,\n collect_data,\n separate_data,\n test_model_rmse,\n test_model,\n)\n\n\n# ============================ Description ============================\n\n# This script defines four pointwise fusions:\n#\n# 1. GELU with Outer-Broadcast Bias Addition\n# y = gelu(x + bias[broadcast, i], approximate='tanh')\n#\n# 2. SILU with Pointwise Multiplication\n# z = silu(x) * y\n#\n# 3. Inner-Broadcast Addition\n# y = x + y[i, broadcast]\n#\n# 4. Pointwise Multiplication\n# z = x + y\n#\n# Script Sequence:\n#\n# 1. Define a nvfuser fusion and its pytorch eager mode reference.\n#\n# 2. Profile the CUDA kernel performance by iterating over a set of input\n# arguments and scheduler configurations.\n#\n# 3. Train a regression model to predict the desired performance metric given\n# some input arguments and a scheduler configuration.\n#\n# 4. Measure the performance of the regression model.\n# - Calculate RMSE of predicted and actual performance on test set.\n# - Find the configuration with the best performance using regression model.\n# Then, compare against the heuristic configuration selected by nvfuser.\n# - For a specific batch size, gather performance across a range of hidden\n# sizes. Calculate performance for best predicted and nvfuser\n# configurations. Plot a chart comparing performance using matplotlib.\n#\n# The selected performance metric is effective_bandwidth_gbs. The empirical\n# scheduler selects the configuration that has the highest predicted\n# effective_bandwidth_gbs.\n\n# ============================ Configurations ============================\n\n\nclass AutotunePointwise:\n class FUSION(Enum):\n GELU_BIAS = 1\n SILU_MUL = 2\n BCAST_ADD = 3\n MUL = 4\n\n @dataclass(unsafe_hash=True)\n class PointwiseConfiguration:\n break_point: int\n bdim: [int]\n vectorize_factor: int\n outer_unroll: int\n inner_unroll: int\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n def __repr__(self):\n return f\"pointwise_{self.selected_fusion.name}\"\n\n # For pointwise scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n def _named_product(**items):\n return itertools.starmap(\n self.PointwiseConfiguration, itertools.product(*items.values())\n )\n\n num_dimensions = len(input_shape)\n warp_size = 32\n warp_group = warp_size * 4\n # limited to a maximum of 128 threads because of pointwise scheduler\n max_threads_per_cta = 128\n threads_per_cta = list(range(warp_group, max_threads_per_cta + 1, warp_group))\n\n scheduler_configs = []\n for bp in range(num_dimensions):\n for num_threads in threads_per_cta:\n if bp == 0:\n # 1D scheduler configurations\n bdim_shapes = [(num_threads, 1)]\n outer_unroll_range = [1]\n # unroll_factor is between [1, 9]\n inner_unroll_range = range(1, 10)\n else:\n # 2D scheduler configurations\n max_bdimy = num_threads // warp_size\n log2_max_bdimy = int(math.log2(max_bdimy))\n bdimy_configs = [\n 2**log_bdimy for log_bdimy in range(1, log2_max_bdimy + 1)\n ]\n\n bdim_shapes = [\n (max(warp_size, num_threads // bdimy), bdimy)\n for bdimy in bdimy_configs\n ]\n # total_unroll_factor is between [1, 9] given that outer and\n # inner unroll factors are between [1, 3].\n outer_unroll_range = range(1, 4)\n inner_unroll_range = range(1, 4)\n\n scheduler_config = _named_product(\n break_point=[bp],\n bdim=bdim_shapes,\n vectorize_factor=[1, 2, 4, 8],\n outer_unroll=outer_unroll_range,\n inner_unroll=inner_unroll_range,\n )\n scheduler_configs.append(scheduler_config)\n return itertools.chain(*scheduler_configs)\n\n def create_inputs(self, shape, tensor_datatype):\n def outer_bcast():\n return [\n torch.randn(1, shape[-1], dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def inner_bcast():\n return [\n torch.randn(shape[0], 1, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def full():\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return outer_bcast()\n elif self.selected_fusion in [self.FUSION.SILU_MUL, self.FUSION.MUL]:\n return full()\n elif self.selected_fusion == FUSION.BCAST_ADD:\n return inner_bcast()\n else:\n assert False\n\n # A decorator to create a pointwise fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def gelu_bias(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T6 = fd.ops.cast(T1, dtype=DataType.Float)\n T7 = fd.ops.cast(T0, dtype=DataType.Float)\n T8 = fd.ops.add(T6, T7)\n T9 = fd.ops.mul(T8, T8)\n T10 = fd.ops.mul(T9, T8)\n S11 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T12 = fd.ops.mul(S11, T8)\n S13 = fd.define_scalar(0.0447150, dtype=DataType.Double)\n T14 = fd.ops.mul(S13, T10)\n T15 = fd.ops.add(T8, T14)\n S16 = fd.define_scalar(0.797885, dtype=DataType.Double)\n T17 = fd.ops.mul(S16, T15)\n T18 = fd.ops.tanh(T17)\n S19 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T20 = fd.ops.add(S19, T18)\n T21 = fd.ops.mul(T12, T20)\n T22 = fd.ops.cast(T21, dtype=DataType.BFloat16)\n fd.add_output(T22)\n\n def silu_mul(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.neg(T2)\n T4 = fd.ops.exp(T3)\n S5 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T6 = fd.ops.add(S5, T4)\n T7 = fd.ops.reciprocal(T6)\n T8 = fd.ops.mul(T2, T7)\n T9 = fd.ops.cast(T1, dtype=DataType.Float)\n T10 = fd.ops.mul(T8, T9)\n T11 = fd.ops.cast(T10, dtype=DataType.BFloat16)\n fd.add_output(T11)\n\n def bcast_add(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1],\n contiguity=[True, None],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.add(T2, T3)\n T5 = fd.ops.cast(T4, dtype=DataType.BFloat16)\n fd.add_output(T5)\n\n def mul(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.mul(T2, T3)\n T5 = fd.ops.cast(T4, dtype=DataType.BFloat16)\n fd.add_output(T5)\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias\n elif self.selected_fusion == self.FUSION.SILU_MUL:\n return silu_mul\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add\n elif self.selected_fusion == self.FUSION.MUL:\n return mul\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def gelu_bias(inputs):\n return torch.nn.functional.gelu(\n inputs[0] + inputs[1].unsqueeze(0), approximate=\"tanh\"\n )\n\n def silu_mul(inputs):\n return torch.nn.functional.silu(inputs[0]) * inputs[1]\n\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:\n return silu_mul(inputs)\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add(inputs)\n elif self.selected_fusion == self.FUSION.MUL:\n return mul(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with pointwise scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.pointwise)\n assert status\n\n schedule_params = fd.sched.compute_pointwise_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n schedule_params.break_point = scheduler_config.break_point\n schedule_params.vectorization_factor = scheduler_config.vectorize_factor\n schedule_params.unroll_factor_outer = scheduler_config.outer_unroll\n schedule_params.unroll_factor_inner = scheduler_config.inner_unroll\n schedule_params.lparams.bdimx = scheduler_config.bdim[0]\n schedule_params.lparams.bdimy = scheduler_config.bdim[1]\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotunePointwise(\n selected_fusion=AutotunePointwise.FUSION.GELU_BIAS\n )\n\n # ============================ Run Experiments ============================\n\n parameters, performance = collect_data(script_config, autotune_config)\n\n # ============================ Separate Data ==============================\n\n train_data, test_data = separate_data(script_config, parameters, performance)\n\n # ========================= Train Regression Models =======================\n\n # Apply machine learning regressor\n # Given input shapes and scheduler parameters, predict performance metric.\n from sklearn import ensemble\n\n train_inputs, train_perf = train_data\n clf = ensemble.RandomForestRegressor()\n clf = clf.fit(train_inputs, train_perf)\n\n # ========================= Test Regression Models ========================\n test_model_rmse(clf, script_config, autotune_config, test_data)\n test_model(clf, script_config, autotune_config)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.AutotunePointwise","uri":"program://Fuser/class/doc.dev.python_scheduling.autotune_pointwise.AutotunePointwise#L65-L330","kind":"class","name":"AutotunePointwise","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":65,"end_line":330,"context_start_line":45,"context_end_line":350,"code":"# arguments and scheduler configurations.\n#\n# 3. Train a regression model to predict the desired performance metric given\n# some input arguments and a scheduler configuration.\n#\n# 4. Measure the performance of the regression model.\n# - Calculate RMSE of predicted and actual performance on test set.\n# - Find the configuration with the best performance using regression model.\n# Then, compare against the heuristic configuration selected by nvfuser.\n# - For a specific batch size, gather performance across a range of hidden\n# sizes. Calculate performance for best predicted and nvfuser\n# configurations. Plot a chart comparing performance using matplotlib.\n#\n# The selected performance metric is effective_bandwidth_gbs. The empirical\n# scheduler selects the configuration that has the highest predicted\n# effective_bandwidth_gbs.\n\n# ============================ Configurations ============================\n\n\nclass AutotunePointwise:\n class FUSION(Enum):\n GELU_BIAS = 1\n SILU_MUL = 2\n BCAST_ADD = 3\n MUL = 4\n\n @dataclass(unsafe_hash=True)\n class PointwiseConfiguration:\n break_point: int\n bdim: [int]\n vectorize_factor: int\n outer_unroll: int\n inner_unroll: int\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n def __repr__(self):\n return f\"pointwise_{self.selected_fusion.name}\"\n\n # For pointwise scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n def _named_product(**items):\n return itertools.starmap(\n self.PointwiseConfiguration, itertools.product(*items.values())\n )\n\n num_dimensions = len(input_shape)\n warp_size = 32\n warp_group = warp_size * 4\n # limited to a maximum of 128 threads because of pointwise scheduler\n max_threads_per_cta = 128\n threads_per_cta = list(range(warp_group, max_threads_per_cta + 1, warp_group))\n\n scheduler_configs = []\n for bp in range(num_dimensions):\n for num_threads in threads_per_cta:\n if bp == 0:\n # 1D scheduler configurations\n bdim_shapes = [(num_threads, 1)]\n outer_unroll_range = [1]\n # unroll_factor is between [1, 9]\n inner_unroll_range = range(1, 10)\n else:\n # 2D scheduler configurations\n max_bdimy = num_threads // warp_size\n log2_max_bdimy = int(math.log2(max_bdimy))\n bdimy_configs = [\n 2**log_bdimy for log_bdimy in range(1, log2_max_bdimy + 1)\n ]\n\n bdim_shapes = [\n (max(warp_size, num_threads // bdimy), bdimy)\n for bdimy in bdimy_configs\n ]\n # total_unroll_factor is between [1, 9] given that outer and\n # inner unroll factors are between [1, 3].\n outer_unroll_range = range(1, 4)\n inner_unroll_range = range(1, 4)\n\n scheduler_config = _named_product(\n break_point=[bp],\n bdim=bdim_shapes,\n vectorize_factor=[1, 2, 4, 8],\n outer_unroll=outer_unroll_range,\n inner_unroll=inner_unroll_range,\n )\n scheduler_configs.append(scheduler_config)\n return itertools.chain(*scheduler_configs)\n\n def create_inputs(self, shape, tensor_datatype):\n def outer_bcast():\n return [\n torch.randn(1, shape[-1], dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def inner_bcast():\n return [\n torch.randn(shape[0], 1, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def full():\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return outer_bcast()\n elif self.selected_fusion in [self.FUSION.SILU_MUL, self.FUSION.MUL]:\n return full()\n elif self.selected_fusion == FUSION.BCAST_ADD:\n return inner_bcast()\n else:\n assert False\n\n # A decorator to create a pointwise fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def gelu_bias(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T6 = fd.ops.cast(T1, dtype=DataType.Float)\n T7 = fd.ops.cast(T0, dtype=DataType.Float)\n T8 = fd.ops.add(T6, T7)\n T9 = fd.ops.mul(T8, T8)\n T10 = fd.ops.mul(T9, T8)\n S11 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T12 = fd.ops.mul(S11, T8)\n S13 = fd.define_scalar(0.0447150, dtype=DataType.Double)\n T14 = fd.ops.mul(S13, T10)\n T15 = fd.ops.add(T8, T14)\n S16 = fd.define_scalar(0.797885, dtype=DataType.Double)\n T17 = fd.ops.mul(S16, T15)\n T18 = fd.ops.tanh(T17)\n S19 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T20 = fd.ops.add(S19, T18)\n T21 = fd.ops.mul(T12, T20)\n T22 = fd.ops.cast(T21, dtype=DataType.BFloat16)\n fd.add_output(T22)\n\n def silu_mul(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.neg(T2)\n T4 = fd.ops.exp(T3)\n S5 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T6 = fd.ops.add(S5, T4)\n T7 = fd.ops.reciprocal(T6)\n T8 = fd.ops.mul(T2, T7)\n T9 = fd.ops.cast(T1, dtype=DataType.Float)\n T10 = fd.ops.mul(T8, T9)\n T11 = fd.ops.cast(T10, dtype=DataType.BFloat16)\n fd.add_output(T11)\n\n def bcast_add(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1],\n contiguity=[True, None],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.add(T2, T3)\n T5 = fd.ops.cast(T4, dtype=DataType.BFloat16)\n fd.add_output(T5)\n\n def mul(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.mul(T2, T3)\n T5 = fd.ops.cast(T4, dtype=DataType.BFloat16)\n fd.add_output(T5)\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias\n elif self.selected_fusion == self.FUSION.SILU_MUL:\n return silu_mul\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add\n elif self.selected_fusion == self.FUSION.MUL:\n return mul\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def gelu_bias(inputs):\n return torch.nn.functional.gelu(\n inputs[0] + inputs[1].unsqueeze(0), approximate=\"tanh\"\n )\n\n def silu_mul(inputs):\n return torch.nn.functional.silu(inputs[0]) * inputs[1]\n\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:\n return silu_mul(inputs)\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add(inputs)\n elif self.selected_fusion == self.FUSION.MUL:\n return mul(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with pointwise scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.pointwise)\n assert status\n\n schedule_params = fd.sched.compute_pointwise_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n schedule_params.break_point = scheduler_config.break_point\n schedule_params.vectorization_factor = scheduler_config.vectorize_factor\n schedule_params.unroll_factor_outer = scheduler_config.outer_unroll\n schedule_params.unroll_factor_inner = scheduler_config.inner_unroll\n schedule_params.lparams.bdimx = scheduler_config.bdim[0]\n schedule_params.lparams.bdimy = scheduler_config.bdim[1]\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotunePointwise(\n selected_fusion=AutotunePointwise.FUSION.GELU_BIAS\n )\n\n # ============================ Run Experiments ============================","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.main","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.main#L334-L370","kind":"function","name":"main","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":334,"end_line":370,"context_start_line":314,"context_end_line":374,"code":"\n schedule_params = fd.sched.compute_pointwise_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n schedule_params.break_point = scheduler_config.break_point\n schedule_params.vectorization_factor = scheduler_config.vectorize_factor\n schedule_params.unroll_factor_outer = scheduler_config.outer_unroll\n schedule_params.unroll_factor_inner = scheduler_config.inner_unroll\n schedule_params.lparams.bdimx = scheduler_config.bdim[0]\n schedule_params.lparams.bdimy = scheduler_config.bdim[1]\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotunePointwise(\n selected_fusion=AutotunePointwise.FUSION.GELU_BIAS\n )\n\n # ============================ Run Experiments ============================\n\n parameters, performance = collect_data(script_config, autotune_config)\n\n # ============================ Separate Data ==============================\n\n train_data, test_data = separate_data(script_config, parameters, performance)\n\n # ========================= Train Regression Models =======================\n\n # Apply machine learning regressor\n # Given input shapes and scheduler parameters, predict performance metric.\n from sklearn import ensemble\n\n train_inputs, train_perf = train_data\n clf = ensemble.RandomForestRegressor()\n clf = clf.fit(train_inputs, train_perf)\n\n # ========================= Test Regression Models ========================\n test_model_rmse(clf, script_config, autotune_config, test_data)\n test_model(clf, script_config, autotune_config)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.FUSION","uri":"program://Fuser/class/doc.dev.python_scheduling.autotune_pointwise.FUSION#L66-L70","kind":"class","name":"FUSION","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":66,"end_line":70,"context_start_line":46,"context_end_line":90,"code":"#\n# 3. Train a regression model to predict the desired performance metric given\n# some input arguments and a scheduler configuration.\n#\n# 4. Measure the performance of the regression model.\n# - Calculate RMSE of predicted and actual performance on test set.\n# - Find the configuration with the best performance using regression model.\n# Then, compare against the heuristic configuration selected by nvfuser.\n# - For a specific batch size, gather performance across a range of hidden\n# sizes. Calculate performance for best predicted and nvfuser\n# configurations. Plot a chart comparing performance using matplotlib.\n#\n# The selected performance metric is effective_bandwidth_gbs. The empirical\n# scheduler selects the configuration that has the highest predicted\n# effective_bandwidth_gbs.\n\n# ============================ Configurations ============================\n\n\nclass AutotunePointwise:\n class FUSION(Enum):\n GELU_BIAS = 1\n SILU_MUL = 2\n BCAST_ADD = 3\n MUL = 4\n\n @dataclass(unsafe_hash=True)\n class PointwiseConfiguration:\n break_point: int\n bdim: [int]\n vectorize_factor: int\n outer_unroll: int\n inner_unroll: int\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n def __repr__(self):\n return f\"pointwise_{self.selected_fusion.name}\"\n\n # For pointwise scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n def _named_product(**items):\n return itertools.starmap(","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.PointwiseConfiguration","uri":"program://Fuser/class/doc.dev.python_scheduling.autotune_pointwise.PointwiseConfiguration#L73-L78","kind":"class","name":"PointwiseConfiguration","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":73,"end_line":78,"context_start_line":53,"context_end_line":98,"code":"# Then, compare against the heuristic configuration selected by nvfuser.\n# - For a specific batch size, gather performance across a range of hidden\n# sizes. Calculate performance for best predicted and nvfuser\n# configurations. Plot a chart comparing performance using matplotlib.\n#\n# The selected performance metric is effective_bandwidth_gbs. The empirical\n# scheduler selects the configuration that has the highest predicted\n# effective_bandwidth_gbs.\n\n# ============================ Configurations ============================\n\n\nclass AutotunePointwise:\n class FUSION(Enum):\n GELU_BIAS = 1\n SILU_MUL = 2\n BCAST_ADD = 3\n MUL = 4\n\n @dataclass(unsafe_hash=True)\n class PointwiseConfiguration:\n break_point: int\n bdim: [int]\n vectorize_factor: int\n outer_unroll: int\n inner_unroll: int\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n def __repr__(self):\n return f\"pointwise_{self.selected_fusion.name}\"\n\n # For pointwise scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n def _named_product(**items):\n return itertools.starmap(\n self.PointwiseConfiguration, itertools.product(*items.values())\n )\n\n num_dimensions = len(input_shape)\n warp_size = 32\n warp_group = warp_size * 4\n # limited to a maximum of 128 threads because of pointwise scheduler\n max_threads_per_cta = 128","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.__init__","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.__init__#L80-L81","kind":"function","name":"__init__","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":80,"end_line":81,"context_start_line":60,"context_end_line":101,"code":"# effective_bandwidth_gbs.\n\n# ============================ Configurations ============================\n\n\nclass AutotunePointwise:\n class FUSION(Enum):\n GELU_BIAS = 1\n SILU_MUL = 2\n BCAST_ADD = 3\n MUL = 4\n\n @dataclass(unsafe_hash=True)\n class PointwiseConfiguration:\n break_point: int\n bdim: [int]\n vectorize_factor: int\n outer_unroll: int\n inner_unroll: int\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n def __repr__(self):\n return f\"pointwise_{self.selected_fusion.name}\"\n\n # For pointwise scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n def _named_product(**items):\n return itertools.starmap(\n self.PointwiseConfiguration, itertools.product(*items.values())\n )\n\n num_dimensions = len(input_shape)\n warp_size = 32\n warp_group = warp_size * 4\n # limited to a maximum of 128 threads because of pointwise scheduler\n max_threads_per_cta = 128\n threads_per_cta = list(range(warp_group, max_threads_per_cta + 1, warp_group))\n\n scheduler_configs = []","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.__repr__","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.__repr__#L83-L84","kind":"function","name":"__repr__","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":83,"end_line":84,"context_start_line":63,"context_end_line":104,"code":"\n\nclass AutotunePointwise:\n class FUSION(Enum):\n GELU_BIAS = 1\n SILU_MUL = 2\n BCAST_ADD = 3\n MUL = 4\n\n @dataclass(unsafe_hash=True)\n class PointwiseConfiguration:\n break_point: int\n bdim: [int]\n vectorize_factor: int\n outer_unroll: int\n inner_unroll: int\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n def __repr__(self):\n return f\"pointwise_{self.selected_fusion.name}\"\n\n # For pointwise scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n def _named_product(**items):\n return itertools.starmap(\n self.PointwiseConfiguration, itertools.product(*items.values())\n )\n\n num_dimensions = len(input_shape)\n warp_size = 32\n warp_group = warp_size * 4\n # limited to a maximum of 128 threads because of pointwise scheduler\n max_threads_per_cta = 128\n threads_per_cta = list(range(warp_group, max_threads_per_cta + 1, warp_group))\n\n scheduler_configs = []\n for bp in range(num_dimensions):\n for num_threads in threads_per_cta:\n if bp == 0:","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.generate_scheduler_configurations","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.generate_scheduler_configurations#L88-L135","kind":"function","name":"generate_scheduler_configurations","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":88,"end_line":135,"context_start_line":68,"context_end_line":155,"code":" SILU_MUL = 2\n BCAST_ADD = 3\n MUL = 4\n\n @dataclass(unsafe_hash=True)\n class PointwiseConfiguration:\n break_point: int\n bdim: [int]\n vectorize_factor: int\n outer_unroll: int\n inner_unroll: int\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n def __repr__(self):\n return f\"pointwise_{self.selected_fusion.name}\"\n\n # For pointwise scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n def _named_product(**items):\n return itertools.starmap(\n self.PointwiseConfiguration, itertools.product(*items.values())\n )\n\n num_dimensions = len(input_shape)\n warp_size = 32\n warp_group = warp_size * 4\n # limited to a maximum of 128 threads because of pointwise scheduler\n max_threads_per_cta = 128\n threads_per_cta = list(range(warp_group, max_threads_per_cta + 1, warp_group))\n\n scheduler_configs = []\n for bp in range(num_dimensions):\n for num_threads in threads_per_cta:\n if bp == 0:\n # 1D scheduler configurations\n bdim_shapes = [(num_threads, 1)]\n outer_unroll_range = [1]\n # unroll_factor is between [1, 9]\n inner_unroll_range = range(1, 10)\n else:\n # 2D scheduler configurations\n max_bdimy = num_threads // warp_size\n log2_max_bdimy = int(math.log2(max_bdimy))\n bdimy_configs = [\n 2**log_bdimy for log_bdimy in range(1, log2_max_bdimy + 1)\n ]\n\n bdim_shapes = [\n (max(warp_size, num_threads // bdimy), bdimy)\n for bdimy in bdimy_configs\n ]\n # total_unroll_factor is between [1, 9] given that outer and\n # inner unroll factors are between [1, 3].\n outer_unroll_range = range(1, 4)\n inner_unroll_range = range(1, 4)\n\n scheduler_config = _named_product(\n break_point=[bp],\n bdim=bdim_shapes,\n vectorize_factor=[1, 2, 4, 8],\n outer_unroll=outer_unroll_range,\n inner_unroll=inner_unroll_range,\n )\n scheduler_configs.append(scheduler_config)\n return itertools.chain(*scheduler_configs)\n\n def create_inputs(self, shape, tensor_datatype):\n def outer_bcast():\n return [\n torch.randn(1, shape[-1], dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def inner_bcast():\n return [\n torch.randn(shape[0], 1, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def full():\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.create_inputs","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.create_inputs#L137-L163","kind":"function","name":"create_inputs","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":137,"end_line":163,"context_start_line":117,"context_end_line":183,"code":"\n bdim_shapes = [\n (max(warp_size, num_threads // bdimy), bdimy)\n for bdimy in bdimy_configs\n ]\n # total_unroll_factor is between [1, 9] given that outer and\n # inner unroll factors are between [1, 3].\n outer_unroll_range = range(1, 4)\n inner_unroll_range = range(1, 4)\n\n scheduler_config = _named_product(\n break_point=[bp],\n bdim=bdim_shapes,\n vectorize_factor=[1, 2, 4, 8],\n outer_unroll=outer_unroll_range,\n inner_unroll=inner_unroll_range,\n )\n scheduler_configs.append(scheduler_config)\n return itertools.chain(*scheduler_configs)\n\n def create_inputs(self, shape, tensor_datatype):\n def outer_bcast():\n return [\n torch.randn(1, shape[-1], dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def inner_bcast():\n return [\n torch.randn(shape[0], 1, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def full():\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return outer_bcast()\n elif self.selected_fusion in [self.FUSION.SILU_MUL, self.FUSION.MUL]:\n return full()\n elif self.selected_fusion == FUSION.BCAST_ADD:\n return inner_bcast()\n else:\n assert False\n\n # A decorator to create a pointwise fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def gelu_bias(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T6 = fd.ops.cast(T1, dtype=DataType.Float)\n T7 = fd.ops.cast(T0, dtype=DataType.Float)","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.create_fusion_func","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.create_fusion_func#L166-L279","kind":"function","name":"create_fusion_func","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":166,"end_line":279,"context_start_line":146,"context_end_line":299,"code":" torch.randn(shape[0], 1, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def full():\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return outer_bcast()\n elif self.selected_fusion in [self.FUSION.SILU_MUL, self.FUSION.MUL]:\n return full()\n elif self.selected_fusion == FUSION.BCAST_ADD:\n return inner_bcast()\n else:\n assert False\n\n # A decorator to create a pointwise fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def gelu_bias(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T6 = fd.ops.cast(T1, dtype=DataType.Float)\n T7 = fd.ops.cast(T0, dtype=DataType.Float)\n T8 = fd.ops.add(T6, T7)\n T9 = fd.ops.mul(T8, T8)\n T10 = fd.ops.mul(T9, T8)\n S11 = fd.define_scalar(0.500000, dtype=DataType.Double)\n T12 = fd.ops.mul(S11, T8)\n S13 = fd.define_scalar(0.0447150, dtype=DataType.Double)\n T14 = fd.ops.mul(S13, T10)\n T15 = fd.ops.add(T8, T14)\n S16 = fd.define_scalar(0.797885, dtype=DataType.Double)\n T17 = fd.ops.mul(S16, T15)\n T18 = fd.ops.tanh(T17)\n S19 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T20 = fd.ops.add(S19, T18)\n T21 = fd.ops.mul(T12, T20)\n T22 = fd.ops.cast(T21, dtype=DataType.BFloat16)\n fd.add_output(T22)\n\n def silu_mul(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.neg(T2)\n T4 = fd.ops.exp(T3)\n S5 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T6 = fd.ops.add(S5, T4)\n T7 = fd.ops.reciprocal(T6)\n T8 = fd.ops.mul(T2, T7)\n T9 = fd.ops.cast(T1, dtype=DataType.Float)\n T10 = fd.ops.mul(T8, T9)\n T11 = fd.ops.cast(T10, dtype=DataType.BFloat16)\n fd.add_output(T11)\n\n def bcast_add(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, 1],\n contiguity=[True, None],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.add(T2, T3)\n T5 = fd.ops.cast(T4, dtype=DataType.BFloat16)\n fd.add_output(T5)\n\n def mul(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.mul(T2, T3)\n T5 = fd.ops.cast(T4, dtype=DataType.BFloat16)\n fd.add_output(T5)\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias\n elif self.selected_fusion == self.FUSION.SILU_MUL:\n return silu_mul\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add\n elif self.selected_fusion == self.FUSION.MUL:\n return mul\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def gelu_bias(inputs):\n return torch.nn.functional.gelu(\n inputs[0] + inputs[1].unsqueeze(0), approximate=\"tanh\"\n )\n\n def silu_mul(inputs):\n return torch.nn.functional.silu(inputs[0]) * inputs[1]\n\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.eager_reference","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.eager_reference#L282-L306","kind":"function","name":"eager_reference","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":282,"end_line":306,"context_start_line":262,"context_end_line":326,"code":" stride_order=[1, 0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.mul(T2, T3)\n T5 = fd.ops.cast(T4, dtype=DataType.BFloat16)\n fd.add_output(T5)\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias\n elif self.selected_fusion == self.FUSION.SILU_MUL:\n return silu_mul\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add\n elif self.selected_fusion == self.FUSION.MUL:\n return mul\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def gelu_bias(inputs):\n return torch.nn.functional.gelu(\n inputs[0] + inputs[1].unsqueeze(0), approximate=\"tanh\"\n )\n\n def silu_mul(inputs):\n return torch.nn.functional.silu(inputs[0]) * inputs[1]\n\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:\n return silu_mul(inputs)\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add(inputs)\n elif self.selected_fusion == self.FUSION.MUL:\n return mul(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with pointwise scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.pointwise)\n assert status\n\n schedule_params = fd.sched.compute_pointwise_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n schedule_params.break_point = scheduler_config.break_point\n schedule_params.vectorization_factor = scheduler_config.vectorize_factor\n schedule_params.unroll_factor_outer = scheduler_config.outer_unroll\n schedule_params.unroll_factor_inner = scheduler_config.inner_unroll\n schedule_params.lparams.bdimx = scheduler_config.bdim[0]\n schedule_params.lparams.bdimy = scheduler_config.bdim[1]\n\n # Schedule fusion","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.custom_scheduler","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.custom_scheduler#L309-L330","kind":"function","name":"custom_scheduler","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":309,"end_line":330,"context_start_line":289,"context_end_line":350,"code":" return torch.nn.functional.silu(inputs[0]) * inputs[1]\n\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:\n return silu_mul(inputs)\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add(inputs)\n elif self.selected_fusion == self.FUSION.MUL:\n return mul(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with pointwise scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.pointwise)\n assert status\n\n schedule_params = fd.sched.compute_pointwise_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n schedule_params.break_point = scheduler_config.break_point\n schedule_params.vectorization_factor = scheduler_config.vectorize_factor\n schedule_params.unroll_factor_outer = scheduler_config.outer_unroll\n schedule_params.unroll_factor_inner = scheduler_config.inner_unroll\n schedule_params.lparams.bdimx = scheduler_config.bdim[0]\n schedule_params.lparams.bdimy = scheduler_config.bdim[1]\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotunePointwise(\n selected_fusion=AutotunePointwise.FUSION.GELU_BIAS\n )\n\n # ============================ Run Experiments ============================","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise._named_product","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise._named_product#L89-L92","kind":"function","name":"_named_product","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":89,"end_line":92,"context_start_line":69,"context_end_line":112,"code":" BCAST_ADD = 3\n MUL = 4\n\n @dataclass(unsafe_hash=True)\n class PointwiseConfiguration:\n break_point: int\n bdim: [int]\n vectorize_factor: int\n outer_unroll: int\n inner_unroll: int\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n def __repr__(self):\n return f\"pointwise_{self.selected_fusion.name}\"\n\n # For pointwise scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n def _named_product(**items):\n return itertools.starmap(\n self.PointwiseConfiguration, itertools.product(*items.values())\n )\n\n num_dimensions = len(input_shape)\n warp_size = 32\n warp_group = warp_size * 4\n # limited to a maximum of 128 threads because of pointwise scheduler\n max_threads_per_cta = 128\n threads_per_cta = list(range(warp_group, max_threads_per_cta + 1, warp_group))\n\n scheduler_configs = []\n for bp in range(num_dimensions):\n for num_threads in threads_per_cta:\n if bp == 0:\n # 1D scheduler configurations\n bdim_shapes = [(num_threads, 1)]\n outer_unroll_range = [1]\n # unroll_factor is between [1, 9]\n inner_unroll_range = range(1, 10)\n else:\n # 2D scheduler configurations\n max_bdimy = num_threads // warp_size","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.outer_bcast","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.outer_bcast#L138-L142","kind":"function","name":"outer_bcast","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":138,"end_line":142,"context_start_line":118,"context_end_line":162,"code":" bdim_shapes = [\n (max(warp_size, num_threads // bdimy), bdimy)\n for bdimy in bdimy_configs\n ]\n # total_unroll_factor is between [1, 9] given that outer and\n # inner unroll factors are between [1, 3].\n outer_unroll_range = range(1, 4)\n inner_unroll_range = range(1, 4)\n\n scheduler_config = _named_product(\n break_point=[bp],\n bdim=bdim_shapes,\n vectorize_factor=[1, 2, 4, 8],\n outer_unroll=outer_unroll_range,\n inner_unroll=inner_unroll_range,\n )\n scheduler_configs.append(scheduler_config)\n return itertools.chain(*scheduler_configs)\n\n def create_inputs(self, shape, tensor_datatype):\n def outer_bcast():\n return [\n torch.randn(1, shape[-1], dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def inner_bcast():\n return [\n torch.randn(shape[0], 1, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def full():\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return outer_bcast()\n elif self.selected_fusion in [self.FUSION.SILU_MUL, self.FUSION.MUL]:\n return full()\n elif self.selected_fusion == FUSION.BCAST_ADD:\n return inner_bcast()\n else:","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.inner_bcast","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.inner_bcast#L144-L148","kind":"function","name":"inner_bcast","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":144,"end_line":148,"context_start_line":124,"context_end_line":168,"code":" outer_unroll_range = range(1, 4)\n inner_unroll_range = range(1, 4)\n\n scheduler_config = _named_product(\n break_point=[bp],\n bdim=bdim_shapes,\n vectorize_factor=[1, 2, 4, 8],\n outer_unroll=outer_unroll_range,\n inner_unroll=inner_unroll_range,\n )\n scheduler_configs.append(scheduler_config)\n return itertools.chain(*scheduler_configs)\n\n def create_inputs(self, shape, tensor_datatype):\n def outer_bcast():\n return [\n torch.randn(1, shape[-1], dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def inner_bcast():\n return [\n torch.randn(shape[0], 1, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def full():\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return outer_bcast()\n elif self.selected_fusion in [self.FUSION.SILU_MUL, self.FUSION.MUL]:\n return full()\n elif self.selected_fusion == FUSION.BCAST_ADD:\n return inner_bcast()\n else:\n assert False\n\n # A decorator to create a pointwise fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def gelu_bias(fd: FusionDefinition):\n T0 = fd.define_tensor(","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.full","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.full#L150-L154","kind":"function","name":"full","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":150,"end_line":154,"context_start_line":130,"context_end_line":174,"code":" vectorize_factor=[1, 2, 4, 8],\n outer_unroll=outer_unroll_range,\n inner_unroll=inner_unroll_range,\n )\n scheduler_configs.append(scheduler_config)\n return itertools.chain(*scheduler_configs)\n\n def create_inputs(self, shape, tensor_datatype):\n def outer_bcast():\n return [\n torch.randn(1, shape[-1], dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def inner_bcast():\n return [\n torch.randn(shape[0], 1, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n def full():\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\"),\n ]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return outer_bcast()\n elif self.selected_fusion in [self.FUSION.SILU_MUL, self.FUSION.MUL]:\n return full()\n elif self.selected_fusion == FUSION.BCAST_ADD:\n return inner_bcast()\n else:\n assert False\n\n # A decorator to create a pointwise fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def gelu_bias(fd: FusionDefinition):\n T0 = fd.define_tensor(\n shape=[1, -1],\n contiguity=[None, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.gelu_bias","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.gelu_bias#L283-L286","kind":"function","name":"gelu_bias","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":283,"end_line":286,"context_start_line":263,"context_end_line":306,"code":" )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.mul(T2, T3)\n T5 = fd.ops.cast(T4, dtype=DataType.BFloat16)\n fd.add_output(T5)\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias\n elif self.selected_fusion == self.FUSION.SILU_MUL:\n return silu_mul\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add\n elif self.selected_fusion == self.FUSION.MUL:\n return mul\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def gelu_bias(inputs):\n return torch.nn.functional.gelu(\n inputs[0] + inputs[1].unsqueeze(0), approximate=\"tanh\"\n )\n\n def silu_mul(inputs):\n return torch.nn.functional.silu(inputs[0]) * inputs[1]\n\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:\n return silu_mul(inputs)\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add(inputs)\n elif self.selected_fusion == self.FUSION.MUL:\n return mul(inputs)\n else:\n assert False","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.silu_mul","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.silu_mul#L288-L289","kind":"function","name":"silu_mul","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":288,"end_line":289,"context_start_line":268,"context_end_line":309,"code":" fd.add_output(T5)\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias\n elif self.selected_fusion == self.FUSION.SILU_MUL:\n return silu_mul\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add\n elif self.selected_fusion == self.FUSION.MUL:\n return mul\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def gelu_bias(inputs):\n return torch.nn.functional.gelu(\n inputs[0] + inputs[1].unsqueeze(0), approximate=\"tanh\"\n )\n\n def silu_mul(inputs):\n return torch.nn.functional.silu(inputs[0]) * inputs[1]\n\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:\n return silu_mul(inputs)\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add(inputs)\n elif self.selected_fusion == self.FUSION.MUL:\n return mul(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.bcast_add","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.bcast_add#L291-L292","kind":"function","name":"bcast_add","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":291,"end_line":292,"context_start_line":271,"context_end_line":312,"code":" return gelu_bias\n elif self.selected_fusion == self.FUSION.SILU_MUL:\n return silu_mul\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add\n elif self.selected_fusion == self.FUSION.MUL:\n return mul\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def gelu_bias(inputs):\n return torch.nn.functional.gelu(\n inputs[0] + inputs[1].unsqueeze(0), approximate=\"tanh\"\n )\n\n def silu_mul(inputs):\n return torch.nn.functional.silu(inputs[0]) * inputs[1]\n\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:\n return silu_mul(inputs)\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add(inputs)\n elif self.selected_fusion == self.FUSION.MUL:\n return mul(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with pointwise scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.pointwise)","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.mul","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.mul#L294-L295","kind":"function","name":"mul","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":294,"end_line":295,"context_start_line":274,"context_end_line":315,"code":" elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add\n elif self.selected_fusion == self.FUSION.MUL:\n return mul\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def gelu_bias(inputs):\n return torch.nn.functional.gelu(\n inputs[0] + inputs[1].unsqueeze(0), approximate=\"tanh\"\n )\n\n def silu_mul(inputs):\n return torch.nn.functional.silu(inputs[0]) * inputs[1]\n\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:\n return silu_mul(inputs)\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add(inputs)\n elif self.selected_fusion == self.FUSION.MUL:\n return mul(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with pointwise scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.pointwise)\n assert status\n\n schedule_params = fd.sched.compute_pointwise_heuristics()","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_pointwise.inner_fn","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_pointwise.inner_fn#L310-L327","kind":"function","name":"inner_fn","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":310,"end_line":327,"context_start_line":290,"context_end_line":347,"code":"\n def bcast_add(inputs):\n return inputs[0] + inputs[1]\n\n def mul(inputs):\n return inputs[0] * inputs[1]\n\n if self.selected_fusion == self.FUSION.GELU_BIAS:\n return gelu_bias(inputs)\n elif self.selected__fusion == self.FUSION.SILU_MUL:\n return silu_mul(inputs)\n elif self.selected_fusion == self.FUSION.BCAST_ADD:\n return bcast_add(inputs)\n elif self.selected_fusion == self.FUSION.MUL:\n return mul(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with pointwise scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.pointwise)\n assert status\n\n schedule_params = fd.sched.compute_pointwise_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n schedule_params.break_point = scheduler_config.break_point\n schedule_params.vectorization_factor = scheduler_config.vectorize_factor\n schedule_params.unroll_factor_outer = scheduler_config.outer_unroll\n schedule_params.unroll_factor_inner = scheduler_config.inner_unroll\n schedule_params.lparams.bdimx = scheduler_config.bdim[0]\n schedule_params.lparams.bdimy = scheduler_config.bdim[1]\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotunePointwise(\n selected_fusion=AutotunePointwise.FUSION.GELU_BIAS","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_matmul","uri":"program://Fuser/module/doc.dev.python_scheduling.autotune_matmul#L1-L114","kind":"module","name":"doc.dev.python_scheduling.autotune_matmul","path":"doc/dev/python_scheduling/autotune_matmul.py","language":"python","start_line":1,"end_line":114,"context_start_line":1,"context_end_line":114,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport itertools\n\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import FusionDefinition, SchedulerType\n\n# Description of the problem\nM = 512\nN = 512\nK = 4096\ndtype = torch.bfloat16\n# TODO: layout\n\n# These are the parameters we'll optimize\nparameter_configurations = [\n splitk_factors := list(range(1, 8)),\n load_stages := list(range(1, 4)),\n]\n\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n return torch.matmul(inputs[0], inputs[1])\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_matmul_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with matmul scheduler\n status, error = fd.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = fd.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n if config is not None:\n splitk_factor, stages = config\n schedule_params.circular_buffer_options.circular_buffer_smem_write = (\n stages > 1\n )\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n schedule_params.splitk_factor = splitk_factor\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(presched_fd, inputs, config=None, num_iterations=10):\n scheduled_fd = custom_matmul_scheduler(presched_fd, config)\n\n mean_bw = 0\n mean_time = 0.0\n for iteration in range(num_iterations):\n nvf_outputs = scheduled_fd.execute(inputs, profile=True)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n mean_bw += (bandwidth - mean_bw) / (iteration + 1)\n mean_time += (time - mean_time) / (iteration + 1)\n\n # validate correctness\n # assert torch.allclose(nvf_outputs[0], eager_reference(inputs))\n\n return mean_bw, mean_time\n\n\n# exhaustively search for best time\ninputs = [\n torch.randn((M, K), dtype=dtype, device=\"cuda\"),\n torch.randn((K, N), dtype=dtype, device=\"cuda\"),\n]\n\nwith FusionDefinition() as presched_fd:\n create_fusion_func(inputs)(presched_fd)\n\noptimal_config = None\noptimal_perf = None\nfor config in itertools.product(splitk_factors, load_stages):\n splitk_factor, stages = config\n # TODO: introduce a utility to check if this config is valid.\n # For example, it should check on smem reuse\n bw, kernel_time = run_profile(presched_fd, inputs, config)\n perf_metric = kernel_time\n\n print(f\" sk={splitk_factor} st={stages} bw={bw} kernel_time={kernel_time}\")\n\n if optimal_config is None or perf_metric < optimal_perf:\n optimal_config = config\n optimal_perf = perf_metric\n\nprint(\n f\"M={M} N={N} K={K} optimal splitk={optimal_config[0]} stages={optimal_config[1]}\"\n)","source_hash":"731e4216a6cfaac03c8a5743a40137e6c028b32c7929d63fec21b30408fbb057","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_matmul.create_fusion_func","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_matmul.create_fusion_func#L27-L34","kind":"function","name":"create_fusion_func","path":"doc/dev/python_scheduling/autotune_matmul.py","language":"python","start_line":27,"end_line":34,"context_start_line":7,"context_end_line":54,"code":"import itertools\n\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import FusionDefinition, SchedulerType\n\n# Description of the problem\nM = 512\nN = 512\nK = 4096\ndtype = torch.bfloat16\n# TODO: layout\n\n# These are the parameters we'll optimize\nparameter_configurations = [\n splitk_factors := list(range(1, 8)),\n load_stages := list(range(1, 4)),\n]\n\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n return torch.matmul(inputs[0], inputs[1])\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_matmul_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with matmul scheduler\n status, error = fd.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = fd.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n if config is not None:\n splitk_factor, stages = config\n schedule_params.circular_buffer_options.circular_buffer_smem_write = (","source_hash":"731e4216a6cfaac03c8a5743a40137e6c028b32c7929d63fec21b30408fbb057","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_matmul.eager_reference","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_matmul.eager_reference#L38-L39","kind":"function","name":"eager_reference","path":"doc/dev/python_scheduling/autotune_matmul.py","language":"python","start_line":38,"end_line":39,"context_start_line":18,"context_end_line":59,"code":"\n# These are the parameters we'll optimize\nparameter_configurations = [\n splitk_factors := list(range(1, 8)),\n load_stages := list(range(1, 4)),\n]\n\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n return torch.matmul(inputs[0], inputs[1])\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_matmul_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with matmul scheduler\n status, error = fd.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = fd.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n if config is not None:\n splitk_factor, stages = config\n schedule_params.circular_buffer_options.circular_buffer_smem_write = (\n stages > 1\n )\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n schedule_params.splitk_factor = splitk_factor\n","source_hash":"731e4216a6cfaac03c8a5743a40137e6c028b32c7929d63fec21b30408fbb057","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_matmul.custom_matmul_scheduler","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_matmul.custom_matmul_scheduler#L43-L64","kind":"function","name":"custom_matmul_scheduler","path":"doc/dev/python_scheduling/autotune_matmul.py","language":"python","start_line":43,"end_line":64,"context_start_line":23,"context_end_line":84,"code":"]\n\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n return torch.matmul(inputs[0], inputs[1])\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_matmul_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with matmul scheduler\n status, error = fd.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = fd.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n if config is not None:\n splitk_factor, stages = config\n schedule_params.circular_buffer_options.circular_buffer_smem_write = (\n stages > 1\n )\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n schedule_params.splitk_factor = splitk_factor\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(presched_fd, inputs, config=None, num_iterations=10):\n scheduled_fd = custom_matmul_scheduler(presched_fd, config)\n\n mean_bw = 0\n mean_time = 0.0\n for iteration in range(num_iterations):\n nvf_outputs = scheduled_fd.execute(inputs, profile=True)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n mean_bw += (bandwidth - mean_bw) / (iteration + 1)\n mean_time += (time - mean_time) / (iteration + 1)\n\n # validate correctness\n # assert torch.allclose(nvf_outputs[0], eager_reference(inputs))\n","source_hash":"731e4216a6cfaac03c8a5743a40137e6c028b32c7929d63fec21b30408fbb057","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_matmul.run_profile","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_matmul.run_profile#L68-L85","kind":"function","name":"run_profile","path":"doc/dev/python_scheduling/autotune_matmul.py","language":"python","start_line":68,"end_line":85,"context_start_line":48,"context_end_line":105,"code":"\n schedule_params = fd.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n if config is not None:\n splitk_factor, stages = config\n schedule_params.circular_buffer_options.circular_buffer_smem_write = (\n stages > 1\n )\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n schedule_params.splitk_factor = splitk_factor\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(presched_fd, inputs, config=None, num_iterations=10):\n scheduled_fd = custom_matmul_scheduler(presched_fd, config)\n\n mean_bw = 0\n mean_time = 0.0\n for iteration in range(num_iterations):\n nvf_outputs = scheduled_fd.execute(inputs, profile=True)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n mean_bw += (bandwidth - mean_bw) / (iteration + 1)\n mean_time += (time - mean_time) / (iteration + 1)\n\n # validate correctness\n # assert torch.allclose(nvf_outputs[0], eager_reference(inputs))\n\n return mean_bw, mean_time\n\n\n# exhaustively search for best time\ninputs = [\n torch.randn((M, K), dtype=dtype, device=\"cuda\"),\n torch.randn((K, N), dtype=dtype, device=\"cuda\"),\n]\n\nwith FusionDefinition() as presched_fd:\n create_fusion_func(inputs)(presched_fd)\n\noptimal_config = None\noptimal_perf = None\nfor config in itertools.product(splitk_factors, load_stages):\n splitk_factor, stages = config\n # TODO: introduce a utility to check if this config is valid.\n # For example, it should check on smem reuse\n bw, kernel_time = run_profile(presched_fd, inputs, config)\n perf_metric = kernel_time\n","source_hash":"731e4216a6cfaac03c8a5743a40137e6c028b32c7929d63fec21b30408fbb057","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_matmul.fusion_func","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_matmul.fusion_func#L28-L32","kind":"function","name":"fusion_func","path":"doc/dev/python_scheduling/autotune_matmul.py","language":"python","start_line":28,"end_line":32,"context_start_line":8,"context_end_line":52,"code":"\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import FusionDefinition, SchedulerType\n\n# Description of the problem\nM = 512\nN = 512\nK = 4096\ndtype = torch.bfloat16\n# TODO: layout\n\n# These are the parameters we'll optimize\nparameter_configurations = [\n splitk_factors := list(range(1, 8)),\n load_stages := list(range(1, 4)),\n]\n\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n return torch.matmul(inputs[0], inputs[1])\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_matmul_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with matmul scheduler\n status, error = fd.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = fd.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n if config is not None:","source_hash":"731e4216a6cfaac03c8a5743a40137e6c028b32c7929d63fec21b30408fbb057","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_matmul.inner_fn","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_matmul.inner_fn#L44-L61","kind":"function","name":"inner_fn","path":"doc/dev/python_scheduling/autotune_matmul.py","language":"python","start_line":44,"end_line":61,"context_start_line":24,"context_end_line":81,"code":"\n\n# A decorator to create a pointwise fusion given some input arguments.\ndef create_fusion_func(inputs):\n def fusion_func(fd: FusionDefinition):\n t0 = fd.from_pytorch(inputs[0])\n t1 = fd.from_pytorch(inputs[1])\n t2 = fd.ops.matmul(t0, t1)\n fd.add_output(t2)\n\n return fusion_func\n\n\n# The pytorch eager mode reference used to validating nvfuser kernel.\ndef eager_reference(inputs):\n return torch.matmul(inputs[0], inputs[1])\n\n\n# Apply scheduler with custom parameters using decorator\ndef custom_matmul_scheduler(fd, config):\n def inner_fn():\n # Check if compatible with matmul scheduler\n status, error = fd.sched.can_schedule(SchedulerType.matmul)\n assert status, error\n\n schedule_params = fd.sched.compute_matmul_heuristics()\n\n # Modify original parameters\n if config is not None:\n splitk_factor, stages = config\n schedule_params.circular_buffer_options.circular_buffer_smem_write = (\n stages > 1\n )\n schedule_params.circular_buffer_options.smem_circular_buffer_stage = stages\n schedule_params.splitk_factor = splitk_factor\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Apply schedule decorator, run fusion, and profile performance\ndef run_profile(presched_fd, inputs, config=None, num_iterations=10):\n scheduled_fd = custom_matmul_scheduler(presched_fd, config)\n\n mean_bw = 0\n mean_time = 0.0\n for iteration in range(num_iterations):\n nvf_outputs = scheduled_fd.execute(inputs, profile=True)\n\n prof = scheduled_fd.profile()\n bandwidth = prof.kernel_profiles[0].effective_bandwidth_gbs\n time = prof.kernel_profiles[0].time_ms\n mean_bw += (bandwidth - mean_bw) / (iteration + 1)\n mean_time += (time - mean_time) / (iteration + 1)\n","source_hash":"731e4216a6cfaac03c8a5743a40137e6c028b32c7929d63fec21b30408fbb057","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction","uri":"program://Fuser/module/doc.dev.python_scheduling.autotune_inner_reduction#L1-L440","kind":"module","name":"doc.dev.python_scheduling.autotune_inner_reduction","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":1,"end_line":440,"context_start_line":1,"context_end_line":440,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport itertools\n\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import FusionDefinition, SchedulerType, DataType, ParallelType\nfrom enum import Enum\nfrom dataclasses import dataclass\n\nfrom autotune_utils import (\n ScriptConfiguration,\n collect_data,\n separate_data,\n test_model_rmse,\n test_model,\n ceil_div,\n floor_div,\n)\n\n\n# ================================ Description ================================\n\n# This script defines four inner reduction fusions:\n#\n# 1. Inner Sum\n# y = sum(x, dim=-1)\n#\n# 2. Add Sum\n# z = sum(x1 + x2 + x3 + x4, dim=-1)\n#\n# 3. Tanh Sum\n# y = sum(tanh(x), dim=-1)\n#\n# 4. Exp Sum\n# z = sum(exp(x), dim=-1)\n#\n# Script Sequence:\n#\n# 1. Define a nvfuser fusion and its pytorch eager mode reference.\n#\n# 2. Profile the CUDA kernel performance by iterating over a set of input\n# arguments and scheduler configurations.\n#\n# 3. Train a regression model to predict the desired performance metric given\n# some input arguments and a scheduler configuration.\n#\n# 4. Measure the performance of the regression model.\n# - Calculate RMSE of predicted and actual performance on test set.\n# - Find the configuration with the best performance using regression model.\n# Then, compare against the heuristic configuration selected by nvfuser.\n# - For a specific batch size, gather performance across a range of hidden\n# sizes. Calculate performance for best predicted and nvfuser\n# configurations. Plot a chart comparing performance using matplotlib.\n#\n# The selected performance metric is effective_bandwidth_gbs. The empirical\n# scheduler selects the configuration that has the highest predicted\n# effective_bandwidth_gbs.\n\n# =============================================================================\n\n\nclass AutotuneInnerReduction:\n class FUSION(Enum):\n INNER_SUM = 1\n ADD_SUM = 2\n TANH_SUM = 3\n EXP_SUM = 4\n\n @dataclass(unsafe_hash=True)\n class InnerReductionConfiguration:\n # The vectorization factor for inner reduction domain.\n vectorize_factor: int = 1\n # The unroll factor for the inner reduction domain.\n reduction_unroll_factor: int = 1\n # The unroll factor for the outer iteration domain.\n iteration_unroll_factor: int = 1\n # The grid size for the outer iteration domain.\n # If grdim > 1, then godim corresponds with y axis of the grid.\n # Otherwise, it is the x axis of the grid.\n godim: int = -1\n # The grid size for the inner reduction domain. It corresponds\n # with x axis of the grid when it is >1.\n grdim: int = -1\n # The x axis of CTA. It corresponds with inner reduction domain.\n bdimx: int = -1\n # The y axis of CTA. It corresponds with outer reduction domain.\n # If it is non-zero, then there are multiple reduction per CTA.\n bdimy: int = -1\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n # gpu device properties are defined globally\n assert torch.cuda.is_available()\n self.gpu_properties = torch.cuda.get_device_properties(device=0)\n\n def __repr__(self):\n return f\"inner_reduction_{self.selected_fusion.name}\"\n\n def convert_to_inner_reduction_params(self, scheduler_config, reduction_params):\n warp_size = 32\n max_number_of_threads_cta = 1024\n grid_x_limit = 2147483647\n grid_y_limit = 65535\n\n reduction_params.schedule_3d = False\n reduction_params.fastest_dim = True\n reduction_params.cross_block_inner_reduction = True\n reduction_params.block_dim_inner_reduction = ParallelType.block_x\n reduction_params.cross_grid_inner_reduction = scheduler_config.grdim > 1\n reduction_params.multiple_reds_per_blk = scheduler_config.bdimy > 1\n reduction_params.pad_inner_reduction_to_warp = (\n scheduler_config.bdimx > warp_size\n ) and (\n (scheduler_config.bdimx * scheduler_config.bdimy)\n < max_number_of_threads_cta\n )\n reduction_params.unroll_factor_inner_reduction = (\n scheduler_config.vectorize_factor\n )\n reduction_params.vectorize_inner_reduction = (\n scheduler_config.vectorize_factor > 1\n )\n reduction_params.unroll_factor_top_of_vectorization = (\n scheduler_config.reduction_unroll_factor\n )\n\n if scheduler_config.bdimy > 1:\n reduction_params.block_dim_iter_dom = ParallelType.block_y\n\n reduction_params.unroll_factor_iter_dom = (\n scheduler_config.iteration_unroll_factor\n )\n\n gdimx = -1\n gdimy = -1\n\n if scheduler_config.grdim > 1:\n reduction_params.grid_dim_inner_reduction = ParallelType.grid_x\n reduction_params.grid_dim_iter_dom = ParallelType.grid_y\n\n reduction_params.split_grid_dim_iter_dom_inner = True\n gdimx = min(scheduler_config.grdim, grid_x_limit)\n gdimy = min(scheduler_config.godim, grid_y_limit)\n if scheduler_config.godim > grid_y_limit:\n reduction_params.split_grid_dim_iter_dom_outer = True\n else:\n reduction_params.grid_dim_iter_dom = ParallelType.grid_x\n gdimx = min(scheduler_config.godim, grid_x_limit)\n if scheduler_config.godim > grid_x_limit:\n reduction_params.split_grid_dim_inner_reduction = True\n\n reduction_params.lparams.gdimx = gdimx\n reduction_params.lparams.gdimy = gdimy\n\n # Reset CTA dimensions to avoid failing LaunchParams::assertValid\n reduction_params.lparams.bdimx = -1\n reduction_params.lparams.bdimy = -1\n reduction_params.lparams.bdimz = -1\n\n reduction_params.lparams.bdimx = scheduler_config.bdimx\n reduction_params.lparams.bdimy = scheduler_config.bdimy\n\n # For reduction scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n threads_per_cta_options = [128, 256, 512, 1024]\n vectorization_factor_options = [1, 2, 4, 8]\n reduction_unroll_factor_options = list(range(1, 6))\n iteration_unroll_factor_options = list(range(1, 6))\n warp_size = 32\n\n num_iterations, num_reductions = input_shape\n\n for (\n threads_per_cta,\n vectorize_factor,\n reduction_unroll_factor,\n iteration_unroll_factor,\n ) in itertools.product(\n threads_per_cta_options,\n vectorization_factor_options,\n reduction_unroll_factor_options,\n iteration_unroll_factor_options,\n ):\n scheduler_config = self.InnerReductionConfiguration(\n vectorize_factor=vectorize_factor,\n reduction_unroll_factor=reduction_unroll_factor,\n iteration_unroll_factor=iteration_unroll_factor,\n )\n scheduler_config.bdimx = min(\n threads_per_cta,\n max(\n warp_size,\n ceil_div(num_reductions, scheduler_config.vectorize_factor),\n ),\n )\n scheduler_config.bdimy = min(\n threads_per_cta,\n max(1, floor_div(threads_per_cta, scheduler_config.bdimx)),\n )\n scheduler_config.godim = ceil_div(\n num_iterations, scheduler_config.bdimy * iteration_unroll_factor\n )\n\n # number of reduction elements not handled by a CTA\n remaining_reduction = ceil_div(\n ceil_div(\n ceil_div(num_reductions, vectorize_factor), scheduler_config.bdimx\n ),\n reduction_unroll_factor,\n )\n\n if iteration_unroll_factor == 1 and remaining_reduction > 1:\n # all remaining reduction goes to grdim\n scheduler_config.grdim = remaining_reduction\n yield scheduler_config\n\n # When iteration dim is small, there may be unused SMs. We need\n # to shift work from block reduction to grid reduction to\n # increase SM usage.\n godim = scheduler_config.godim\n grdim = 1\n while (\n godim * grdim * 2 <= self.gpu_properties.multi_processor_count\n and (remaining_reduction / grdim) >= 2\n ):\n grdim *= 2\n scheduler_config.grdim = grdim\n yield scheduler_config\n\n # grid stride across reduction iterDomain is 1\n scheduler_config.grdim = 1\n yield scheduler_config\n\n def create_inputs(self, shape, tensor_datatype):\n def inner_fn(num_inputs):\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\")\n for _ in range(num_inputs)\n ]\n\n if self.selected_fusion == self.FUSION.ADD_SUM:\n return inner_fn(num_inputs=4)\n elif self.selected_fusion in [\n self.FUSION.INNER_SUM,\n self.FUSION.TANH_SUM,\n self.FUSION.EXP_SUM,\n ]:\n return inner_fn(num_inputs=1)\n else:\n assert False\n\n # A decorator to create a reduction fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def sum_fusion(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.sum(T1, dims=[1], keepdim=False, dtype=DataType.Null)\n T3 = fd.ops.cast(T2, dtype=DataType.BFloat16)\n fd.add_output(T3)\n\n def add_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T4 = fd.ops.cast(T0, dtype=DataType.Float)\n T5 = fd.ops.cast(T1, dtype=DataType.Float)\n T6 = fd.ops.add(T4, T5)\n T7 = fd.ops.cast(T2, dtype=DataType.Float)\n T8 = fd.ops.add(T6, T7)\n T9 = fd.ops.cast(T3, dtype=DataType.Float)\n T10 = fd.ops.add(T8, T9)\n T11 = fd.ops.sum(T10, dims=[1], keepdim=False, dtype=DataType.Null)\n T12 = fd.ops.cast(T11, dtype=DataType.BFloat16)\n fd.add_output(T12)\n\n def tanh_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.tanh(T1)\n T3 = fd.ops.sum(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.cast(T3, dtype=DataType.BFloat16)\n fd.add_output(T4)\n\n def exp_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.exp(T1)\n T3 = fd.ops.sum(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.cast(T3, dtype=DataType.BFloat16)\n fd.add_output(T4)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def sum_fusion(inputs):\n return torch.sum(inputs[0], dim=-1)\n\n def add_sum(inputs):\n return torch.sum(inputs[0] + inputs[1] + inputs[2] + inputs[3], dim=-1)\n\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum(inputs)\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with reduction scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.reduction)\n assert status\n\n reduction_params = fd.sched.compute_reduction_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n self.convert_to_inner_reduction_params(\n scheduler_config, reduction_params\n )\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotuneInnerReduction(\n selected_fusion=AutotuneInnerReduction.FUSION.INNER_SUM\n )\n\n # ============================ Run Experiments ============================\n\n parameters, performance = collect_data(script_config, autotune_config)\n\n # ============================ Separate Data ==============================\n\n train_data, test_data = separate_data(script_config, parameters, performance)\n\n # ========================= Train Regression Models =======================\n\n # Apply machine learning regressor\n # Given input shapes and scheduler parameters, predict performance metric.\n from sklearn import ensemble\n\n train_inputs, train_perf = train_data\n clf = ensemble.RandomForestRegressor()\n clf = clf.fit(train_inputs, train_perf)\n\n # ========================= Test Regression Models ========================\n test_model_rmse(clf, script_config, autotune_config, test_data)\n test_model(clf, script_config, autotune_config)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.AutotuneInnerReduction","uri":"program://Fuser/class/doc.dev.python_scheduling.autotune_inner_reduction.AutotuneInnerReduction#L66-L396","kind":"class","name":"AutotuneInnerReduction","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":66,"end_line":396,"context_start_line":46,"context_end_line":416,"code":"# arguments and scheduler configurations.\n#\n# 3. Train a regression model to predict the desired performance metric given\n# some input arguments and a scheduler configuration.\n#\n# 4. Measure the performance of the regression model.\n# - Calculate RMSE of predicted and actual performance on test set.\n# - Find the configuration with the best performance using regression model.\n# Then, compare against the heuristic configuration selected by nvfuser.\n# - For a specific batch size, gather performance across a range of hidden\n# sizes. Calculate performance for best predicted and nvfuser\n# configurations. Plot a chart comparing performance using matplotlib.\n#\n# The selected performance metric is effective_bandwidth_gbs. The empirical\n# scheduler selects the configuration that has the highest predicted\n# effective_bandwidth_gbs.\n\n# =============================================================================\n\n\nclass AutotuneInnerReduction:\n class FUSION(Enum):\n INNER_SUM = 1\n ADD_SUM = 2\n TANH_SUM = 3\n EXP_SUM = 4\n\n @dataclass(unsafe_hash=True)\n class InnerReductionConfiguration:\n # The vectorization factor for inner reduction domain.\n vectorize_factor: int = 1\n # The unroll factor for the inner reduction domain.\n reduction_unroll_factor: int = 1\n # The unroll factor for the outer iteration domain.\n iteration_unroll_factor: int = 1\n # The grid size for the outer iteration domain.\n # If grdim > 1, then godim corresponds with y axis of the grid.\n # Otherwise, it is the x axis of the grid.\n godim: int = -1\n # The grid size for the inner reduction domain. It corresponds\n # with x axis of the grid when it is >1.\n grdim: int = -1\n # The x axis of CTA. It corresponds with inner reduction domain.\n bdimx: int = -1\n # The y axis of CTA. It corresponds with outer reduction domain.\n # If it is non-zero, then there are multiple reduction per CTA.\n bdimy: int = -1\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n # gpu device properties are defined globally\n assert torch.cuda.is_available()\n self.gpu_properties = torch.cuda.get_device_properties(device=0)\n\n def __repr__(self):\n return f\"inner_reduction_{self.selected_fusion.name}\"\n\n def convert_to_inner_reduction_params(self, scheduler_config, reduction_params):\n warp_size = 32\n max_number_of_threads_cta = 1024\n grid_x_limit = 2147483647\n grid_y_limit = 65535\n\n reduction_params.schedule_3d = False\n reduction_params.fastest_dim = True\n reduction_params.cross_block_inner_reduction = True\n reduction_params.block_dim_inner_reduction = ParallelType.block_x\n reduction_params.cross_grid_inner_reduction = scheduler_config.grdim > 1\n reduction_params.multiple_reds_per_blk = scheduler_config.bdimy > 1\n reduction_params.pad_inner_reduction_to_warp = (\n scheduler_config.bdimx > warp_size\n ) and (\n (scheduler_config.bdimx * scheduler_config.bdimy)\n < max_number_of_threads_cta\n )\n reduction_params.unroll_factor_inner_reduction = (\n scheduler_config.vectorize_factor\n )\n reduction_params.vectorize_inner_reduction = (\n scheduler_config.vectorize_factor > 1\n )\n reduction_params.unroll_factor_top_of_vectorization = (\n scheduler_config.reduction_unroll_factor\n )\n\n if scheduler_config.bdimy > 1:\n reduction_params.block_dim_iter_dom = ParallelType.block_y\n\n reduction_params.unroll_factor_iter_dom = (\n scheduler_config.iteration_unroll_factor\n )\n\n gdimx = -1\n gdimy = -1\n\n if scheduler_config.grdim > 1:\n reduction_params.grid_dim_inner_reduction = ParallelType.grid_x\n reduction_params.grid_dim_iter_dom = ParallelType.grid_y\n\n reduction_params.split_grid_dim_iter_dom_inner = True\n gdimx = min(scheduler_config.grdim, grid_x_limit)\n gdimy = min(scheduler_config.godim, grid_y_limit)\n if scheduler_config.godim > grid_y_limit:\n reduction_params.split_grid_dim_iter_dom_outer = True\n else:\n reduction_params.grid_dim_iter_dom = ParallelType.grid_x\n gdimx = min(scheduler_config.godim, grid_x_limit)\n if scheduler_config.godim > grid_x_limit:\n reduction_params.split_grid_dim_inner_reduction = True\n\n reduction_params.lparams.gdimx = gdimx\n reduction_params.lparams.gdimy = gdimy\n\n # Reset CTA dimensions to avoid failing LaunchParams::assertValid\n reduction_params.lparams.bdimx = -1\n reduction_params.lparams.bdimy = -1\n reduction_params.lparams.bdimz = -1\n\n reduction_params.lparams.bdimx = scheduler_config.bdimx\n reduction_params.lparams.bdimy = scheduler_config.bdimy\n\n # For reduction scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n threads_per_cta_options = [128, 256, 512, 1024]\n vectorization_factor_options = [1, 2, 4, 8]\n reduction_unroll_factor_options = list(range(1, 6))\n iteration_unroll_factor_options = list(range(1, 6))\n warp_size = 32\n\n num_iterations, num_reductions = input_shape\n\n for (\n threads_per_cta,\n vectorize_factor,\n reduction_unroll_factor,\n iteration_unroll_factor,\n ) in itertools.product(\n threads_per_cta_options,\n vectorization_factor_options,\n reduction_unroll_factor_options,\n iteration_unroll_factor_options,\n ):\n scheduler_config = self.InnerReductionConfiguration(\n vectorize_factor=vectorize_factor,\n reduction_unroll_factor=reduction_unroll_factor,\n iteration_unroll_factor=iteration_unroll_factor,\n )\n scheduler_config.bdimx = min(\n threads_per_cta,\n max(\n warp_size,\n ceil_div(num_reductions, scheduler_config.vectorize_factor),\n ),\n )\n scheduler_config.bdimy = min(\n threads_per_cta,\n max(1, floor_div(threads_per_cta, scheduler_config.bdimx)),\n )\n scheduler_config.godim = ceil_div(\n num_iterations, scheduler_config.bdimy * iteration_unroll_factor\n )\n\n # number of reduction elements not handled by a CTA\n remaining_reduction = ceil_div(\n ceil_div(\n ceil_div(num_reductions, vectorize_factor), scheduler_config.bdimx\n ),\n reduction_unroll_factor,\n )\n\n if iteration_unroll_factor == 1 and remaining_reduction > 1:\n # all remaining reduction goes to grdim\n scheduler_config.grdim = remaining_reduction\n yield scheduler_config\n\n # When iteration dim is small, there may be unused SMs. We need\n # to shift work from block reduction to grid reduction to\n # increase SM usage.\n godim = scheduler_config.godim\n grdim = 1\n while (\n godim * grdim * 2 <= self.gpu_properties.multi_processor_count\n and (remaining_reduction / grdim) >= 2\n ):\n grdim *= 2\n scheduler_config.grdim = grdim\n yield scheduler_config\n\n # grid stride across reduction iterDomain is 1\n scheduler_config.grdim = 1\n yield scheduler_config\n\n def create_inputs(self, shape, tensor_datatype):\n def inner_fn(num_inputs):\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\")\n for _ in range(num_inputs)\n ]\n\n if self.selected_fusion == self.FUSION.ADD_SUM:\n return inner_fn(num_inputs=4)\n elif self.selected_fusion in [\n self.FUSION.INNER_SUM,\n self.FUSION.TANH_SUM,\n self.FUSION.EXP_SUM,\n ]:\n return inner_fn(num_inputs=1)\n else:\n assert False\n\n # A decorator to create a reduction fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def sum_fusion(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.sum(T1, dims=[1], keepdim=False, dtype=DataType.Null)\n T3 = fd.ops.cast(T2, dtype=DataType.BFloat16)\n fd.add_output(T3)\n\n def add_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T4 = fd.ops.cast(T0, dtype=DataType.Float)\n T5 = fd.ops.cast(T1, dtype=DataType.Float)\n T6 = fd.ops.add(T4, T5)\n T7 = fd.ops.cast(T2, dtype=DataType.Float)\n T8 = fd.ops.add(T6, T7)\n T9 = fd.ops.cast(T3, dtype=DataType.Float)\n T10 = fd.ops.add(T8, T9)\n T11 = fd.ops.sum(T10, dims=[1], keepdim=False, dtype=DataType.Null)\n T12 = fd.ops.cast(T11, dtype=DataType.BFloat16)\n fd.add_output(T12)\n\n def tanh_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.tanh(T1)\n T3 = fd.ops.sum(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.cast(T3, dtype=DataType.BFloat16)\n fd.add_output(T4)\n\n def exp_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.exp(T1)\n T3 = fd.ops.sum(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.cast(T3, dtype=DataType.BFloat16)\n fd.add_output(T4)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def sum_fusion(inputs):\n return torch.sum(inputs[0], dim=-1)\n\n def add_sum(inputs):\n return torch.sum(inputs[0] + inputs[1] + inputs[2] + inputs[3], dim=-1)\n\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum(inputs)\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with reduction scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.reduction)\n assert status\n\n reduction_params = fd.sched.compute_reduction_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n self.convert_to_inner_reduction_params(\n scheduler_config, reduction_params\n )\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotuneInnerReduction(\n selected_fusion=AutotuneInnerReduction.FUSION.INNER_SUM\n )\n\n # ============================ Run Experiments ============================","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.main","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.main#L400-L436","kind":"function","name":"main","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":400,"end_line":436,"context_start_line":380,"context_end_line":440,"code":" # Check if compatible with reduction scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.reduction)\n assert status\n\n reduction_params = fd.sched.compute_reduction_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n self.convert_to_inner_reduction_params(\n scheduler_config, reduction_params\n )\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotuneInnerReduction(\n selected_fusion=AutotuneInnerReduction.FUSION.INNER_SUM\n )\n\n # ============================ Run Experiments ============================\n\n parameters, performance = collect_data(script_config, autotune_config)\n\n # ============================ Separate Data ==============================\n\n train_data, test_data = separate_data(script_config, parameters, performance)\n\n # ========================= Train Regression Models =======================\n\n # Apply machine learning regressor\n # Given input shapes and scheduler parameters, predict performance metric.\n from sklearn import ensemble\n\n train_inputs, train_perf = train_data\n clf = ensemble.RandomForestRegressor()\n clf = clf.fit(train_inputs, train_perf)\n\n # ========================= Test Regression Models ========================\n test_model_rmse(clf, script_config, autotune_config, test_data)\n test_model(clf, script_config, autotune_config)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.FUSION","uri":"program://Fuser/class/doc.dev.python_scheduling.autotune_inner_reduction.FUSION#L67-L71","kind":"class","name":"FUSION","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":67,"end_line":71,"context_start_line":47,"context_end_line":91,"code":"#\n# 3. Train a regression model to predict the desired performance metric given\n# some input arguments and a scheduler configuration.\n#\n# 4. Measure the performance of the regression model.\n# - Calculate RMSE of predicted and actual performance on test set.\n# - Find the configuration with the best performance using regression model.\n# Then, compare against the heuristic configuration selected by nvfuser.\n# - For a specific batch size, gather performance across a range of hidden\n# sizes. Calculate performance for best predicted and nvfuser\n# configurations. Plot a chart comparing performance using matplotlib.\n#\n# The selected performance metric is effective_bandwidth_gbs. The empirical\n# scheduler selects the configuration that has the highest predicted\n# effective_bandwidth_gbs.\n\n# =============================================================================\n\n\nclass AutotuneInnerReduction:\n class FUSION(Enum):\n INNER_SUM = 1\n ADD_SUM = 2\n TANH_SUM = 3\n EXP_SUM = 4\n\n @dataclass(unsafe_hash=True)\n class InnerReductionConfiguration:\n # The vectorization factor for inner reduction domain.\n vectorize_factor: int = 1\n # The unroll factor for the inner reduction domain.\n reduction_unroll_factor: int = 1\n # The unroll factor for the outer iteration domain.\n iteration_unroll_factor: int = 1\n # The grid size for the outer iteration domain.\n # If grdim > 1, then godim corresponds with y axis of the grid.\n # Otherwise, it is the x axis of the grid.\n godim: int = -1\n # The grid size for the inner reduction domain. It corresponds\n # with x axis of the grid when it is >1.\n grdim: int = -1\n # The x axis of CTA. It corresponds with inner reduction domain.\n bdimx: int = -1\n # The y axis of CTA. It corresponds with outer reduction domain.\n # If it is non-zero, then there are multiple reduction per CTA.","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.InnerReductionConfiguration","uri":"program://Fuser/class/doc.dev.python_scheduling.autotune_inner_reduction.InnerReductionConfiguration#L74-L92","kind":"class","name":"InnerReductionConfiguration","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":74,"end_line":92,"context_start_line":54,"context_end_line":112,"code":"# Then, compare against the heuristic configuration selected by nvfuser.\n# - For a specific batch size, gather performance across a range of hidden\n# sizes. Calculate performance for best predicted and nvfuser\n# configurations. Plot a chart comparing performance using matplotlib.\n#\n# The selected performance metric is effective_bandwidth_gbs. The empirical\n# scheduler selects the configuration that has the highest predicted\n# effective_bandwidth_gbs.\n\n# =============================================================================\n\n\nclass AutotuneInnerReduction:\n class FUSION(Enum):\n INNER_SUM = 1\n ADD_SUM = 2\n TANH_SUM = 3\n EXP_SUM = 4\n\n @dataclass(unsafe_hash=True)\n class InnerReductionConfiguration:\n # The vectorization factor for inner reduction domain.\n vectorize_factor: int = 1\n # The unroll factor for the inner reduction domain.\n reduction_unroll_factor: int = 1\n # The unroll factor for the outer iteration domain.\n iteration_unroll_factor: int = 1\n # The grid size for the outer iteration domain.\n # If grdim > 1, then godim corresponds with y axis of the grid.\n # Otherwise, it is the x axis of the grid.\n godim: int = -1\n # The grid size for the inner reduction domain. It corresponds\n # with x axis of the grid when it is >1.\n grdim: int = -1\n # The x axis of CTA. It corresponds with inner reduction domain.\n bdimx: int = -1\n # The y axis of CTA. It corresponds with outer reduction domain.\n # If it is non-zero, then there are multiple reduction per CTA.\n bdimy: int = -1\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n # gpu device properties are defined globally\n assert torch.cuda.is_available()\n self.gpu_properties = torch.cuda.get_device_properties(device=0)\n\n def __repr__(self):\n return f\"inner_reduction_{self.selected_fusion.name}\"\n\n def convert_to_inner_reduction_params(self, scheduler_config, reduction_params):\n warp_size = 32\n max_number_of_threads_cta = 1024\n grid_x_limit = 2147483647\n grid_y_limit = 65535\n\n reduction_params.schedule_3d = False\n reduction_params.fastest_dim = True\n reduction_params.cross_block_inner_reduction = True","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.__init__","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.__init__#L94-L99","kind":"function","name":"__init__","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":94,"end_line":99,"context_start_line":74,"context_end_line":119,"code":" class InnerReductionConfiguration:\n # The vectorization factor for inner reduction domain.\n vectorize_factor: int = 1\n # The unroll factor for the inner reduction domain.\n reduction_unroll_factor: int = 1\n # The unroll factor for the outer iteration domain.\n iteration_unroll_factor: int = 1\n # The grid size for the outer iteration domain.\n # If grdim > 1, then godim corresponds with y axis of the grid.\n # Otherwise, it is the x axis of the grid.\n godim: int = -1\n # The grid size for the inner reduction domain. It corresponds\n # with x axis of the grid when it is >1.\n grdim: int = -1\n # The x axis of CTA. It corresponds with inner reduction domain.\n bdimx: int = -1\n # The y axis of CTA. It corresponds with outer reduction domain.\n # If it is non-zero, then there are multiple reduction per CTA.\n bdimy: int = -1\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n # gpu device properties are defined globally\n assert torch.cuda.is_available()\n self.gpu_properties = torch.cuda.get_device_properties(device=0)\n\n def __repr__(self):\n return f\"inner_reduction_{self.selected_fusion.name}\"\n\n def convert_to_inner_reduction_params(self, scheduler_config, reduction_params):\n warp_size = 32\n max_number_of_threads_cta = 1024\n grid_x_limit = 2147483647\n grid_y_limit = 65535\n\n reduction_params.schedule_3d = False\n reduction_params.fastest_dim = True\n reduction_params.cross_block_inner_reduction = True\n reduction_params.block_dim_inner_reduction = ParallelType.block_x\n reduction_params.cross_grid_inner_reduction = scheduler_config.grdim > 1\n reduction_params.multiple_reds_per_blk = scheduler_config.bdimy > 1\n reduction_params.pad_inner_reduction_to_warp = (\n scheduler_config.bdimx > warp_size\n ) and (\n (scheduler_config.bdimx * scheduler_config.bdimy)","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.__repr__","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.__repr__#L101-L102","kind":"function","name":"__repr__","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":101,"end_line":102,"context_start_line":81,"context_end_line":122,"code":" # The grid size for the outer iteration domain.\n # If grdim > 1, then godim corresponds with y axis of the grid.\n # Otherwise, it is the x axis of the grid.\n godim: int = -1\n # The grid size for the inner reduction domain. It corresponds\n # with x axis of the grid when it is >1.\n grdim: int = -1\n # The x axis of CTA. It corresponds with inner reduction domain.\n bdimx: int = -1\n # The y axis of CTA. It corresponds with outer reduction domain.\n # If it is non-zero, then there are multiple reduction per CTA.\n bdimy: int = -1\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n # gpu device properties are defined globally\n assert torch.cuda.is_available()\n self.gpu_properties = torch.cuda.get_device_properties(device=0)\n\n def __repr__(self):\n return f\"inner_reduction_{self.selected_fusion.name}\"\n\n def convert_to_inner_reduction_params(self, scheduler_config, reduction_params):\n warp_size = 32\n max_number_of_threads_cta = 1024\n grid_x_limit = 2147483647\n grid_y_limit = 65535\n\n reduction_params.schedule_3d = False\n reduction_params.fastest_dim = True\n reduction_params.cross_block_inner_reduction = True\n reduction_params.block_dim_inner_reduction = ParallelType.block_x\n reduction_params.cross_grid_inner_reduction = scheduler_config.grdim > 1\n reduction_params.multiple_reds_per_blk = scheduler_config.bdimy > 1\n reduction_params.pad_inner_reduction_to_warp = (\n scheduler_config.bdimx > warp_size\n ) and (\n (scheduler_config.bdimx * scheduler_config.bdimy)\n < max_number_of_threads_cta\n )\n reduction_params.unroll_factor_inner_reduction = (","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.convert_to_inner_reduction_params","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.convert_to_inner_reduction_params#L104-L166","kind":"function","name":"convert_to_inner_reduction_params","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":104,"end_line":166,"context_start_line":84,"context_end_line":186,"code":" godim: int = -1\n # The grid size for the inner reduction domain. It corresponds\n # with x axis of the grid when it is >1.\n grdim: int = -1\n # The x axis of CTA. It corresponds with inner reduction domain.\n bdimx: int = -1\n # The y axis of CTA. It corresponds with outer reduction domain.\n # If it is non-zero, then there are multiple reduction per CTA.\n bdimy: int = -1\n\n def __init__(self, selected_fusion):\n self.selected_fusion = selected_fusion\n\n # gpu device properties are defined globally\n assert torch.cuda.is_available()\n self.gpu_properties = torch.cuda.get_device_properties(device=0)\n\n def __repr__(self):\n return f\"inner_reduction_{self.selected_fusion.name}\"\n\n def convert_to_inner_reduction_params(self, scheduler_config, reduction_params):\n warp_size = 32\n max_number_of_threads_cta = 1024\n grid_x_limit = 2147483647\n grid_y_limit = 65535\n\n reduction_params.schedule_3d = False\n reduction_params.fastest_dim = True\n reduction_params.cross_block_inner_reduction = True\n reduction_params.block_dim_inner_reduction = ParallelType.block_x\n reduction_params.cross_grid_inner_reduction = scheduler_config.grdim > 1\n reduction_params.multiple_reds_per_blk = scheduler_config.bdimy > 1\n reduction_params.pad_inner_reduction_to_warp = (\n scheduler_config.bdimx > warp_size\n ) and (\n (scheduler_config.bdimx * scheduler_config.bdimy)\n < max_number_of_threads_cta\n )\n reduction_params.unroll_factor_inner_reduction = (\n scheduler_config.vectorize_factor\n )\n reduction_params.vectorize_inner_reduction = (\n scheduler_config.vectorize_factor > 1\n )\n reduction_params.unroll_factor_top_of_vectorization = (\n scheduler_config.reduction_unroll_factor\n )\n\n if scheduler_config.bdimy > 1:\n reduction_params.block_dim_iter_dom = ParallelType.block_y\n\n reduction_params.unroll_factor_iter_dom = (\n scheduler_config.iteration_unroll_factor\n )\n\n gdimx = -1\n gdimy = -1\n\n if scheduler_config.grdim > 1:\n reduction_params.grid_dim_inner_reduction = ParallelType.grid_x\n reduction_params.grid_dim_iter_dom = ParallelType.grid_y\n\n reduction_params.split_grid_dim_iter_dom_inner = True\n gdimx = min(scheduler_config.grdim, grid_x_limit)\n gdimy = min(scheduler_config.godim, grid_y_limit)\n if scheduler_config.godim > grid_y_limit:\n reduction_params.split_grid_dim_iter_dom_outer = True\n else:\n reduction_params.grid_dim_iter_dom = ParallelType.grid_x\n gdimx = min(scheduler_config.godim, grid_x_limit)\n if scheduler_config.godim > grid_x_limit:\n reduction_params.split_grid_dim_inner_reduction = True\n\n reduction_params.lparams.gdimx = gdimx\n reduction_params.lparams.gdimy = gdimy\n\n # Reset CTA dimensions to avoid failing LaunchParams::assertValid\n reduction_params.lparams.bdimx = -1\n reduction_params.lparams.bdimy = -1\n reduction_params.lparams.bdimz = -1\n\n reduction_params.lparams.bdimx = scheduler_config.bdimx\n reduction_params.lparams.bdimy = scheduler_config.bdimy\n\n # For reduction scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n threads_per_cta_options = [128, 256, 512, 1024]\n vectorization_factor_options = [1, 2, 4, 8]\n reduction_unroll_factor_options = list(range(1, 6))\n iteration_unroll_factor_options = list(range(1, 6))\n warp_size = 32\n\n num_iterations, num_reductions = input_shape\n\n for (\n threads_per_cta,\n vectorize_factor,\n reduction_unroll_factor,\n iteration_unroll_factor,\n ) in itertools.product(\n threads_per_cta_options,\n vectorization_factor_options,","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.generate_scheduler_configurations","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.generate_scheduler_configurations#L170-L238","kind":"function","name":"generate_scheduler_configurations","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":170,"end_line":238,"context_start_line":150,"context_end_line":258,"code":" reduction_params.split_grid_dim_iter_dom_outer = True\n else:\n reduction_params.grid_dim_iter_dom = ParallelType.grid_x\n gdimx = min(scheduler_config.godim, grid_x_limit)\n if scheduler_config.godim > grid_x_limit:\n reduction_params.split_grid_dim_inner_reduction = True\n\n reduction_params.lparams.gdimx = gdimx\n reduction_params.lparams.gdimy = gdimy\n\n # Reset CTA dimensions to avoid failing LaunchParams::assertValid\n reduction_params.lparams.bdimx = -1\n reduction_params.lparams.bdimy = -1\n reduction_params.lparams.bdimz = -1\n\n reduction_params.lparams.bdimx = scheduler_config.bdimx\n reduction_params.lparams.bdimy = scheduler_config.bdimy\n\n # For reduction scheduler, we test the cartesian product of vectorization and\n # unroll factors.\n def generate_scheduler_configurations(self, input_shape):\n threads_per_cta_options = [128, 256, 512, 1024]\n vectorization_factor_options = [1, 2, 4, 8]\n reduction_unroll_factor_options = list(range(1, 6))\n iteration_unroll_factor_options = list(range(1, 6))\n warp_size = 32\n\n num_iterations, num_reductions = input_shape\n\n for (\n threads_per_cta,\n vectorize_factor,\n reduction_unroll_factor,\n iteration_unroll_factor,\n ) in itertools.product(\n threads_per_cta_options,\n vectorization_factor_options,\n reduction_unroll_factor_options,\n iteration_unroll_factor_options,\n ):\n scheduler_config = self.InnerReductionConfiguration(\n vectorize_factor=vectorize_factor,\n reduction_unroll_factor=reduction_unroll_factor,\n iteration_unroll_factor=iteration_unroll_factor,\n )\n scheduler_config.bdimx = min(\n threads_per_cta,\n max(\n warp_size,\n ceil_div(num_reductions, scheduler_config.vectorize_factor),\n ),\n )\n scheduler_config.bdimy = min(\n threads_per_cta,\n max(1, floor_div(threads_per_cta, scheduler_config.bdimx)),\n )\n scheduler_config.godim = ceil_div(\n num_iterations, scheduler_config.bdimy * iteration_unroll_factor\n )\n\n # number of reduction elements not handled by a CTA\n remaining_reduction = ceil_div(\n ceil_div(\n ceil_div(num_reductions, vectorize_factor), scheduler_config.bdimx\n ),\n reduction_unroll_factor,\n )\n\n if iteration_unroll_factor == 1 and remaining_reduction > 1:\n # all remaining reduction goes to grdim\n scheduler_config.grdim = remaining_reduction\n yield scheduler_config\n\n # When iteration dim is small, there may be unused SMs. We need\n # to shift work from block reduction to grid reduction to\n # increase SM usage.\n godim = scheduler_config.godim\n grdim = 1\n while (\n godim * grdim * 2 <= self.gpu_properties.multi_processor_count\n and (remaining_reduction / grdim) >= 2\n ):\n grdim *= 2\n scheduler_config.grdim = grdim\n yield scheduler_config\n\n # grid stride across reduction iterDomain is 1\n scheduler_config.grdim = 1\n yield scheduler_config\n\n def create_inputs(self, shape, tensor_datatype):\n def inner_fn(num_inputs):\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\")\n for _ in range(num_inputs)\n ]\n\n if self.selected_fusion == self.FUSION.ADD_SUM:\n return inner_fn(num_inputs=4)\n elif self.selected_fusion in [\n self.FUSION.INNER_SUM,\n self.FUSION.TANH_SUM,\n self.FUSION.EXP_SUM,\n ]:\n return inner_fn(num_inputs=1)\n else:\n assert False\n\n # A decorator to create a reduction fusion given some input arguments.","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.create_inputs","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.create_inputs#L240-L256","kind":"function","name":"create_inputs","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":240,"end_line":256,"context_start_line":220,"context_end_line":276,"code":" scheduler_config.grdim = remaining_reduction\n yield scheduler_config\n\n # When iteration dim is small, there may be unused SMs. We need\n # to shift work from block reduction to grid reduction to\n # increase SM usage.\n godim = scheduler_config.godim\n grdim = 1\n while (\n godim * grdim * 2 <= self.gpu_properties.multi_processor_count\n and (remaining_reduction / grdim) >= 2\n ):\n grdim *= 2\n scheduler_config.grdim = grdim\n yield scheduler_config\n\n # grid stride across reduction iterDomain is 1\n scheduler_config.grdim = 1\n yield scheduler_config\n\n def create_inputs(self, shape, tensor_datatype):\n def inner_fn(num_inputs):\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\")\n for _ in range(num_inputs)\n ]\n\n if self.selected_fusion == self.FUSION.ADD_SUM:\n return inner_fn(num_inputs=4)\n elif self.selected_fusion in [\n self.FUSION.INNER_SUM,\n self.FUSION.TANH_SUM,\n self.FUSION.EXP_SUM,\n ]:\n return inner_fn(num_inputs=1)\n else:\n assert False\n\n # A decorator to create a reduction fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def sum_fusion(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.sum(T1, dims=[1], keepdim=False, dtype=DataType.Null)\n T3 = fd.ops.cast(T2, dtype=DataType.BFloat16)\n fd.add_output(T3)\n\n def add_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.create_fusion_func","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.create_fusion_func#L259-L350","kind":"function","name":"create_fusion_func","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":259,"end_line":350,"context_start_line":239,"context_end_line":370,"code":"\n def create_inputs(self, shape, tensor_datatype):\n def inner_fn(num_inputs):\n return [\n torch.randn(*shape, dtype=tensor_datatype, device=\"cuda\")\n for _ in range(num_inputs)\n ]\n\n if self.selected_fusion == self.FUSION.ADD_SUM:\n return inner_fn(num_inputs=4)\n elif self.selected_fusion in [\n self.FUSION.INNER_SUM,\n self.FUSION.TANH_SUM,\n self.FUSION.EXP_SUM,\n ]:\n return inner_fn(num_inputs=1)\n else:\n assert False\n\n # A decorator to create a reduction fusion given some input arguments.\n def create_fusion_func(self, inputs):\n def sum_fusion(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.sum(T1, dims=[1], keepdim=False, dtype=DataType.Null)\n T3 = fd.ops.cast(T2, dtype=DataType.BFloat16)\n fd.add_output(T3)\n\n def add_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T4 = fd.ops.cast(T0, dtype=DataType.Float)\n T5 = fd.ops.cast(T1, dtype=DataType.Float)\n T6 = fd.ops.add(T4, T5)\n T7 = fd.ops.cast(T2, dtype=DataType.Float)\n T8 = fd.ops.add(T6, T7)\n T9 = fd.ops.cast(T3, dtype=DataType.Float)\n T10 = fd.ops.add(T8, T9)\n T11 = fd.ops.sum(T10, dims=[1], keepdim=False, dtype=DataType.Null)\n T12 = fd.ops.cast(T11, dtype=DataType.BFloat16)\n fd.add_output(T12)\n\n def tanh_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.tanh(T1)\n T3 = fd.ops.sum(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.cast(T3, dtype=DataType.BFloat16)\n fd.add_output(T4)\n\n def exp_sum(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.exp(T1)\n T3 = fd.ops.sum(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.cast(T3, dtype=DataType.BFloat16)\n fd.add_output(T4)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def sum_fusion(inputs):\n return torch.sum(inputs[0], dim=-1)\n\n def add_sum(inputs):\n return torch.sum(inputs[0] + inputs[1] + inputs[2] + inputs[3], dim=-1)\n\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.eager_reference","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.eager_reference#L353-L375","kind":"function","name":"eager_reference","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":353,"end_line":375,"context_start_line":333,"context_end_line":395,"code":" stride_order=[1, 0],\n )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.exp(T1)\n T3 = fd.ops.sum(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.cast(T3, dtype=DataType.BFloat16)\n fd.add_output(T4)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def sum_fusion(inputs):\n return torch.sum(inputs[0], dim=-1)\n\n def add_sum(inputs):\n return torch.sum(inputs[0] + inputs[1] + inputs[2] + inputs[3], dim=-1)\n\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum(inputs)\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with reduction scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.reduction)\n assert status\n\n reduction_params = fd.sched.compute_reduction_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n self.convert_to_inner_reduction_params(\n scheduler_config, reduction_params\n )\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.custom_scheduler","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.custom_scheduler#L378-L396","kind":"function","name":"custom_scheduler","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":378,"end_line":396,"context_start_line":358,"context_end_line":416,"code":" return torch.sum(inputs[0] + inputs[1] + inputs[2] + inputs[3], dim=-1)\n\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum(inputs)\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with reduction scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.reduction)\n assert status\n\n reduction_params = fd.sched.compute_reduction_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n self.convert_to_inner_reduction_params(\n scheduler_config, reduction_params\n )\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotuneInnerReduction(\n selected_fusion=AutotuneInnerReduction.FUSION.INNER_SUM\n )\n\n # ============================ Run Experiments ============================","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.inner_fn","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.inner_fn#L379-L393","kind":"function","name":"inner_fn","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":379,"end_line":393,"context_start_line":359,"context_end_line":413,"code":"\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum(inputs)\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with reduction scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.reduction)\n assert status\n\n reduction_params = fd.sched.compute_reduction_heuristics()\n\n # Modify original parameters\n if scheduler_config is not None:\n self.convert_to_inner_reduction_params(\n scheduler_config, reduction_params\n )\n\n # Schedule fusion\n fd.sched.schedule()\n\n fd.schedule = inner_fn\n return fd\n\n\n# Run sequence of steps to collect data, train and test model\ndef main():\n # ====================== Setup Script Configuration =======================\n script_config = ScriptConfiguration(\n num_dimensions=2,\n outer_shapes=[16384],\n inner_shapes=[128, 1024, 4096, 16384],\n tensor_datatype=torch.bfloat16,\n test_data_percentage=0.1,\n empirical_batch_size=16384,\n empirical_hidden_sizes=list(range(256, 32768, 256)),\n )\n\n autotune_config = AutotuneInnerReduction(\n selected_fusion=AutotuneInnerReduction.FUSION.INNER_SUM","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.sum_fusion","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.sum_fusion#L354-L355","kind":"function","name":"sum_fusion","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":354,"end_line":355,"context_start_line":334,"context_end_line":375,"code":" )\n T1 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.exp(T1)\n T3 = fd.ops.sum(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.cast(T3, dtype=DataType.BFloat16)\n fd.add_output(T4)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def sum_fusion(inputs):\n return torch.sum(inputs[0], dim=-1)\n\n def add_sum(inputs):\n return torch.sum(inputs[0] + inputs[1] + inputs[2] + inputs[3], dim=-1)\n\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum(inputs)\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum(inputs)\n else:\n assert False","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.add_sum","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.add_sum#L357-L358","kind":"function","name":"add_sum","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":357,"end_line":358,"context_start_line":337,"context_end_line":378,"code":" T3 = fd.ops.sum(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.cast(T3, dtype=DataType.BFloat16)\n fd.add_output(T4)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def sum_fusion(inputs):\n return torch.sum(inputs[0], dim=-1)\n\n def add_sum(inputs):\n return torch.sum(inputs[0] + inputs[1] + inputs[2] + inputs[3], dim=-1)\n\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum(inputs)\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.tanh_sum","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.tanh_sum#L360-L361","kind":"function","name":"tanh_sum","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":360,"end_line":361,"context_start_line":340,"context_end_line":381,"code":"\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def sum_fusion(inputs):\n return torch.sum(inputs[0], dim=-1)\n\n def add_sum(inputs):\n return torch.sum(inputs[0] + inputs[1] + inputs[2] + inputs[3], dim=-1)\n\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum(inputs)\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with reduction scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.reduction)","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.dev.python_scheduling.autotune_inner_reduction.exp_sum","uri":"program://Fuser/function/doc.dev.python_scheduling.autotune_inner_reduction.exp_sum#L363-L364","kind":"function","name":"exp_sum","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":363,"end_line":364,"context_start_line":343,"context_end_line":384,"code":" elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum\n else:\n assert False\n\n # The pytorch eager mode reference used to validating nvfuser kernel.\n def eager_reference(self, inputs):\n def sum_fusion(inputs):\n return torch.sum(inputs[0], dim=-1)\n\n def add_sum(inputs):\n return torch.sum(inputs[0] + inputs[1] + inputs[2] + inputs[3], dim=-1)\n\n def tanh_sum(inputs):\n return torch.sum(torch.tanh(inputs[0]), dim=-1)\n\n def exp_sum(inputs):\n return torch.sum(torch.exp(inputs[0]), dim=-1)\n\n if self.selected_fusion == self.FUSION.INNER_SUM:\n return sum_fusion(inputs)\n elif self.selected_fusion == self.FUSION.ADD_SUM:\n return add_sum(inputs)\n elif self.selected_fusion == self.FUSION.TANH_SUM:\n return tanh_sum(inputs)\n elif self.selected_fusion == self.FUSION.EXP_SUM:\n return exp_sum(inputs)\n else:\n assert False\n\n # Apply scheduler with custom parameters using decorator\n def custom_scheduler(self, fd, scheduler_config):\n def inner_fn():\n # Check if compatible with reduction scheduler\n status, _ = fd.sched.can_schedule(SchedulerType.reduction)\n assert status\n\n reduction_params = fd.sched.compute_reduction_heuristics()","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"py:doc.sphinx.source.conf","uri":"program://Fuser/module/doc.sphinx.source.conf#L1-L83","kind":"module","name":"doc.sphinx.source.conf","path":"doc/sphinx/source/conf.py","language":"python","start_line":1,"end_line":83,"context_start_line":1,"context_end_line":83,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport os\nimport sys\nimport datetime\nimport pathlib\n\nsys.path.insert(0, os.path.abspath(\"../..\"))\n\nproject = \"nvFuser\"\nauthor = \"NVIDIA CORPORATION & AFFILIATES\"\n\n# Copyright statement\nrelease_year = 2023\ncurrent_year = datetime.date.today().year\nif current_year == release_year:\n copyright_year = release_year\nelse:\n copyright_year = str(release_year) + \"-\" + str(current_year)\ncopyright = f\"{copyright_year}, NVIDIA CORPORATION & AFFILIATES. All rights reserved.\"\n\n# Version\nroot_path = pathlib.Path(__file__).resolve().parents[3]\nprint(root_path)\nwith open(root_path / \"python\" / \"version.txt\", \"r\") as f:\n _raw_version = f.readline().strip()\nversion = str(_raw_version)\nrelease = str(_raw_version)\n\nextensions = [\n \"myst_parser\",\n \"sphinx.ext.mathjax\",\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.viewcode\",\n \"sphinx.ext.intersphinx\",\n \"sphinx_toolbox.more_autodoc.overloads\",\n]\n\nmyst_enable_extensions = [\n \"dollarmath\",\n \"html_image\",\n]\n\npygments_style = \"sphinx\"\ntemplates_path = [\"_templates\"]\nexclude_patterns = []\n\nhtml_theme = \"sphinx_rtd_theme\"\nhtml_show_sphinx = False\nhtml_static_path = [\"_static\"]\nhtml_sidebars = {\"**\": [\"globaltoc.html\", \"searchbox.html\"]}\nhtml_css_files = [\n \"css/nvidia_font.css\",\n \"css/nvidia_footer.css\",\n]\nhtml_theme_options = {\n \"collapse_navigation\": False,\n \"logo_only\": False,\n \"version_selector\": False,\n \"language_selector\": False,\n}\n\nsource_suffix = {\n \".rst\": \"restructuredtext\",\n \".txt\": \"markdown\",\n \".md\": \"markdown\",\n}\n\n# Hide overload type signatures (from \"sphinx_toolbox.more_autodoc.overload\")\noverloads_location = [\"signature\"]\n\n# Display long function signatures with each param on a new line.\n# Helps make annotated signatures more readable.\nmaximum_signature_line_length = 120\n\nintersphinx_mapping = {\n \"python\": (\"https://docs.python.org/3\", None),\n \"torch\": (\"https://pytorch.org/docs/stable/\", None),\n}","source_hash":"9cfc483ba59e266a4b5b5d59f6e5ab56d7c95889af7e0155823a0a2ce66ee6c8","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.benchmark_thunder","uri":"program://Fuser/module/tools.benchmark_thunder#L1-L102","kind":"module","name":"tools.benchmark_thunder","path":"tools/benchmark_thunder.py","language":"python","start_line":1,"end_line":102,"context_start_line":1,"context_end_line":102,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n# \"python benchmark_thunder.py -h\" for help.\n\nimport argparse\nimport os\nimport subprocess\nfrom typing import Iterable\n\n\n# Switches to the given branch, syncs to head, and returns the short hash of\n# the head.\ndef switch_to(branch: str, sync: bool) -> str:\n subprocess.check_call(f\"git fetch origin {branch}\", shell=True)\n\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch}\", shell=True\n )\n\n if sync:\n subprocess.check_call(f\"git reset --hard origin/{branch}\", shell=True)\n\n return subprocess.check_output(\n \"git rev-parse --short HEAD\", shell=True, text=True\n ).strip()\n\n\n# Sanitize the branch name so it can be used in a filename.\ndef sanitize_branch_name(branch: str) -> str:\n return branch.replace(\"/\", \"_\")\n\n\nclass BenchmarkRunner:\n def __init__(self, storage: str, benchmark_filter: str, sync: bool):\n self._storage = storage\n self._benchmark_filter = benchmark_filter\n self._sync = sync\n\n def run_setting(self, setting: str) -> None:\n thunder_branch, nvfuser_branch = setting.split(\":\")\n print(\n f\"Running Thunder benchmarks for nvFuser branch '{nvfuser_branch}' and Thunder branch '{thunder_branch}'...\"\n )\n\n os.chdir(\"/opt/pytorch/nvfuser\")\n nvfuser_commit = switch_to(nvfuser_branch, self._sync)\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n subprocess.check_call(\"_bn\", shell=True)\n\n os.chdir(\"/opt/pytorch/lightning-thunder\")\n thunder_commit = switch_to(thunder_branch, self._sync)\n subprocess.check_call(\"pip install -r requirements/devel.txt\", shell=True)\n\n out_stem = f\"thunder_{sanitize_branch_name(thunder_branch)}_{thunder_commit}_nvfuser_{sanitize_branch_name(nvfuser_branch)}_{nvfuser_commit}\"\n # Benchmarks fail occasionally for various reasons, e.g. OOM. Use `run`\n # instead of `check_call` to continue with other settings and report only\n # benchmarks that succeeded.\n command = f\"pytest thunder/benchmarks/targets.py --color=no -k '{self._benchmark_filter}' --benchmark-save={out_stem}\"\n if self._storage:\n command += f\" --benchmark-storage={self._storage}\"\n subprocess.run(command, shell=True)\n\n def run_settings(self, settings: Iterable[str]) -> None:\n for setting in settings:\n self.run_setting(setting)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Runs Thunder benchmarks with multiple settings. \"\n \"It stores benchmark results to the specified storage path, which \"\n \"can be compared by running `pytest-benchmark --storage \"\n \"compare --group-by name`.\"\n )\n parser.add_argument(\n \"settings\",\n type=str,\n nargs=\"+\",\n help=\"a list of settings to benchmark. Each setting is in format of :\",\n )\n parser.add_argument(\n \"--storage\",\n type=str,\n default=\"\",\n help=\"the path to give to `pytest --benchmark-storage`. If not specified, `pytest` will use its default storage path. This flag is useful to save benchmark results out of a transient Docker container.\",\n )\n parser.add_argument(\n \"--filter\",\n type=str,\n default=\"thunder]\",\n help=\"a benchmark filter that will be passed to `pytest -k `. By default, the filter is 'thunder]'.\",\n )\n parser.add_argument(\n \"--sync\", action=\"store_true\", help=\"whether to `git reset origin`\"\n )\n args = parser.parse_args()\n\n runner = BenchmarkRunner(args.storage, args.filter, args.sync)\n runner.run_settings(args.settings)","source_hash":"9864e6294b690faa29a234eadd14ba50e9c24115d7060b207e18a44cabf60bd7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.benchmark_thunder.switch_to","uri":"program://Fuser/function/tools.benchmark_thunder.switch_to#L15-L28","kind":"function","name":"switch_to","path":"tools/benchmark_thunder.py","language":"python","start_line":15,"end_line":28,"context_start_line":1,"context_end_line":48,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n# \"python benchmark_thunder.py -h\" for help.\n\nimport argparse\nimport os\nimport subprocess\nfrom typing import Iterable\n\n\n# Switches to the given branch, syncs to head, and returns the short hash of\n# the head.\ndef switch_to(branch: str, sync: bool) -> str:\n subprocess.check_call(f\"git fetch origin {branch}\", shell=True)\n\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch}\", shell=True\n )\n\n if sync:\n subprocess.check_call(f\"git reset --hard origin/{branch}\", shell=True)\n\n return subprocess.check_output(\n \"git rev-parse --short HEAD\", shell=True, text=True\n ).strip()\n\n\n# Sanitize the branch name so it can be used in a filename.\ndef sanitize_branch_name(branch: str) -> str:\n return branch.replace(\"/\", \"_\")\n\n\nclass BenchmarkRunner:\n def __init__(self, storage: str, benchmark_filter: str, sync: bool):\n self._storage = storage\n self._benchmark_filter = benchmark_filter\n self._sync = sync\n\n def run_setting(self, setting: str) -> None:\n thunder_branch, nvfuser_branch = setting.split(\":\")\n print(\n f\"Running Thunder benchmarks for nvFuser branch '{nvfuser_branch}' and Thunder branch '{thunder_branch}'...\"\n )\n\n os.chdir(\"/opt/pytorch/nvfuser\")","source_hash":"9864e6294b690faa29a234eadd14ba50e9c24115d7060b207e18a44cabf60bd7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.benchmark_thunder.sanitize_branch_name","uri":"program://Fuser/function/tools.benchmark_thunder.sanitize_branch_name#L32-L33","kind":"function","name":"sanitize_branch_name","path":"tools/benchmark_thunder.py","language":"python","start_line":32,"end_line":33,"context_start_line":12,"context_end_line":53,"code":"\n# Switches to the given branch, syncs to head, and returns the short hash of\n# the head.\ndef switch_to(branch: str, sync: bool) -> str:\n subprocess.check_call(f\"git fetch origin {branch}\", shell=True)\n\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch}\", shell=True\n )\n\n if sync:\n subprocess.check_call(f\"git reset --hard origin/{branch}\", shell=True)\n\n return subprocess.check_output(\n \"git rev-parse --short HEAD\", shell=True, text=True\n ).strip()\n\n\n# Sanitize the branch name so it can be used in a filename.\ndef sanitize_branch_name(branch: str) -> str:\n return branch.replace(\"/\", \"_\")\n\n\nclass BenchmarkRunner:\n def __init__(self, storage: str, benchmark_filter: str, sync: bool):\n self._storage = storage\n self._benchmark_filter = benchmark_filter\n self._sync = sync\n\n def run_setting(self, setting: str) -> None:\n thunder_branch, nvfuser_branch = setting.split(\":\")\n print(\n f\"Running Thunder benchmarks for nvFuser branch '{nvfuser_branch}' and Thunder branch '{thunder_branch}'...\"\n )\n\n os.chdir(\"/opt/pytorch/nvfuser\")\n nvfuser_commit = switch_to(nvfuser_branch, self._sync)\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n subprocess.check_call(\"_bn\", shell=True)\n\n os.chdir(\"/opt/pytorch/lightning-thunder\")","source_hash":"9864e6294b690faa29a234eadd14ba50e9c24115d7060b207e18a44cabf60bd7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.benchmark_thunder.BenchmarkRunner","uri":"program://Fuser/class/tools.benchmark_thunder.BenchmarkRunner#L36-L68","kind":"class","name":"BenchmarkRunner","path":"tools/benchmark_thunder.py","language":"python","start_line":36,"end_line":68,"context_start_line":16,"context_end_line":88,"code":" subprocess.check_call(f\"git fetch origin {branch}\", shell=True)\n\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch}\", shell=True\n )\n\n if sync:\n subprocess.check_call(f\"git reset --hard origin/{branch}\", shell=True)\n\n return subprocess.check_output(\n \"git rev-parse --short HEAD\", shell=True, text=True\n ).strip()\n\n\n# Sanitize the branch name so it can be used in a filename.\ndef sanitize_branch_name(branch: str) -> str:\n return branch.replace(\"/\", \"_\")\n\n\nclass BenchmarkRunner:\n def __init__(self, storage: str, benchmark_filter: str, sync: bool):\n self._storage = storage\n self._benchmark_filter = benchmark_filter\n self._sync = sync\n\n def run_setting(self, setting: str) -> None:\n thunder_branch, nvfuser_branch = setting.split(\":\")\n print(\n f\"Running Thunder benchmarks for nvFuser branch '{nvfuser_branch}' and Thunder branch '{thunder_branch}'...\"\n )\n\n os.chdir(\"/opt/pytorch/nvfuser\")\n nvfuser_commit = switch_to(nvfuser_branch, self._sync)\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n subprocess.check_call(\"_bn\", shell=True)\n\n os.chdir(\"/opt/pytorch/lightning-thunder\")\n thunder_commit = switch_to(thunder_branch, self._sync)\n subprocess.check_call(\"pip install -r requirements/devel.txt\", shell=True)\n\n out_stem = f\"thunder_{sanitize_branch_name(thunder_branch)}_{thunder_commit}_nvfuser_{sanitize_branch_name(nvfuser_branch)}_{nvfuser_commit}\"\n # Benchmarks fail occasionally for various reasons, e.g. OOM. Use `run`\n # instead of `check_call` to continue with other settings and report only\n # benchmarks that succeeded.\n command = f\"pytest thunder/benchmarks/targets.py --color=no -k '{self._benchmark_filter}' --benchmark-save={out_stem}\"\n if self._storage:\n command += f\" --benchmark-storage={self._storage}\"\n subprocess.run(command, shell=True)\n\n def run_settings(self, settings: Iterable[str]) -> None:\n for setting in settings:\n self.run_setting(setting)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Runs Thunder benchmarks with multiple settings. \"\n \"It stores benchmark results to the specified storage path, which \"\n \"can be compared by running `pytest-benchmark --storage \"\n \"compare --group-by name`.\"\n )\n parser.add_argument(\n \"settings\",\n type=str,\n nargs=\"+\",\n help=\"a list of settings to benchmark. Each setting is in format of :\",\n )\n parser.add_argument(\n \"--storage\",\n type=str,\n default=\"\",\n help=\"the path to give to `pytest --benchmark-storage`. If not specified, `pytest` will use its default storage path. This flag is useful to save benchmark results out of a transient Docker container.\",","source_hash":"9864e6294b690faa29a234eadd14ba50e9c24115d7060b207e18a44cabf60bd7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.benchmark_thunder.__init__","uri":"program://Fuser/function/tools.benchmark_thunder.__init__#L37-L40","kind":"function","name":"__init__","path":"tools/benchmark_thunder.py","language":"python","start_line":37,"end_line":40,"context_start_line":17,"context_end_line":60,"code":"\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch}\", shell=True\n )\n\n if sync:\n subprocess.check_call(f\"git reset --hard origin/{branch}\", shell=True)\n\n return subprocess.check_output(\n \"git rev-parse --short HEAD\", shell=True, text=True\n ).strip()\n\n\n# Sanitize the branch name so it can be used in a filename.\ndef sanitize_branch_name(branch: str) -> str:\n return branch.replace(\"/\", \"_\")\n\n\nclass BenchmarkRunner:\n def __init__(self, storage: str, benchmark_filter: str, sync: bool):\n self._storage = storage\n self._benchmark_filter = benchmark_filter\n self._sync = sync\n\n def run_setting(self, setting: str) -> None:\n thunder_branch, nvfuser_branch = setting.split(\":\")\n print(\n f\"Running Thunder benchmarks for nvFuser branch '{nvfuser_branch}' and Thunder branch '{thunder_branch}'...\"\n )\n\n os.chdir(\"/opt/pytorch/nvfuser\")\n nvfuser_commit = switch_to(nvfuser_branch, self._sync)\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n subprocess.check_call(\"_bn\", shell=True)\n\n os.chdir(\"/opt/pytorch/lightning-thunder\")\n thunder_commit = switch_to(thunder_branch, self._sync)\n subprocess.check_call(\"pip install -r requirements/devel.txt\", shell=True)\n\n out_stem = f\"thunder_{sanitize_branch_name(thunder_branch)}_{thunder_commit}_nvfuser_{sanitize_branch_name(nvfuser_branch)}_{nvfuser_commit}\"\n # Benchmarks fail occasionally for various reasons, e.g. OOM. Use `run`\n # instead of `check_call` to continue with other settings and report only\n # benchmarks that succeeded.","source_hash":"9864e6294b690faa29a234eadd14ba50e9c24115d7060b207e18a44cabf60bd7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.benchmark_thunder.run_setting","uri":"program://Fuser/function/tools.benchmark_thunder.run_setting#L42-L64","kind":"function","name":"run_setting","path":"tools/benchmark_thunder.py","language":"python","start_line":42,"end_line":64,"context_start_line":22,"context_end_line":84,"code":"\n if sync:\n subprocess.check_call(f\"git reset --hard origin/{branch}\", shell=True)\n\n return subprocess.check_output(\n \"git rev-parse --short HEAD\", shell=True, text=True\n ).strip()\n\n\n# Sanitize the branch name so it can be used in a filename.\ndef sanitize_branch_name(branch: str) -> str:\n return branch.replace(\"/\", \"_\")\n\n\nclass BenchmarkRunner:\n def __init__(self, storage: str, benchmark_filter: str, sync: bool):\n self._storage = storage\n self._benchmark_filter = benchmark_filter\n self._sync = sync\n\n def run_setting(self, setting: str) -> None:\n thunder_branch, nvfuser_branch = setting.split(\":\")\n print(\n f\"Running Thunder benchmarks for nvFuser branch '{nvfuser_branch}' and Thunder branch '{thunder_branch}'...\"\n )\n\n os.chdir(\"/opt/pytorch/nvfuser\")\n nvfuser_commit = switch_to(nvfuser_branch, self._sync)\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n subprocess.check_call(\"_bn\", shell=True)\n\n os.chdir(\"/opt/pytorch/lightning-thunder\")\n thunder_commit = switch_to(thunder_branch, self._sync)\n subprocess.check_call(\"pip install -r requirements/devel.txt\", shell=True)\n\n out_stem = f\"thunder_{sanitize_branch_name(thunder_branch)}_{thunder_commit}_nvfuser_{sanitize_branch_name(nvfuser_branch)}_{nvfuser_commit}\"\n # Benchmarks fail occasionally for various reasons, e.g. OOM. Use `run`\n # instead of `check_call` to continue with other settings and report only\n # benchmarks that succeeded.\n command = f\"pytest thunder/benchmarks/targets.py --color=no -k '{self._benchmark_filter}' --benchmark-save={out_stem}\"\n if self._storage:\n command += f\" --benchmark-storage={self._storage}\"\n subprocess.run(command, shell=True)\n\n def run_settings(self, settings: Iterable[str]) -> None:\n for setting in settings:\n self.run_setting(setting)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Runs Thunder benchmarks with multiple settings. \"\n \"It stores benchmark results to the specified storage path, which \"\n \"can be compared by running `pytest-benchmark --storage \"\n \"compare --group-by name`.\"\n )\n parser.add_argument(\n \"settings\",\n type=str,\n nargs=\"+\",\n help=\"a list of settings to benchmark. Each setting is in format of :\",\n )\n parser.add_argument(","source_hash":"9864e6294b690faa29a234eadd14ba50e9c24115d7060b207e18a44cabf60bd7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.benchmark_thunder.run_settings","uri":"program://Fuser/function/tools.benchmark_thunder.run_settings#L66-L68","kind":"function","name":"run_settings","path":"tools/benchmark_thunder.py","language":"python","start_line":66,"end_line":68,"context_start_line":46,"context_end_line":88,"code":" )\n\n os.chdir(\"/opt/pytorch/nvfuser\")\n nvfuser_commit = switch_to(nvfuser_branch, self._sync)\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n subprocess.check_call(\"_bn\", shell=True)\n\n os.chdir(\"/opt/pytorch/lightning-thunder\")\n thunder_commit = switch_to(thunder_branch, self._sync)\n subprocess.check_call(\"pip install -r requirements/devel.txt\", shell=True)\n\n out_stem = f\"thunder_{sanitize_branch_name(thunder_branch)}_{thunder_commit}_nvfuser_{sanitize_branch_name(nvfuser_branch)}_{nvfuser_commit}\"\n # Benchmarks fail occasionally for various reasons, e.g. OOM. Use `run`\n # instead of `check_call` to continue with other settings and report only\n # benchmarks that succeeded.\n command = f\"pytest thunder/benchmarks/targets.py --color=no -k '{self._benchmark_filter}' --benchmark-save={out_stem}\"\n if self._storage:\n command += f\" --benchmark-storage={self._storage}\"\n subprocess.run(command, shell=True)\n\n def run_settings(self, settings: Iterable[str]) -> None:\n for setting in settings:\n self.run_setting(setting)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Runs Thunder benchmarks with multiple settings. \"\n \"It stores benchmark results to the specified storage path, which \"\n \"can be compared by running `pytest-benchmark --storage \"\n \"compare --group-by name`.\"\n )\n parser.add_argument(\n \"settings\",\n type=str,\n nargs=\"+\",\n help=\"a list of settings to benchmark. Each setting is in format of :\",\n )\n parser.add_argument(\n \"--storage\",\n type=str,\n default=\"\",\n help=\"the path to give to `pytest --benchmark-storage`. If not specified, `pytest` will use its default storage path. This flag is useful to save benchmark results out of a transient Docker container.\",","source_hash":"9864e6294b690faa29a234eadd14ba50e9c24115d7060b207e18a44cabf60bd7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark","uri":"program://Fuser/module/tools.compare_benchmark#L1-L220","kind":"module","name":"tools.compare_benchmark","path":"tools/compare_benchmark.py","language":"python","start_line":1,"end_line":220,"context_start_line":1,"context_end_line":220,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# \"compare_benchmark.py -h\" for help.\n\nimport argparse\nfrom dataclasses import dataclass\nimport json\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport subprocess\nfrom typing import Iterable\n\n\n# If `arg` uses a forbidden option, returns that forbidden option; otherwise,\n# returns an empty string.\ndef uses_forbidden_option(arg: str) -> str:\n for forbidden_option in (\n \"--benchmark_out\",\n \"--benchmark_out_format\",\n \"--benchmark_format\",\n ):\n # Depending on which shell, the name of a long option and the value can\n # be split by a space or an =.\n if arg == forbidden_option or arg.startswith(forbidden_option + \"=\"):\n return forbidden_option\n return \"\"\n\n\ndef sanitize_benchmark_args(args: list[str]) -> list[str]:\n # Skip the leading \"--\". It's sometimes written before the benchmark args\n # as a convention.\n if args and args[0] == \"--\":\n args = args[1:]\n\n for arg in args:\n if forbidden_option := uses_forbidden_option(arg):\n raise ValueError(\n f\"{forbidden_option} should be specified by run_benchmark not the user.\"\n )\n\n return args\n\n\ndef check_out(branch_or_commit: str) -> None:\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch_or_commit}\", shell=True\n )\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n\n\n# Runs nvfuser_bench with `benchmark_args` on the given branch or commit. Dumps\n# outputs to `out_dir`. Returns `out_dir`/`branch_or_commit`.json that captures\n# the benchmark result. If the output already exists, skips benchmarking and\n# uses that output. This is useful, for example, when comparing multiple\n# contenders to the same base.\ndef run_benchmark(\n branch_or_commit: str, benchmark_args: list[str], out_dir: str\n) -> str:\n benchmark_out = os.path.join(out_dir, branch_or_commit + \".json\")\n if os.path.exists(benchmark_out):\n print(f\"{benchmark_out} already exists. Skip benchmarking {branch_or_commit}.\")\n return benchmark_out\n\n check_out(branch_or_commit)\n\n subprocess.check_call(\"pip install -e .\", shell=True)\n\n benchmark_command = \" \".join(\n [\"bin/nvfuser_bench\"]\n + benchmark_args\n + [f\"--benchmark_out={benchmark_out}\", \"--benchmark_format=json\"]\n )\n stdout_path = os.path.join(out_dir, branch_or_commit + \".stdout\")\n stderr_path = os.path.join(out_dir, branch_or_commit + \".stderr\")\n print(\"Running benchmark command: \" + benchmark_command)\n print(f\"Stdout and stderr are redirected to {stdout_path} and {stderr_path}.\")\n with open(stdout_path, \"w\") as stdout, open(stderr_path, \"w\") as stderr:\n subprocess.check_call(\n benchmark_command, stdout=stdout, stderr=stderr, shell=True\n )\n print(f\"The benchmark output is stored in {benchmark_out}.\")\n\n return benchmark_out\n\n\n@dataclass\nclass Comparison:\n name: str\n baseline_time: float\n contender_time: float\n # contender_time divided by baseline_time. Smaller is better.\n change: float\n time_unit: str\n\n def __str__(self):\n return f\"Benchmark {self.name} changed from {self.baseline_time}{self.time_unit} to {self.contender_time}{self.time_unit} ({self.change:.2f}x)\"\n\n\n# Compares the two given benchmark results and produces a .json file containing\n# the comparison.\ndef compare(baseline_out: str, contender_out: str, out_dir: str) -> str:\n baseline, _ = os.path.splitext(os.path.basename(baseline_out))\n contender, _ = os.path.splitext(os.path.basename(contender_out))\n comparison_out = os.path.join(out_dir, f\"{baseline}_vs_{contender}.json\")\n subprocess.check_call(\n f\"third_party/benchmark/tools/compare.py -d {comparison_out} benchmarks {baseline_out} {contender_out}\",\n shell=True,\n )\n return comparison_out\n\n\ndef load_comparison(comparison_out: str) -> list[Comparison]:\n comparisons: list[Comparison] = []\n with open(comparison_out) as f:\n data = json.loads(f.read())\n\n for row in data:\n for measurement in row[\"measurements\"]:\n if row[\"run_type\"] != \"iteration\":\n continue\n comparisons.append(\n Comparison(\n name=row[\"name\"],\n baseline_time=measurement[\"real_time\"],\n contender_time=measurement[\"real_time_other\"],\n # measurement[\"time\"] means (contender-baseline)/baseline.\n # That plus 1 is the ratio that we want.\n change=measurement[\"time\"] + 1,\n time_unit=row[\"time_unit\"],\n )\n )\n\n return comparisons\n\n\ndef summarize_comparison(comparisons: Iterable[Comparison], out_dir: str) -> None:\n comparisons = sorted(comparisons, key=lambda x: x.change)\n\n # Print top improvements and regressions.\n num_tops = 5\n print(f\"Top {num_tops} improvements:\")\n for i in range(min(num_tops, len(comparisons))):\n comparison = comparisons[i]\n if comparison.change >= 1:\n break\n print(f\" {comparison}\")\n print()\n print(f\"Top {num_tops} regressions:\")\n for i in range(min(num_tops, len(comparisons))):\n comparison = comparisons[-(i + 1)]\n if comparison.change <= 1:\n break\n print(f\" {comparison}\")\n\n # Generate and save the histogram of time changes.\n plt.xlabel(\"Time change (contender/baseline)\")\n plt.ylabel(\"Number of benchmarks\")\n n, bins, patches = plt.hist([comparison.change for comparison in comparisons])\n bin_centers = np.diff(bins) / 2 + bins[:-1]\n for bar, count, x in zip(patches, n, bin_centers):\n plt.text(x, count + 0.5, str(count), ha=\"center\", va=\"bottom\")\n\n histogram_out = os.path.join(out_dir, \"histogram.png\")\n plt.savefig(histogram_out)\n print()\n print(f\"Saved the histogram of time changes to {histogram_out}.\")\n\n\ndef get_head_branch_or_commit() -> str:\n # Return the branch name if possible.\n head_branch_or_commit = subprocess.check_output(\n \"git rev-parse --abbrev-ref HEAD\", text=True, shell=True\n ).strip()\n\n if head_branch_or_commit != \"HEAD\":\n return head_branch_or_commit\n # Head is detached. Return the commit instead.\n return subprocess.check_output(\"git rev-parse HEAD\", text=True, shell=True).strip()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Runs nvfuser_bench on two commits and compares their results. See https://github.com/NVIDIA/Fuser/wiki/Developer-guide#benchmark-nvfuser for usage.\"\n )\n\n parser.add_argument(\"baseline\", type=str, help=\"The baseline branch or commit\")\n parser.add_argument(\"contender\", type=str, help=\"The contender branch or commit\")\n parser.add_argument(\n \"out_dir\",\n type=str,\n help=\"The output folder that will contain benchmark results and comparison\",\n )\n parser.add_argument(\n \"benchmark_args\",\n type=str,\n nargs=argparse.REMAINDER,\n help=\"Arguments passed to nvfuser_bench, e.g., --benchmark_filter=NvFuserScheduler\",\n )\n args = parser.parse_args()\n\n benchmark_args = sanitize_benchmark_args(args.benchmark_args)\n\n if not os.path.exists(args.out_dir):\n os.makedirs(args.out_dir)\n\n original_branch_or_commit = get_head_branch_or_commit()\n try:\n baseline_out = run_benchmark(args.baseline, benchmark_args, args.out_dir)\n contender_out = run_benchmark(args.contender, benchmark_args, args.out_dir)\n finally:\n # Check out the original branch even when benchmarking failed.\n check_out(original_branch_or_commit)\n\n comparison_out = compare(baseline_out, contender_out, args.out_dir)\n comparisons = load_comparison(comparison_out)\n summarize_comparison(comparisons, args.out_dir)","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.uses_forbidden_option","uri":"program://Fuser/function/tools.compare_benchmark.uses_forbidden_option#L19-L29","kind":"function","name":"uses_forbidden_option","path":"tools/compare_benchmark.py","language":"python","start_line":19,"end_line":29,"context_start_line":1,"context_end_line":49,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# \"compare_benchmark.py -h\" for help.\n\nimport argparse\nfrom dataclasses import dataclass\nimport json\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport subprocess\nfrom typing import Iterable\n\n\n# If `arg` uses a forbidden option, returns that forbidden option; otherwise,\n# returns an empty string.\ndef uses_forbidden_option(arg: str) -> str:\n for forbidden_option in (\n \"--benchmark_out\",\n \"--benchmark_out_format\",\n \"--benchmark_format\",\n ):\n # Depending on which shell, the name of a long option and the value can\n # be split by a space or an =.\n if arg == forbidden_option or arg.startswith(forbidden_option + \"=\"):\n return forbidden_option\n return \"\"\n\n\ndef sanitize_benchmark_args(args: list[str]) -> list[str]:\n # Skip the leading \"--\". It's sometimes written before the benchmark args\n # as a convention.\n if args and args[0] == \"--\":\n args = args[1:]\n\n for arg in args:\n if forbidden_option := uses_forbidden_option(arg):\n raise ValueError(\n f\"{forbidden_option} should be specified by run_benchmark not the user.\"\n )\n\n return args\n\n\ndef check_out(branch_or_commit: str) -> None:\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.sanitize_benchmark_args","uri":"program://Fuser/function/tools.compare_benchmark.sanitize_benchmark_args#L32-L44","kind":"function","name":"sanitize_benchmark_args","path":"tools/compare_benchmark.py","language":"python","start_line":32,"end_line":44,"context_start_line":12,"context_end_line":64,"code":"import os\nimport subprocess\nfrom typing import Iterable\n\n\n# If `arg` uses a forbidden option, returns that forbidden option; otherwise,\n# returns an empty string.\ndef uses_forbidden_option(arg: str) -> str:\n for forbidden_option in (\n \"--benchmark_out\",\n \"--benchmark_out_format\",\n \"--benchmark_format\",\n ):\n # Depending on which shell, the name of a long option and the value can\n # be split by a space or an =.\n if arg == forbidden_option or arg.startswith(forbidden_option + \"=\"):\n return forbidden_option\n return \"\"\n\n\ndef sanitize_benchmark_args(args: list[str]) -> list[str]:\n # Skip the leading \"--\". It's sometimes written before the benchmark args\n # as a convention.\n if args and args[0] == \"--\":\n args = args[1:]\n\n for arg in args:\n if forbidden_option := uses_forbidden_option(arg):\n raise ValueError(\n f\"{forbidden_option} should be specified by run_benchmark not the user.\"\n )\n\n return args\n\n\ndef check_out(branch_or_commit: str) -> None:\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch_or_commit}\", shell=True\n )\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n\n\n# Runs nvfuser_bench with `benchmark_args` on the given branch or commit. Dumps\n# outputs to `out_dir`. Returns `out_dir`/`branch_or_commit`.json that captures\n# the benchmark result. If the output already exists, skips benchmarking and\n# uses that output. This is useful, for example, when comparing multiple\n# contenders to the same base.\ndef run_benchmark(\n branch_or_commit: str, benchmark_args: list[str], out_dir: str\n) -> str:\n benchmark_out = os.path.join(out_dir, branch_or_commit + \".json\")\n if os.path.exists(benchmark_out):","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.check_out","uri":"program://Fuser/function/tools.compare_benchmark.check_out#L47-L52","kind":"function","name":"check_out","path":"tools/compare_benchmark.py","language":"python","start_line":47,"end_line":52,"context_start_line":27,"context_end_line":72,"code":" if arg == forbidden_option or arg.startswith(forbidden_option + \"=\"):\n return forbidden_option\n return \"\"\n\n\ndef sanitize_benchmark_args(args: list[str]) -> list[str]:\n # Skip the leading \"--\". It's sometimes written before the benchmark args\n # as a convention.\n if args and args[0] == \"--\":\n args = args[1:]\n\n for arg in args:\n if forbidden_option := uses_forbidden_option(arg):\n raise ValueError(\n f\"{forbidden_option} should be specified by run_benchmark not the user.\"\n )\n\n return args\n\n\ndef check_out(branch_or_commit: str) -> None:\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch_or_commit}\", shell=True\n )\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n\n\n# Runs nvfuser_bench with `benchmark_args` on the given branch or commit. Dumps\n# outputs to `out_dir`. Returns `out_dir`/`branch_or_commit`.json that captures\n# the benchmark result. If the output already exists, skips benchmarking and\n# uses that output. This is useful, for example, when comparing multiple\n# contenders to the same base.\ndef run_benchmark(\n branch_or_commit: str, benchmark_args: list[str], out_dir: str\n) -> str:\n benchmark_out = os.path.join(out_dir, branch_or_commit + \".json\")\n if os.path.exists(benchmark_out):\n print(f\"{benchmark_out} already exists. Skip benchmarking {branch_or_commit}.\")\n return benchmark_out\n\n check_out(branch_or_commit)\n\n subprocess.check_call(\"pip install -e .\", shell=True)\n\n benchmark_command = \" \".join(","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.run_benchmark","uri":"program://Fuser/function/tools.compare_benchmark.run_benchmark#L60-L87","kind":"function","name":"run_benchmark","path":"tools/compare_benchmark.py","language":"python","start_line":60,"end_line":87,"context_start_line":40,"context_end_line":107,"code":" raise ValueError(\n f\"{forbidden_option} should be specified by run_benchmark not the user.\"\n )\n\n return args\n\n\ndef check_out(branch_or_commit: str) -> None:\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch_or_commit}\", shell=True\n )\n subprocess.check_call(\"git submodule update --init --recursive\", shell=True)\n\n\n# Runs nvfuser_bench with `benchmark_args` on the given branch or commit. Dumps\n# outputs to `out_dir`. Returns `out_dir`/`branch_or_commit`.json that captures\n# the benchmark result. If the output already exists, skips benchmarking and\n# uses that output. This is useful, for example, when comparing multiple\n# contenders to the same base.\ndef run_benchmark(\n branch_or_commit: str, benchmark_args: list[str], out_dir: str\n) -> str:\n benchmark_out = os.path.join(out_dir, branch_or_commit + \".json\")\n if os.path.exists(benchmark_out):\n print(f\"{benchmark_out} already exists. Skip benchmarking {branch_or_commit}.\")\n return benchmark_out\n\n check_out(branch_or_commit)\n\n subprocess.check_call(\"pip install -e .\", shell=True)\n\n benchmark_command = \" \".join(\n [\"bin/nvfuser_bench\"]\n + benchmark_args\n + [f\"--benchmark_out={benchmark_out}\", \"--benchmark_format=json\"]\n )\n stdout_path = os.path.join(out_dir, branch_or_commit + \".stdout\")\n stderr_path = os.path.join(out_dir, branch_or_commit + \".stderr\")\n print(\"Running benchmark command: \" + benchmark_command)\n print(f\"Stdout and stderr are redirected to {stdout_path} and {stderr_path}.\")\n with open(stdout_path, \"w\") as stdout, open(stderr_path, \"w\") as stderr:\n subprocess.check_call(\n benchmark_command, stdout=stdout, stderr=stderr, shell=True\n )\n print(f\"The benchmark output is stored in {benchmark_out}.\")\n\n return benchmark_out\n\n\n@dataclass\nclass Comparison:\n name: str\n baseline_time: float\n contender_time: float\n # contender_time divided by baseline_time. Smaller is better.\n change: float\n time_unit: str\n\n def __str__(self):\n return f\"Benchmark {self.name} changed from {self.baseline_time}{self.time_unit} to {self.contender_time}{self.time_unit} ({self.change:.2f}x)\"\n\n\n# Compares the two given benchmark results and produces a .json file containing\n# the comparison.\ndef compare(baseline_out: str, contender_out: str, out_dir: str) -> str:\n baseline, _ = os.path.splitext(os.path.basename(baseline_out))\n contender, _ = os.path.splitext(os.path.basename(contender_out))","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.Comparison","uri":"program://Fuser/class/tools.compare_benchmark.Comparison#L91-L100","kind":"class","name":"Comparison","path":"tools/compare_benchmark.py","language":"python","start_line":91,"end_line":100,"context_start_line":71,"context_end_line":120,"code":"\n benchmark_command = \" \".join(\n [\"bin/nvfuser_bench\"]\n + benchmark_args\n + [f\"--benchmark_out={benchmark_out}\", \"--benchmark_format=json\"]\n )\n stdout_path = os.path.join(out_dir, branch_or_commit + \".stdout\")\n stderr_path = os.path.join(out_dir, branch_or_commit + \".stderr\")\n print(\"Running benchmark command: \" + benchmark_command)\n print(f\"Stdout and stderr are redirected to {stdout_path} and {stderr_path}.\")\n with open(stdout_path, \"w\") as stdout, open(stderr_path, \"w\") as stderr:\n subprocess.check_call(\n benchmark_command, stdout=stdout, stderr=stderr, shell=True\n )\n print(f\"The benchmark output is stored in {benchmark_out}.\")\n\n return benchmark_out\n\n\n@dataclass\nclass Comparison:\n name: str\n baseline_time: float\n contender_time: float\n # contender_time divided by baseline_time. Smaller is better.\n change: float\n time_unit: str\n\n def __str__(self):\n return f\"Benchmark {self.name} changed from {self.baseline_time}{self.time_unit} to {self.contender_time}{self.time_unit} ({self.change:.2f}x)\"\n\n\n# Compares the two given benchmark results and produces a .json file containing\n# the comparison.\ndef compare(baseline_out: str, contender_out: str, out_dir: str) -> str:\n baseline, _ = os.path.splitext(os.path.basename(baseline_out))\n contender, _ = os.path.splitext(os.path.basename(contender_out))\n comparison_out = os.path.join(out_dir, f\"{baseline}_vs_{contender}.json\")\n subprocess.check_call(\n f\"third_party/benchmark/tools/compare.py -d {comparison_out} benchmarks {baseline_out} {contender_out}\",\n shell=True,\n )\n return comparison_out\n\n\ndef load_comparison(comparison_out: str) -> list[Comparison]:\n comparisons: list[Comparison] = []\n with open(comparison_out) as f:\n data = json.loads(f.read())\n","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.compare","uri":"program://Fuser/function/tools.compare_benchmark.compare#L105-L113","kind":"function","name":"compare","path":"tools/compare_benchmark.py","language":"python","start_line":105,"end_line":113,"context_start_line":85,"context_end_line":133,"code":" print(f\"The benchmark output is stored in {benchmark_out}.\")\n\n return benchmark_out\n\n\n@dataclass\nclass Comparison:\n name: str\n baseline_time: float\n contender_time: float\n # contender_time divided by baseline_time. Smaller is better.\n change: float\n time_unit: str\n\n def __str__(self):\n return f\"Benchmark {self.name} changed from {self.baseline_time}{self.time_unit} to {self.contender_time}{self.time_unit} ({self.change:.2f}x)\"\n\n\n# Compares the two given benchmark results and produces a .json file containing\n# the comparison.\ndef compare(baseline_out: str, contender_out: str, out_dir: str) -> str:\n baseline, _ = os.path.splitext(os.path.basename(baseline_out))\n contender, _ = os.path.splitext(os.path.basename(contender_out))\n comparison_out = os.path.join(out_dir, f\"{baseline}_vs_{contender}.json\")\n subprocess.check_call(\n f\"third_party/benchmark/tools/compare.py -d {comparison_out} benchmarks {baseline_out} {contender_out}\",\n shell=True,\n )\n return comparison_out\n\n\ndef load_comparison(comparison_out: str) -> list[Comparison]:\n comparisons: list[Comparison] = []\n with open(comparison_out) as f:\n data = json.loads(f.read())\n\n for row in data:\n for measurement in row[\"measurements\"]:\n if row[\"run_type\"] != \"iteration\":\n continue\n comparisons.append(\n Comparison(\n name=row[\"name\"],\n baseline_time=measurement[\"real_time\"],\n contender_time=measurement[\"real_time_other\"],\n # measurement[\"time\"] means (contender-baseline)/baseline.\n # That plus 1 is the ratio that we want.\n change=measurement[\"time\"] + 1,\n time_unit=row[\"time_unit\"],","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.load_comparison","uri":"program://Fuser/function/tools.compare_benchmark.load_comparison#L116-L137","kind":"function","name":"load_comparison","path":"tools/compare_benchmark.py","language":"python","start_line":116,"end_line":137,"context_start_line":96,"context_end_line":157,"code":" change: float\n time_unit: str\n\n def __str__(self):\n return f\"Benchmark {self.name} changed from {self.baseline_time}{self.time_unit} to {self.contender_time}{self.time_unit} ({self.change:.2f}x)\"\n\n\n# Compares the two given benchmark results and produces a .json file containing\n# the comparison.\ndef compare(baseline_out: str, contender_out: str, out_dir: str) -> str:\n baseline, _ = os.path.splitext(os.path.basename(baseline_out))\n contender, _ = os.path.splitext(os.path.basename(contender_out))\n comparison_out = os.path.join(out_dir, f\"{baseline}_vs_{contender}.json\")\n subprocess.check_call(\n f\"third_party/benchmark/tools/compare.py -d {comparison_out} benchmarks {baseline_out} {contender_out}\",\n shell=True,\n )\n return comparison_out\n\n\ndef load_comparison(comparison_out: str) -> list[Comparison]:\n comparisons: list[Comparison] = []\n with open(comparison_out) as f:\n data = json.loads(f.read())\n\n for row in data:\n for measurement in row[\"measurements\"]:\n if row[\"run_type\"] != \"iteration\":\n continue\n comparisons.append(\n Comparison(\n name=row[\"name\"],\n baseline_time=measurement[\"real_time\"],\n contender_time=measurement[\"real_time_other\"],\n # measurement[\"time\"] means (contender-baseline)/baseline.\n # That plus 1 is the ratio that we want.\n change=measurement[\"time\"] + 1,\n time_unit=row[\"time_unit\"],\n )\n )\n\n return comparisons\n\n\ndef summarize_comparison(comparisons: Iterable[Comparison], out_dir: str) -> None:\n comparisons = sorted(comparisons, key=lambda x: x.change)\n\n # Print top improvements and regressions.\n num_tops = 5\n print(f\"Top {num_tops} improvements:\")\n for i in range(min(num_tops, len(comparisons))):\n comparison = comparisons[i]\n if comparison.change >= 1:\n break\n print(f\" {comparison}\")\n print()\n print(f\"Top {num_tops} regressions:\")\n for i in range(min(num_tops, len(comparisons))):\n comparison = comparisons[-(i + 1)]\n if comparison.change <= 1:\n break\n print(f\" {comparison}\")","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.summarize_comparison","uri":"program://Fuser/function/tools.compare_benchmark.summarize_comparison#L140-L170","kind":"function","name":"summarize_comparison","path":"tools/compare_benchmark.py","language":"python","start_line":140,"end_line":170,"context_start_line":120,"context_end_line":190,"code":"\n for row in data:\n for measurement in row[\"measurements\"]:\n if row[\"run_type\"] != \"iteration\":\n continue\n comparisons.append(\n Comparison(\n name=row[\"name\"],\n baseline_time=measurement[\"real_time\"],\n contender_time=measurement[\"real_time_other\"],\n # measurement[\"time\"] means (contender-baseline)/baseline.\n # That plus 1 is the ratio that we want.\n change=measurement[\"time\"] + 1,\n time_unit=row[\"time_unit\"],\n )\n )\n\n return comparisons\n\n\ndef summarize_comparison(comparisons: Iterable[Comparison], out_dir: str) -> None:\n comparisons = sorted(comparisons, key=lambda x: x.change)\n\n # Print top improvements and regressions.\n num_tops = 5\n print(f\"Top {num_tops} improvements:\")\n for i in range(min(num_tops, len(comparisons))):\n comparison = comparisons[i]\n if comparison.change >= 1:\n break\n print(f\" {comparison}\")\n print()\n print(f\"Top {num_tops} regressions:\")\n for i in range(min(num_tops, len(comparisons))):\n comparison = comparisons[-(i + 1)]\n if comparison.change <= 1:\n break\n print(f\" {comparison}\")\n\n # Generate and save the histogram of time changes.\n plt.xlabel(\"Time change (contender/baseline)\")\n plt.ylabel(\"Number of benchmarks\")\n n, bins, patches = plt.hist([comparison.change for comparison in comparisons])\n bin_centers = np.diff(bins) / 2 + bins[:-1]\n for bar, count, x in zip(patches, n, bin_centers):\n plt.text(x, count + 0.5, str(count), ha=\"center\", va=\"bottom\")\n\n histogram_out = os.path.join(out_dir, \"histogram.png\")\n plt.savefig(histogram_out)\n print()\n print(f\"Saved the histogram of time changes to {histogram_out}.\")\n\n\ndef get_head_branch_or_commit() -> str:\n # Return the branch name if possible.\n head_branch_or_commit = subprocess.check_output(\n \"git rev-parse --abbrev-ref HEAD\", text=True, shell=True\n ).strip()\n\n if head_branch_or_commit != \"HEAD\":\n return head_branch_or_commit\n # Head is detached. Return the commit instead.\n return subprocess.check_output(\"git rev-parse HEAD\", text=True, shell=True).strip()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Runs nvfuser_bench on two commits and compares their results. See https://github.com/NVIDIA/Fuser/wiki/Developer-guide#benchmark-nvfuser for usage.\"\n )\n\n parser.add_argument(\"baseline\", type=str, help=\"The baseline branch or commit\")","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.get_head_branch_or_commit","uri":"program://Fuser/function/tools.compare_benchmark.get_head_branch_or_commit#L173-L182","kind":"function","name":"get_head_branch_or_commit","path":"tools/compare_benchmark.py","language":"python","start_line":173,"end_line":182,"context_start_line":153,"context_end_line":202,"code":" for i in range(min(num_tops, len(comparisons))):\n comparison = comparisons[-(i + 1)]\n if comparison.change <= 1:\n break\n print(f\" {comparison}\")\n\n # Generate and save the histogram of time changes.\n plt.xlabel(\"Time change (contender/baseline)\")\n plt.ylabel(\"Number of benchmarks\")\n n, bins, patches = plt.hist([comparison.change for comparison in comparisons])\n bin_centers = np.diff(bins) / 2 + bins[:-1]\n for bar, count, x in zip(patches, n, bin_centers):\n plt.text(x, count + 0.5, str(count), ha=\"center\", va=\"bottom\")\n\n histogram_out = os.path.join(out_dir, \"histogram.png\")\n plt.savefig(histogram_out)\n print()\n print(f\"Saved the histogram of time changes to {histogram_out}.\")\n\n\ndef get_head_branch_or_commit() -> str:\n # Return the branch name if possible.\n head_branch_or_commit = subprocess.check_output(\n \"git rev-parse --abbrev-ref HEAD\", text=True, shell=True\n ).strip()\n\n if head_branch_or_commit != \"HEAD\":\n return head_branch_or_commit\n # Head is detached. Return the commit instead.\n return subprocess.check_output(\"git rev-parse HEAD\", text=True, shell=True).strip()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Runs nvfuser_bench on two commits and compares their results. See https://github.com/NVIDIA/Fuser/wiki/Developer-guide#benchmark-nvfuser for usage.\"\n )\n\n parser.add_argument(\"baseline\", type=str, help=\"The baseline branch or commit\")\n parser.add_argument(\"contender\", type=str, help=\"The contender branch or commit\")\n parser.add_argument(\n \"out_dir\",\n type=str,\n help=\"The output folder that will contain benchmark results and comparison\",\n )\n parser.add_argument(\n \"benchmark_args\",\n type=str,\n nargs=argparse.REMAINDER,\n help=\"Arguments passed to nvfuser_bench, e.g., --benchmark_filter=NvFuserScheduler\",\n )","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.compare_benchmark.__str__","uri":"program://Fuser/function/tools.compare_benchmark.__str__#L99-L100","kind":"function","name":"__str__","path":"tools/compare_benchmark.py","language":"python","start_line":99,"end_line":100,"context_start_line":79,"context_end_line":120,"code":" print(\"Running benchmark command: \" + benchmark_command)\n print(f\"Stdout and stderr are redirected to {stdout_path} and {stderr_path}.\")\n with open(stdout_path, \"w\") as stdout, open(stderr_path, \"w\") as stderr:\n subprocess.check_call(\n benchmark_command, stdout=stdout, stderr=stderr, shell=True\n )\n print(f\"The benchmark output is stored in {benchmark_out}.\")\n\n return benchmark_out\n\n\n@dataclass\nclass Comparison:\n name: str\n baseline_time: float\n contender_time: float\n # contender_time divided by baseline_time. Smaller is better.\n change: float\n time_unit: str\n\n def __str__(self):\n return f\"Benchmark {self.name} changed from {self.baseline_time}{self.time_unit} to {self.contender_time}{self.time_unit} ({self.change:.2f}x)\"\n\n\n# Compares the two given benchmark results and produces a .json file containing\n# the comparison.\ndef compare(baseline_out: str, contender_out: str, out_dir: str) -> str:\n baseline, _ = os.path.splitext(os.path.basename(baseline_out))\n contender, _ = os.path.splitext(os.path.basename(contender_out))\n comparison_out = os.path.join(out_dir, f\"{baseline}_vs_{contender}.json\")\n subprocess.check_call(\n f\"third_party/benchmark/tools/compare.py -d {comparison_out} benchmarks {baseline_out} {contender_out}\",\n shell=True,\n )\n return comparison_out\n\n\ndef load_comparison(comparison_out: str) -> list[Comparison]:\n comparisons: list[Comparison] = []\n with open(comparison_out) as f:\n data = json.loads(f.read())\n","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.memory","uri":"program://Fuser/module/tools.memory#L1-L28","kind":"module","name":"tools.memory","path":"python/tools/memory.py","language":"python","start_line":1,"end_line":28,"context_start_line":1,"context_end_line":28,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\ndef get_available_memory_gb():\n \"\"\"Returns the available memory in GB.\"\"\"\n try:\n import psutil\n\n return psutil.virtual_memory().available / 1024 / 1024 / 1024\n except: # noqa: E722\n pass\n\n try:\n with open(\"/proc/meminfo\", \"r\") as f:\n while True:\n line = f.readline()\n if line.startswith(\"MemAvailable:\"):\n mem = line.split()[1]\n assert line.split()[2] == \"kB\"\n return int(mem) / 1024 / 1024\n if not line:\n break\n except: # noqa: E722\n pass\n\n return 0","source_hash":"29abf2a174c9e2b85c35c42603262a8157251a100571e5525577f4fff6e00105","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.memory.get_available_memory_gb","uri":"program://Fuser/function/tools.memory.get_available_memory_gb#L6-L28","kind":"function","name":"get_available_memory_gb","path":"python/tools/memory.py","language":"python","start_line":6,"end_line":28,"context_start_line":1,"context_end_line":28,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\ndef get_available_memory_gb():\n \"\"\"Returns the available memory in GB.\"\"\"\n try:\n import psutil\n\n return psutil.virtual_memory().available / 1024 / 1024 / 1024\n except: # noqa: E722\n pass\n\n try:\n with open(\"/proc/meminfo\", \"r\") as f:\n while True:\n line = f.readline()\n if line.startswith(\"MemAvailable:\"):\n mem = line.split()[1]\n assert line.split()[2] == \"kB\"\n return int(mem) / 1024 / 1024\n if not line:\n break\n except: # noqa: E722\n pass\n\n return 0","source_hash":"29abf2a174c9e2b85c35c42603262a8157251a100571e5525577f4fff6e00105","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.cpp-repro-gen","uri":"program://Fuser/module/tools.cpp-repro-gen#L1-L353","kind":"module","name":"tools.cpp-repro-gen","path":"tools/cpp-repro-gen.py","language":"python","start_line":1,"end_line":353,"context_start_line":1,"context_end_line":353,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport ast\nimport typing\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--symbolic_sizes\", nargs=\"+\", type=int)\ncmd_args = parser.parse_args()\nsymbolic_sizes_index = 0\n\ninput = sys.stdin.read()\n\nlines = input.strip().splitlines()\n\nis_aten = False\n\n\ndef parse(l: str):\n ast_ = ast.parse(l)\n assert len(ast_.body) == 1\n return ast_.body[0]\n\n\ndef replace_name(name: str):\n ops_prefix = \"fd.ops.\"\n if name.startswith(\"T\"):\n if is_aten:\n return f\"t{name[1:]}\"\n else:\n return f\"tv{name[1:]}\"\n elif name.startswith(\"S\"):\n return f\"s{name[1:]}\"\n elif name.startswith(ops_prefix):\n op = name[len(ops_prefix) :]\n if is_aten:\n return \"at::\" + op\n else:\n if op == \"cast\":\n return \"castOp\"\n if op == \"var_mean\":\n return \"variance_mean\"\n return op\n elif name == \"fd.add_output\":\n if is_aten:\n return \"outputs.push_back\"\n else:\n return \"fusion->addOutput\"\n elif name == \"fd.define_scalar\":\n if not is_aten:\n return \"IrBuilder::create\"\n return name\n\n\ndef tocppstr(x):\n if isinstance(x, bool):\n return \"true\" if x else \"false\"\n return str(x)\n\n\ndef list2vector(l: typing.Union[ast.List, list]):\n if isinstance(l, ast.List):\n l = eval(ast.unparse(l))\n l = [tocppstr(x) for x in l]\n l = \"{\" + \", \".join(l) + \"}\"\n return ast.Name(l)\n\n\ndef handle_call(l: ast.Call):\n func = ast.Name(replace_name(ast.unparse(l.func)))\n args = handle(l.args)\n keywords = l.keywords\n if func.id == \"IrBuilder::create\":\n assert len(args) == 1\n arg = args[0]\n assert isinstance(arg, ast.Constant)\n arg = arg.value\n if len(keywords) > 0:\n keyword = keywords[0]\n assert keyword.arg == \"dtype\"\n value = ast.unparse(keyword.value).replace(\".\", \"::\")\n value = ast.Name(value)\n args.append(value)\n keywords = []\n elif func.id == \"fd.define_scalar\":\n assert is_aten\n arg = args[0]\n assert isinstance(arg, ast.Constant)\n return arg\n elif func.id == \"castOp\":\n assert len(args) == 1\n assert len(keywords) == 1\n keyword = keywords[0]\n assert isinstance(keyword, ast.keyword)\n assert keyword.arg == \"dtype\"\n value = ast.unparse(keyword.value).replace(\".\", \"::\")\n value = ast.Name(value)\n args.insert(0, value)\n keywords = []\n elif func.id == \"at::cast\":\n assert is_aten\n assert len(args) == 1\n assert len(keywords) == 1\n keyword = keywords[0]\n assert isinstance(keyword, ast.keyword)\n assert keyword.arg == \"dtype\"\n value = ast.unparse(keyword.value).replace(\"DataType.\", \"ScalarType::\")\n value = ast.Name(value)\n func = ast.Attribute(args[0], \"to\")\n args[0] = value\n keywords = []\n elif func.id == \"view\" or func.id == \"at::view\":\n assert len(args) == 1\n assert len(keywords) == 2\n\n original_shape = keywords[0]\n assert original_shape.arg == \"original_shape\"\n original_shape = list2vector(original_shape.value)\n\n new_shape = keywords[1]\n assert new_shape.arg == \"new_shape\"\n new_shape = list2vector(new_shape.value)\n\n if is_aten:\n func = ast.Attribute(args[0], \"view\")\n args = [new_shape]\n else:\n args.extend([original_shape, new_shape])\n\n keywords = []\n elif func.id == \"fd.define_tensor\":\n assert len(keywords) == 3\n assert len(args) == 0\n\n symbolic_sizes = keywords[0]\n assert symbolic_sizes.arg == \"symbolic_sizes\"\n symbolic_sizes_val = symbolic_sizes.value\n ndims = len(symbolic_sizes_val.elts)\n symbolic_sizes = list2vector(symbolic_sizes_val)\n\n contiguous = keywords[1]\n assert contiguous.arg == \"contiguous\"\n contiguous = contiguous.value\n assert ndims == len(contiguous.elts)\n contiguous = list2vector(contiguous)\n\n dtype = keywords[2]\n assert dtype.arg == \"dtype\"\n dtype = ast.unparse(dtype.value)\n if is_aten:\n sizes = symbolic_sizes\n if cmd_args.symbolic_sizes is not None:\n sizes = eval(ast.unparse(symbolic_sizes_val))\n for i, s in enumerate(sizes):\n if s == -1:\n global symbolic_sizes_index\n sizes[i] = cmd_args.symbolic_sizes[symbolic_sizes_index]\n symbolic_sizes_index += 1\n sizes = list2vector(sizes)\n result = ast.Call(ast.Name(\"at::randn\"), [sizes, ast.Name(\"options\")], [])\n if dtype != \"DataType.Float\":\n to = ast.Attribute(result, \"to\")\n result = ast.Call(\n to, [ast.Name(dtype.replace(\"DataType.\", \"ScalarType::\"))], []\n )\n if \"false\" in contiguous.id:\n contig = ast.Attribute(result, \"set_contiguous\")\n result = ast.Call(contig, [contiguous], [])\n return result\n else:\n builder = ast.Name(\"TensorViewBuilder()\")\n ndims_call = ast.Call(\n ast.Attribute(builder, \"ndims\"), [ast.Constant(ndims)], []\n )\n shape_call = ast.Call(\n ast.Attribute(ndims_call, \"shape\"), [symbolic_sizes], []\n )\n contig_call = ast.Call(\n ast.Attribute(shape_call, \"contiguity\"), [contiguous], []\n )\n dtype_call = ast.Call(\n ast.Attribute(contig_call, \"dtype\"),\n [ast.Name(dtype.replace(\".\", \"::\"))],\n [],\n )\n build_call = ast.Call(ast.Attribute(dtype_call, \"build\"), [], [])\n return build_call\n elif func.id == \"broadcast_in_dim\" or func.id == \"at::broadcast_in_dim\":\n assert len(keywords) == 2\n assert len(args) == 1\n\n output_shape = keywords[0]\n assert output_shape.arg == \"output_shape\"\n output_shape = output_shape.value\n output_shape = eval(ast.unparse(output_shape))\n\n broadcast_dims = keywords[1]\n assert broadcast_dims.arg == \"broadcast_dims\"\n broadcast_dims = broadcast_dims.value\n broadcast_dims = eval(ast.unparse(broadcast_dims))\n\n n_out_dims = len(output_shape)\n\n is_broadcast = [True] * n_out_dims\n for orig_dim in broadcast_dims:\n is_broadcast[orig_dim] = False\n\n if is_aten:\n result = args[0]\n for i, b in enumerate(is_broadcast):\n if b:\n result = ast.Call(\n ast.Attribute(result, \"unsqueeze\"), [ast.Constant(i)], []\n )\n result = ast.Call(\n ast.Attribute(result, \"expand\"), [list2vector(output_shape)], []\n )\n else:\n result = ast.Call(\n ast.Name(\"broadcast\"), [args[0], list2vector(is_broadcast)], []\n )\n result = ast.Call(\n ast.Name(\"expand\"),\n [\n result,\n list2vector([f\"IrBuilder::create({x})\" for x in output_shape]),\n ],\n [],\n )\n\n return result\n elif func.id == \"at::var_mean\" or func.id == \"variance_mean\":\n assert len(args) == 1\n assert len(keywords) == 3\n\n axes = keywords[0]\n assert isinstance(axes, ast.keyword)\n assert axes.arg == \"axes\"\n axes = list2vector(axes.value)\n\n correction = keywords[1]\n assert isinstance(correction, ast.keyword)\n assert correction.arg == \"correction\"\n correction = correction.value\n\n keepdim = keywords[2]\n assert isinstance(keepdim, ast.keyword)\n assert keepdim.arg == \"keepdim\"\n keepdim = keepdim.value\n assert isinstance(keepdim, ast.Constant)\n keepdim = ast.Name(tocppstr(keepdim.value))\n\n args.extend([axes, correction, keepdim])\n keywords = []\n\n return ast.Call(func, args, keywords)\n\n\ndef handle(l):\n if isinstance(l, list):\n result = []\n for item in l:\n result.append(handle(item))\n return result\n elif isinstance(l, ast.Assign):\n create = ast.Assign(handle(l.targets), handle(l.value), l.type_comment)\n if len(create.targets) == 1 and isinstance(create.targets[0], ast.Tuple):\n targets = create.targets[0].elts\n tuple_name = ast.Name(\"_\".join([x.id for x in targets]))\n create.targets[0] = tuple_name\n result = [create]\n for i, n in enumerate(targets):\n value = ast.Call(ast.Name(f\"std::get<{i}>\"), [tuple_name], [])\n result.append(ast.Assign([n], value))\n return result\n is_define_tensor = (\n isinstance(l.value, ast.Call)\n and ast.unparse(l.value.func) == \"fd.define_tensor\"\n )\n if is_define_tensor:\n if is_aten:\n func = \"inputs.push_back\"\n else:\n func = \"fusion->addInput\"\n assert len(create.targets) == 1\n add = ast.Call(ast.Name(func), [create.targets[0]], [])\n return [create, add]\n else:\n return create\n elif isinstance(l, ast.Name):\n return ast.Name(replace_name(l.id), l.ctx)\n elif isinstance(l, ast.Call):\n return handle_call(l)\n elif isinstance(l, ast.Expr):\n return ast.Expr(handle(l.value))\n elif isinstance(l, ast.Tuple):\n return ast.Tuple([handle(x) for x in l.elts])\n return l\n\n\ndef ast2str(l):\n if isinstance(l, ast.Assign):\n assert len(l.targets) == 1\n return f\"auto {ast2str(l.targets[0])} = {ast2str(l.value)}\"\n l.lineno = 0\n return ast.unparse(l)\n\n\ntest_str = \"\"\"TEST_F(NVFuserTest, FusionGeneratedTest_CUDA) {\n std::unique_ptr fusion_ptr = std::make_unique();\n auto fusion = fusion_ptr.get();\n FusionGuard fg(fusion);\n\n {\n\"\"\"\n\nfor l in lines:\n l = parse(l)\n l = handle(l)\n if not isinstance(l, list):\n l = [l]\n for x in l:\n test_str += f\" {ast2str(x)};\\n\"\n\ntest_str += \"\"\" }\n\n auto options = at::TensorOptions().dtype(kFloat).device(at::kCUDA, 0);\n std::vector inputs;\n std::vector outputs;\n\n {\n\"\"\"\n\nis_aten = True\n\nfor l in lines:\n l = parse(l)\n l = handle(l)\n if not isinstance(l, list):\n l = [l]\n for x in l:\n test_str += f\" {ast2str(x)};\\n\"\n\ntest_str += \"\"\" }\n\n FusionExecutorCache executor_cache(std::move(fusion_ptr));\n auto cg_outputs = executor_cache.runFusionWithInputs(inputs);\n testValidate(fusion, cg_outputs, inputs, outputs, __LINE__, __FILE__);\n}\"\"\"\n\nprint(test_str)","source_hash":"83e86d88435c8764f25a0322df76892dc9a5019c8cc7b9b1f739b8c1ecee78e5","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.cpp-repro-gen.parse","uri":"program://Fuser/function/tools.cpp-repro-gen.parse#L21-L24","kind":"function","name":"parse","path":"tools/cpp-repro-gen.py","language":"python","start_line":21,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport ast\nimport typing\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--symbolic_sizes\", nargs=\"+\", type=int)\ncmd_args = parser.parse_args()\nsymbolic_sizes_index = 0\n\ninput = sys.stdin.read()\n\nlines = input.strip().splitlines()\n\nis_aten = False\n\n\ndef parse(l: str):\n ast_ = ast.parse(l)\n assert len(ast_.body) == 1\n return ast_.body[0]\n\n\ndef replace_name(name: str):\n ops_prefix = \"fd.ops.\"\n if name.startswith(\"T\"):\n if is_aten:\n return f\"t{name[1:]}\"\n else:\n return f\"tv{name[1:]}\"\n elif name.startswith(\"S\"):\n return f\"s{name[1:]}\"\n elif name.startswith(ops_prefix):\n op = name[len(ops_prefix) :]\n if is_aten:\n return \"at::\" + op\n else:\n if op == \"cast\":\n return \"castOp\"\n if op == \"var_mean\":\n return \"variance_mean\"","source_hash":"83e86d88435c8764f25a0322df76892dc9a5019c8cc7b9b1f739b8c1ecee78e5","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.cpp-repro-gen.replace_name","uri":"program://Fuser/function/tools.cpp-repro-gen.replace_name#L27-L54","kind":"function","name":"replace_name","path":"tools/cpp-repro-gen.py","language":"python","start_line":27,"end_line":54,"context_start_line":7,"context_end_line":74,"code":"import argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--symbolic_sizes\", nargs=\"+\", type=int)\ncmd_args = parser.parse_args()\nsymbolic_sizes_index = 0\n\ninput = sys.stdin.read()\n\nlines = input.strip().splitlines()\n\nis_aten = False\n\n\ndef parse(l: str):\n ast_ = ast.parse(l)\n assert len(ast_.body) == 1\n return ast_.body[0]\n\n\ndef replace_name(name: str):\n ops_prefix = \"fd.ops.\"\n if name.startswith(\"T\"):\n if is_aten:\n return f\"t{name[1:]}\"\n else:\n return f\"tv{name[1:]}\"\n elif name.startswith(\"S\"):\n return f\"s{name[1:]}\"\n elif name.startswith(ops_prefix):\n op = name[len(ops_prefix) :]\n if is_aten:\n return \"at::\" + op\n else:\n if op == \"cast\":\n return \"castOp\"\n if op == \"var_mean\":\n return \"variance_mean\"\n return op\n elif name == \"fd.add_output\":\n if is_aten:\n return \"outputs.push_back\"\n else:\n return \"fusion->addOutput\"\n elif name == \"fd.define_scalar\":\n if not is_aten:\n return \"IrBuilder::create\"\n return name\n\n\ndef tocppstr(x):\n if isinstance(x, bool):\n return \"true\" if x else \"false\"\n return str(x)\n\n\ndef list2vector(l: typing.Union[ast.List, list]):\n if isinstance(l, ast.List):\n l = eval(ast.unparse(l))\n l = [tocppstr(x) for x in l]\n l = \"{\" + \", \".join(l) + \"}\"\n return ast.Name(l)\n\n\ndef handle_call(l: ast.Call):\n func = ast.Name(replace_name(ast.unparse(l.func)))\n args = handle(l.args)\n keywords = l.keywords","source_hash":"83e86d88435c8764f25a0322df76892dc9a5019c8cc7b9b1f739b8c1ecee78e5","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.cpp-repro-gen.tocppstr","uri":"program://Fuser/function/tools.cpp-repro-gen.tocppstr#L57-L60","kind":"function","name":"tocppstr","path":"tools/cpp-repro-gen.py","language":"python","start_line":57,"end_line":60,"context_start_line":37,"context_end_line":80,"code":" op = name[len(ops_prefix) :]\n if is_aten:\n return \"at::\" + op\n else:\n if op == \"cast\":\n return \"castOp\"\n if op == \"var_mean\":\n return \"variance_mean\"\n return op\n elif name == \"fd.add_output\":\n if is_aten:\n return \"outputs.push_back\"\n else:\n return \"fusion->addOutput\"\n elif name == \"fd.define_scalar\":\n if not is_aten:\n return \"IrBuilder::create\"\n return name\n\n\ndef tocppstr(x):\n if isinstance(x, bool):\n return \"true\" if x else \"false\"\n return str(x)\n\n\ndef list2vector(l: typing.Union[ast.List, list]):\n if isinstance(l, ast.List):\n l = eval(ast.unparse(l))\n l = [tocppstr(x) for x in l]\n l = \"{\" + \", \".join(l) + \"}\"\n return ast.Name(l)\n\n\ndef handle_call(l: ast.Call):\n func = ast.Name(replace_name(ast.unparse(l.func)))\n args = handle(l.args)\n keywords = l.keywords\n if func.id == \"IrBuilder::create\":\n assert len(args) == 1\n arg = args[0]\n assert isinstance(arg, ast.Constant)\n arg = arg.value\n if len(keywords) > 0:","source_hash":"83e86d88435c8764f25a0322df76892dc9a5019c8cc7b9b1f739b8c1ecee78e5","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.cpp-repro-gen.list2vector","uri":"program://Fuser/function/tools.cpp-repro-gen.list2vector#L63-L68","kind":"function","name":"list2vector","path":"tools/cpp-repro-gen.py","language":"python","start_line":63,"end_line":68,"context_start_line":43,"context_end_line":88,"code":" if op == \"var_mean\":\n return \"variance_mean\"\n return op\n elif name == \"fd.add_output\":\n if is_aten:\n return \"outputs.push_back\"\n else:\n return \"fusion->addOutput\"\n elif name == \"fd.define_scalar\":\n if not is_aten:\n return \"IrBuilder::create\"\n return name\n\n\ndef tocppstr(x):\n if isinstance(x, bool):\n return \"true\" if x else \"false\"\n return str(x)\n\n\ndef list2vector(l: typing.Union[ast.List, list]):\n if isinstance(l, ast.List):\n l = eval(ast.unparse(l))\n l = [tocppstr(x) for x in l]\n l = \"{\" + \", \".join(l) + \"}\"\n return ast.Name(l)\n\n\ndef handle_call(l: ast.Call):\n func = ast.Name(replace_name(ast.unparse(l.func)))\n args = handle(l.args)\n keywords = l.keywords\n if func.id == \"IrBuilder::create\":\n assert len(args) == 1\n arg = args[0]\n assert isinstance(arg, ast.Constant)\n arg = arg.value\n if len(keywords) > 0:\n keyword = keywords[0]\n assert keyword.arg == \"dtype\"\n value = ast.unparse(keyword.value).replace(\".\", \"::\")\n value = ast.Name(value)\n args.append(value)\n keywords = []\n elif func.id == \"fd.define_scalar\":\n assert is_aten","source_hash":"83e86d88435c8764f25a0322df76892dc9a5019c8cc7b9b1f739b8c1ecee78e5","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.cpp-repro-gen.handle_call","uri":"program://Fuser/function/tools.cpp-repro-gen.handle_call#L71-L258","kind":"function","name":"handle_call","path":"tools/cpp-repro-gen.py","language":"python","start_line":71,"end_line":258,"context_start_line":51,"context_end_line":278,"code":" elif name == \"fd.define_scalar\":\n if not is_aten:\n return \"IrBuilder::create\"\n return name\n\n\ndef tocppstr(x):\n if isinstance(x, bool):\n return \"true\" if x else \"false\"\n return str(x)\n\n\ndef list2vector(l: typing.Union[ast.List, list]):\n if isinstance(l, ast.List):\n l = eval(ast.unparse(l))\n l = [tocppstr(x) for x in l]\n l = \"{\" + \", \".join(l) + \"}\"\n return ast.Name(l)\n\n\ndef handle_call(l: ast.Call):\n func = ast.Name(replace_name(ast.unparse(l.func)))\n args = handle(l.args)\n keywords = l.keywords\n if func.id == \"IrBuilder::create\":\n assert len(args) == 1\n arg = args[0]\n assert isinstance(arg, ast.Constant)\n arg = arg.value\n if len(keywords) > 0:\n keyword = keywords[0]\n assert keyword.arg == \"dtype\"\n value = ast.unparse(keyword.value).replace(\".\", \"::\")\n value = ast.Name(value)\n args.append(value)\n keywords = []\n elif func.id == \"fd.define_scalar\":\n assert is_aten\n arg = args[0]\n assert isinstance(arg, ast.Constant)\n return arg\n elif func.id == \"castOp\":\n assert len(args) == 1\n assert len(keywords) == 1\n keyword = keywords[0]\n assert isinstance(keyword, ast.keyword)\n assert keyword.arg == \"dtype\"\n value = ast.unparse(keyword.value).replace(\".\", \"::\")\n value = ast.Name(value)\n args.insert(0, value)\n keywords = []\n elif func.id == \"at::cast\":\n assert is_aten\n assert len(args) == 1\n assert len(keywords) == 1\n keyword = keywords[0]\n assert isinstance(keyword, ast.keyword)\n assert keyword.arg == \"dtype\"\n value = ast.unparse(keyword.value).replace(\"DataType.\", \"ScalarType::\")\n value = ast.Name(value)\n func = ast.Attribute(args[0], \"to\")\n args[0] = value\n keywords = []\n elif func.id == \"view\" or func.id == \"at::view\":\n assert len(args) == 1\n assert len(keywords) == 2\n\n original_shape = keywords[0]\n assert original_shape.arg == \"original_shape\"\n original_shape = list2vector(original_shape.value)\n\n new_shape = keywords[1]\n assert new_shape.arg == \"new_shape\"\n new_shape = list2vector(new_shape.value)\n\n if is_aten:\n func = ast.Attribute(args[0], \"view\")\n args = [new_shape]\n else:\n args.extend([original_shape, new_shape])\n\n keywords = []\n elif func.id == \"fd.define_tensor\":\n assert len(keywords) == 3\n assert len(args) == 0\n\n symbolic_sizes = keywords[0]\n assert symbolic_sizes.arg == \"symbolic_sizes\"\n symbolic_sizes_val = symbolic_sizes.value\n ndims = len(symbolic_sizes_val.elts)\n symbolic_sizes = list2vector(symbolic_sizes_val)\n\n contiguous = keywords[1]\n assert contiguous.arg == \"contiguous\"\n contiguous = contiguous.value\n assert ndims == len(contiguous.elts)\n contiguous = list2vector(contiguous)\n\n dtype = keywords[2]\n assert dtype.arg == \"dtype\"\n dtype = ast.unparse(dtype.value)\n if is_aten:\n sizes = symbolic_sizes\n if cmd_args.symbolic_sizes is not None:\n sizes = eval(ast.unparse(symbolic_sizes_val))\n for i, s in enumerate(sizes):\n if s == -1:\n global symbolic_sizes_index\n sizes[i] = cmd_args.symbolic_sizes[symbolic_sizes_index]\n symbolic_sizes_index += 1\n sizes = list2vector(sizes)\n result = ast.Call(ast.Name(\"at::randn\"), [sizes, ast.Name(\"options\")], [])\n if dtype != \"DataType.Float\":\n to = ast.Attribute(result, \"to\")\n result = ast.Call(\n to, [ast.Name(dtype.replace(\"DataType.\", \"ScalarType::\"))], []\n )\n if \"false\" in contiguous.id:\n contig = ast.Attribute(result, \"set_contiguous\")\n result = ast.Call(contig, [contiguous], [])\n return result\n else:\n builder = ast.Name(\"TensorViewBuilder()\")\n ndims_call = ast.Call(\n ast.Attribute(builder, \"ndims\"), [ast.Constant(ndims)], []\n )\n shape_call = ast.Call(\n ast.Attribute(ndims_call, \"shape\"), [symbolic_sizes], []\n )\n contig_call = ast.Call(\n ast.Attribute(shape_call, \"contiguity\"), [contiguous], []\n )\n dtype_call = ast.Call(\n ast.Attribute(contig_call, \"dtype\"),\n [ast.Name(dtype.replace(\".\", \"::\"))],\n [],\n )\n build_call = ast.Call(ast.Attribute(dtype_call, \"build\"), [], [])\n return build_call\n elif func.id == \"broadcast_in_dim\" or func.id == \"at::broadcast_in_dim\":\n assert len(keywords) == 2\n assert len(args) == 1\n\n output_shape = keywords[0]\n assert output_shape.arg == \"output_shape\"\n output_shape = output_shape.value\n output_shape = eval(ast.unparse(output_shape))\n\n broadcast_dims = keywords[1]\n assert broadcast_dims.arg == \"broadcast_dims\"\n broadcast_dims = broadcast_dims.value\n broadcast_dims = eval(ast.unparse(broadcast_dims))\n\n n_out_dims = len(output_shape)\n\n is_broadcast = [True] * n_out_dims\n for orig_dim in broadcast_dims:\n is_broadcast[orig_dim] = False\n\n if is_aten:\n result = args[0]\n for i, b in enumerate(is_broadcast):\n if b:\n result = ast.Call(\n ast.Attribute(result, \"unsqueeze\"), [ast.Constant(i)], []\n )\n result = ast.Call(\n ast.Attribute(result, \"expand\"), [list2vector(output_shape)], []\n )\n else:\n result = ast.Call(\n ast.Name(\"broadcast\"), [args[0], list2vector(is_broadcast)], []\n )\n result = ast.Call(\n ast.Name(\"expand\"),\n [\n result,\n list2vector([f\"IrBuilder::create({x})\" for x in output_shape]),\n ],\n [],\n )\n\n return result\n elif func.id == \"at::var_mean\" or func.id == \"variance_mean\":\n assert len(args) == 1\n assert len(keywords) == 3\n\n axes = keywords[0]\n assert isinstance(axes, ast.keyword)\n assert axes.arg == \"axes\"\n axes = list2vector(axes.value)\n\n correction = keywords[1]\n assert isinstance(correction, ast.keyword)\n assert correction.arg == \"correction\"\n correction = correction.value\n\n keepdim = keywords[2]\n assert isinstance(keepdim, ast.keyword)\n assert keepdim.arg == \"keepdim\"\n keepdim = keepdim.value\n assert isinstance(keepdim, ast.Constant)\n keepdim = ast.Name(tocppstr(keepdim.value))\n\n args.extend([axes, correction, keepdim])\n keywords = []\n\n return ast.Call(func, args, keywords)\n\n\ndef handle(l):\n if isinstance(l, list):\n result = []\n for item in l:\n result.append(handle(item))\n return result\n elif isinstance(l, ast.Assign):\n create = ast.Assign(handle(l.targets), handle(l.value), l.type_comment)\n if len(create.targets) == 1 and isinstance(create.targets[0], ast.Tuple):\n targets = create.targets[0].elts\n tuple_name = ast.Name(\"_\".join([x.id for x in targets]))\n create.targets[0] = tuple_name\n result = [create]\n for i, n in enumerate(targets):\n value = ast.Call(ast.Name(f\"std::get<{i}>\"), [tuple_name], [])\n result.append(ast.Assign([n], value))\n return result\n is_define_tensor = (","source_hash":"83e86d88435c8764f25a0322df76892dc9a5019c8cc7b9b1f739b8c1ecee78e5","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.cpp-repro-gen.handle","uri":"program://Fuser/function/tools.cpp-repro-gen.handle#L261-L300","kind":"function","name":"handle","path":"tools/cpp-repro-gen.py","language":"python","start_line":261,"end_line":300,"context_start_line":241,"context_end_line":320,"code":" axes = list2vector(axes.value)\n\n correction = keywords[1]\n assert isinstance(correction, ast.keyword)\n assert correction.arg == \"correction\"\n correction = correction.value\n\n keepdim = keywords[2]\n assert isinstance(keepdim, ast.keyword)\n assert keepdim.arg == \"keepdim\"\n keepdim = keepdim.value\n assert isinstance(keepdim, ast.Constant)\n keepdim = ast.Name(tocppstr(keepdim.value))\n\n args.extend([axes, correction, keepdim])\n keywords = []\n\n return ast.Call(func, args, keywords)\n\n\ndef handle(l):\n if isinstance(l, list):\n result = []\n for item in l:\n result.append(handle(item))\n return result\n elif isinstance(l, ast.Assign):\n create = ast.Assign(handle(l.targets), handle(l.value), l.type_comment)\n if len(create.targets) == 1 and isinstance(create.targets[0], ast.Tuple):\n targets = create.targets[0].elts\n tuple_name = ast.Name(\"_\".join([x.id for x in targets]))\n create.targets[0] = tuple_name\n result = [create]\n for i, n in enumerate(targets):\n value = ast.Call(ast.Name(f\"std::get<{i}>\"), [tuple_name], [])\n result.append(ast.Assign([n], value))\n return result\n is_define_tensor = (\n isinstance(l.value, ast.Call)\n and ast.unparse(l.value.func) == \"fd.define_tensor\"\n )\n if is_define_tensor:\n if is_aten:\n func = \"inputs.push_back\"\n else:\n func = \"fusion->addInput\"\n assert len(create.targets) == 1\n add = ast.Call(ast.Name(func), [create.targets[0]], [])\n return [create, add]\n else:\n return create\n elif isinstance(l, ast.Name):\n return ast.Name(replace_name(l.id), l.ctx)\n elif isinstance(l, ast.Call):\n return handle_call(l)\n elif isinstance(l, ast.Expr):\n return ast.Expr(handle(l.value))\n elif isinstance(l, ast.Tuple):\n return ast.Tuple([handle(x) for x in l.elts])\n return l\n\n\ndef ast2str(l):\n if isinstance(l, ast.Assign):\n assert len(l.targets) == 1\n return f\"auto {ast2str(l.targets[0])} = {ast2str(l.value)}\"\n l.lineno = 0\n return ast.unparse(l)\n\n\ntest_str = \"\"\"TEST_F(NVFuserTest, FusionGeneratedTest_CUDA) {\n std::unique_ptr fusion_ptr = std::make_unique();\n auto fusion = fusion_ptr.get();\n FusionGuard fg(fusion);\n\n {\n\"\"\"\n\nfor l in lines:\n l = parse(l)","source_hash":"83e86d88435c8764f25a0322df76892dc9a5019c8cc7b9b1f739b8c1ecee78e5","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.cpp-repro-gen.ast2str","uri":"program://Fuser/function/tools.cpp-repro-gen.ast2str#L303-L308","kind":"function","name":"ast2str","path":"tools/cpp-repro-gen.py","language":"python","start_line":303,"end_line":308,"context_start_line":283,"context_end_line":328,"code":" if is_aten:\n func = \"inputs.push_back\"\n else:\n func = \"fusion->addInput\"\n assert len(create.targets) == 1\n add = ast.Call(ast.Name(func), [create.targets[0]], [])\n return [create, add]\n else:\n return create\n elif isinstance(l, ast.Name):\n return ast.Name(replace_name(l.id), l.ctx)\n elif isinstance(l, ast.Call):\n return handle_call(l)\n elif isinstance(l, ast.Expr):\n return ast.Expr(handle(l.value))\n elif isinstance(l, ast.Tuple):\n return ast.Tuple([handle(x) for x in l.elts])\n return l\n\n\ndef ast2str(l):\n if isinstance(l, ast.Assign):\n assert len(l.targets) == 1\n return f\"auto {ast2str(l.targets[0])} = {ast2str(l.value)}\"\n l.lineno = 0\n return ast.unparse(l)\n\n\ntest_str = \"\"\"TEST_F(NVFuserTest, FusionGeneratedTest_CUDA) {\n std::unique_ptr fusion_ptr = std::make_unique();\n auto fusion = fusion_ptr.get();\n FusionGuard fg(fusion);\n\n {\n\"\"\"\n\nfor l in lines:\n l = parse(l)\n l = handle(l)\n if not isinstance(l, list):\n l = [l]\n for x in l:\n test_str += f\" {ast2str(x)};\\n\"\n\ntest_str += \"\"\" }\n","source_hash":"83e86d88435c8764f25a0322df76892dc9a5019c8cc7b9b1f739b8c1ecee78e5","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.update_copyright","uri":"program://Fuser/module/tools.update_copyright#L1-L94","kind":"module","name":"tools.update_copyright","path":"tools/update_copyright.py","language":"python","start_line":1,"end_line":94,"context_start_line":1,"context_end_line":94,"code":"import os\n\next_map = {\n \"cpp\": (\"c\", \"cpp\", \"cu\", \"cc\", \"cuh\", \"h\"),\n \"py\": (\"py\",),\n \"txt\": (\"txt\",),\n}\n\nlicence_style_0 = \"\"\"\\\n// clang-format off\n/*\n * SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n * All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n */\n// clang-format on\n\"\"\"\n\nlicence_style_1 = \"\"\"\\\n# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\n\nheader_license = {\n \"cpp\": licence_style_0,\n \"py\": licence_style_1,\n \"txt\": licence_style_1,\n}\n\nexclude_list = (\n \"./tools/update_copyright.py\",\n \"./examples/sinh_libtorch/main.cpp\",\n \"./version.txt\",\n \"./test/main.cpp\",\n \"Dependencies.cmake\",\n \"FlatBuffers.cmake\",\n # lint adapters are taken from pytorch\n \"tools/linter/adapters/black_linter.py\",\n \"tools/linter/adapters/clangformat_linter.py\",\n \"tools/linter/adapters/clangtidy_linter.py\",\n \"tools/linter/adapters/exec_linter.py\",\n \"tools/linter/adapters/flake8_linter.py\",\n \"tools/linter/adapters/grep_linter.py\",\n \"tools/linter/adapters/mypy_linter.py\",\n \"tools/linter/adapters/newlines_linter.py\",\n \"tools/linter/adapters/pip_init.py\",\n \"tools/linter/adapters/README.md\",\n \"tools/linter/adapters/s3_init_config.json\",\n \"tools/linter/adapters/s3_init.py\",\n)\n\n\ndef get_exclusions():\n parent_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\n print(parent_path)\n return [os.path.abspath(os.path.join(parent_path, f)) for f in exclude_list]\n\n\ndef has_licence(file_handle, licence_str):\n header_content = file_handle.read(len(licence_str))\n file_handle.seek(0, 0)\n return header_content.startswith(licence_str)\n\n\ndef update_licence(file_handle, licence_str):\n if not has_licence(file_handle, licence_str):\n content = file_handle.read()\n file_handle.seek(0, 0)\n file_handle.write(licence_str + content)\n return True\n return False\n\n\ndef update_files(root_path):\n exclusions = get_exclusions()\n print(exclusions)\n for root, dirs, files in os.walk(root_path):\n for file_name in files:\n abs_file = os.path.abspath(os.path.join(root, file_name))\n print(abs_file)\n if file_name[0] == \".\" or abs_file in exclusions:\n continue\n file_ext = file_name.split(\".\")[-1]\n for k, v in ext_map.items():\n if file_ext in v:\n licence_str = header_license[k]\n with open(abs_file, \"r+\") as file_handle:\n if update_licence(file_handle, licence_str):\n print(\"attached licence header to \", abs_file)\n\n\nif __name__ == \"__main__\":\n update_files(\".\")","source_hash":"5c7c23caad57961775158ad10d8c49f08455a70399c887c69fb63d1006c9f4d1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.update_copyright.get_exclusions","uri":"program://Fuser/function/tools.update_copyright.get_exclusions#L54-L57","kind":"function","name":"get_exclusions","path":"tools/update_copyright.py","language":"python","start_line":54,"end_line":57,"context_start_line":34,"context_end_line":77,"code":" \"./version.txt\",\n \"./test/main.cpp\",\n \"Dependencies.cmake\",\n \"FlatBuffers.cmake\",\n # lint adapters are taken from pytorch\n \"tools/linter/adapters/black_linter.py\",\n \"tools/linter/adapters/clangformat_linter.py\",\n \"tools/linter/adapters/clangtidy_linter.py\",\n \"tools/linter/adapters/exec_linter.py\",\n \"tools/linter/adapters/flake8_linter.py\",\n \"tools/linter/adapters/grep_linter.py\",\n \"tools/linter/adapters/mypy_linter.py\",\n \"tools/linter/adapters/newlines_linter.py\",\n \"tools/linter/adapters/pip_init.py\",\n \"tools/linter/adapters/README.md\",\n \"tools/linter/adapters/s3_init_config.json\",\n \"tools/linter/adapters/s3_init.py\",\n)\n\n\ndef get_exclusions():\n parent_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\n print(parent_path)\n return [os.path.abspath(os.path.join(parent_path, f)) for f in exclude_list]\n\n\ndef has_licence(file_handle, licence_str):\n header_content = file_handle.read(len(licence_str))\n file_handle.seek(0, 0)\n return header_content.startswith(licence_str)\n\n\ndef update_licence(file_handle, licence_str):\n if not has_licence(file_handle, licence_str):\n content = file_handle.read()\n file_handle.seek(0, 0)\n file_handle.write(licence_str + content)\n return True\n return False\n\n\ndef update_files(root_path):\n exclusions = get_exclusions()\n print(exclusions)","source_hash":"5c7c23caad57961775158ad10d8c49f08455a70399c887c69fb63d1006c9f4d1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.update_copyright.has_licence","uri":"program://Fuser/function/tools.update_copyright.has_licence#L60-L63","kind":"function","name":"has_licence","path":"tools/update_copyright.py","language":"python","start_line":60,"end_line":63,"context_start_line":40,"context_end_line":83,"code":" \"tools/linter/adapters/clangformat_linter.py\",\n \"tools/linter/adapters/clangtidy_linter.py\",\n \"tools/linter/adapters/exec_linter.py\",\n \"tools/linter/adapters/flake8_linter.py\",\n \"tools/linter/adapters/grep_linter.py\",\n \"tools/linter/adapters/mypy_linter.py\",\n \"tools/linter/adapters/newlines_linter.py\",\n \"tools/linter/adapters/pip_init.py\",\n \"tools/linter/adapters/README.md\",\n \"tools/linter/adapters/s3_init_config.json\",\n \"tools/linter/adapters/s3_init.py\",\n)\n\n\ndef get_exclusions():\n parent_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\n print(parent_path)\n return [os.path.abspath(os.path.join(parent_path, f)) for f in exclude_list]\n\n\ndef has_licence(file_handle, licence_str):\n header_content = file_handle.read(len(licence_str))\n file_handle.seek(0, 0)\n return header_content.startswith(licence_str)\n\n\ndef update_licence(file_handle, licence_str):\n if not has_licence(file_handle, licence_str):\n content = file_handle.read()\n file_handle.seek(0, 0)\n file_handle.write(licence_str + content)\n return True\n return False\n\n\ndef update_files(root_path):\n exclusions = get_exclusions()\n print(exclusions)\n for root, dirs, files in os.walk(root_path):\n for file_name in files:\n abs_file = os.path.abspath(os.path.join(root, file_name))\n print(abs_file)\n if file_name[0] == \".\" or abs_file in exclusions:\n continue","source_hash":"5c7c23caad57961775158ad10d8c49f08455a70399c887c69fb63d1006c9f4d1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.update_copyright.update_licence","uri":"program://Fuser/function/tools.update_copyright.update_licence#L66-L72","kind":"function","name":"update_licence","path":"tools/update_copyright.py","language":"python","start_line":66,"end_line":72,"context_start_line":46,"context_end_line":92,"code":" \"tools/linter/adapters/newlines_linter.py\",\n \"tools/linter/adapters/pip_init.py\",\n \"tools/linter/adapters/README.md\",\n \"tools/linter/adapters/s3_init_config.json\",\n \"tools/linter/adapters/s3_init.py\",\n)\n\n\ndef get_exclusions():\n parent_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\n print(parent_path)\n return [os.path.abspath(os.path.join(parent_path, f)) for f in exclude_list]\n\n\ndef has_licence(file_handle, licence_str):\n header_content = file_handle.read(len(licence_str))\n file_handle.seek(0, 0)\n return header_content.startswith(licence_str)\n\n\ndef update_licence(file_handle, licence_str):\n if not has_licence(file_handle, licence_str):\n content = file_handle.read()\n file_handle.seek(0, 0)\n file_handle.write(licence_str + content)\n return True\n return False\n\n\ndef update_files(root_path):\n exclusions = get_exclusions()\n print(exclusions)\n for root, dirs, files in os.walk(root_path):\n for file_name in files:\n abs_file = os.path.abspath(os.path.join(root, file_name))\n print(abs_file)\n if file_name[0] == \".\" or abs_file in exclusions:\n continue\n file_ext = file_name.split(\".\")[-1]\n for k, v in ext_map.items():\n if file_ext in v:\n licence_str = header_license[k]\n with open(abs_file, \"r+\") as file_handle:\n if update_licence(file_handle, licence_str):\n print(\"attached licence header to \", abs_file)\n\n","source_hash":"5c7c23caad57961775158ad10d8c49f08455a70399c887c69fb63d1006c9f4d1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.update_copyright.update_files","uri":"program://Fuser/function/tools.update_copyright.update_files#L75-L90","kind":"function","name":"update_files","path":"tools/update_copyright.py","language":"python","start_line":75,"end_line":90,"context_start_line":55,"context_end_line":94,"code":" parent_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\n print(parent_path)\n return [os.path.abspath(os.path.join(parent_path, f)) for f in exclude_list]\n\n\ndef has_licence(file_handle, licence_str):\n header_content = file_handle.read(len(licence_str))\n file_handle.seek(0, 0)\n return header_content.startswith(licence_str)\n\n\ndef update_licence(file_handle, licence_str):\n if not has_licence(file_handle, licence_str):\n content = file_handle.read()\n file_handle.seek(0, 0)\n file_handle.write(licence_str + content)\n return True\n return False\n\n\ndef update_files(root_path):\n exclusions = get_exclusions()\n print(exclusions)\n for root, dirs, files in os.walk(root_path):\n for file_name in files:\n abs_file = os.path.abspath(os.path.join(root, file_name))\n print(abs_file)\n if file_name[0] == \".\" or abs_file in exclusions:\n continue\n file_ext = file_name.split(\".\")[-1]\n for k, v in ext_map.items():\n if file_ext in v:\n licence_str = header_license[k]\n with open(abs_file, \"r+\") as file_handle:\n if update_licence(file_handle, licence_str):\n print(\"attached licence header to \", abs_file)\n\n\nif __name__ == \"__main__\":\n update_files(\".\")","source_hash":"5c7c23caad57961775158ad10d8c49f08455a70399c887c69fb63d1006c9f4d1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.stringify_file","uri":"program://Fuser/module/tools.stringify_file#L1-L53","kind":"module","name":"tools.stringify_file","path":"tools/stringify_file.py","language":"python","start_line":1,"end_line":53,"context_start_line":1,"context_end_line":53,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n# Generates a C++ header files embedding the original input as a string literal\n\nimport argparse\nimport pathlib\nfrom datetime import datetime\n\narg_parser = argparse.ArgumentParser(\n description=\"Converts source files to C++ string literals\", allow_abbrev=False\n)\n\narg_parser.add_argument(\"-i\", \"--input\", required=True, help=\"Input source file\")\n\narg_parser.add_argument(\n \"-o\", \"--output\", required=True, help=\"Name of the generated header file\"\n)\n\nargs = arg_parser.parse_args()\n\n# msvc string literal maximum length 16380\n# https://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2026?view=msvc-170\nMAX_STRING_LITERAL = 1600000000000\n# https://docs.microsoft.com/en-us/cpp/c-language/maximum-string-length?view=msvc-170\nMAX_STRING_CONCATENATED = 6553500000000\n\nwith open(args.input, \"r\") as fin:\n with open(args.output, \"w\") as fout:\n literal_name = f\"{pathlib.Path(args.input).stem}_cu\"\n fout.write(f'// Generated from \"{args.input}\"\\n')\n fout.write(f'// {datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")}\\n\\n')\n fout.write(\"namespace nvfuser_resources {\\n\\n\")\n fout.write(f'constexpr const char* {literal_name} = R\"(\\n')\n accumulated_chars = 0\n accumulated_chars_per_literal = 0\n for line in fin:\n accumulated_chars = accumulated_chars + len(line) + 1\n accumulated_chars_per_literal = (\n accumulated_chars_per_literal + len(line) + 1\n )\n if accumulated_chars_per_literal >= MAX_STRING_LITERAL:\n fout.write(')\"\\n')\n fout.write('R\"(\\n')\n fout.write(line)\n accumulated_chars_per_literal = len(line) + 1\n else:\n fout.write(line)\n fout.write(')\";\\n')\n fout.write(\"\\n} // namespace nvfuser_resources\\n\")\n if accumulated_chars >= MAX_STRING_CONCATENATED:\n raise Exception(\"runtime header file exceeds size limit of 65535 for MSVC\")","source_hash":"0d1e992a976633f5108638a9c35a8895ff48c626e43dd7b9f82da24d4a513981","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests","uri":"program://Fuser/module/tools.run_nvfuser_tests#L1-L567","kind":"module","name":"tools.run_nvfuser_tests","path":"tools/run_nvfuser_tests.py","language":"python","start_line":1,"end_line":567,"context_start_line":1,"context_end_line":567,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport subprocess\nimport os\nimport glob\nimport datetime\nfrom pathlib import Path\nimport time\nimport argparse\n\n\ndef setup_logging_dir():\n \"\"\"Create a timestamped directory for test logs and update latest symlink\"\"\"\n timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n log_dir = Path(f\"test_log_{timestamp}\")\n log_dir.mkdir(exist_ok=True)\n\n # Check and handle the 'latest' symlink\n latest_link = Path(\"test_log_latest\")\n if latest_link.exists():\n if not latest_link.is_symlink():\n raise RuntimeError(\n \"test_log_latest exists but is not a symlink. \"\n \"Please remove it manually to proceed.\"\n )\n latest_link.unlink() # Remove existing symlink\n\n # Create new symlink pointing to the new log directory\n latest_link.symlink_to(log_dir, target_is_directory=True)\n\n return log_dir\n\n\ndef get_cpp_test_executables(build_dir):\n \"\"\"Find all test executables in the build directory\"\"\"\n all_tests = glob.glob(os.path.join(build_dir, \"*test*\"))\n\n # Separate multidevice and single device tests\n multidevice_tests, single_device_tests = [], []\n for test in all_tests:\n (single_device_tests, multidevice_tests)[\n \"multidevice\" in os.path.basename(test).lower()\n ].append(test)\n\n return multidevice_tests, single_device_tests\n\n\ndef get_python_tests(python_test_dir):\n \"\"\"Find all Python test files\"\"\"\n all_tests = glob.glob(os.path.join(python_test_dir, \"test_*.py\"))\n\n # Separate multidevice and single device tests\n # This is not catching all python multidevice tests like test_communication.py\n # TODO: Change test names to separate out multidevice tests, or update to support all multidevice python tests\n multidevice_tests, single_device_tests = [], []\n for test in all_tests:\n (single_device_tests, multidevice_tests)[\n \"multidevice\" in os.path.basename(test).lower()\n ].append(test)\n\n return multidevice_tests, single_device_tests\n\n\ndef get_test_timeout(test_name):\n \"\"\"Return timeout in seconds for a given test\"\"\"\n if test_name in [\"test_nvfuser\", \"test_matmul\", \"test_direct_ops.py\"]:\n return 3600 # 1 hour\n return 600 # 10 minutes\n\n\ndef run_multidevice_test(test_path, log_dir, num_gpus, dry_run=False):\n \"\"\"Run a multidevice test using mpirun\"\"\"\n test_name = os.path.basename(test_path)\n log_base = log_dir / test_name\n timeout = get_test_timeout(test_name)\n\n cmd = [\n \"mpirun\",\n \"-np\",\n str(num_gpus), # Use available GPU count\n \"--output-filename\",\n f\"{log_base}\",\n \"--merge-stderr-to-stdout\",\n test_path,\n ]\n\n if dry_run:\n print(f\"Would run: {' '.join(cmd)} (timeout: {timeout / 60} minutes)\")\n return True\n\n print(f\"Running multidevice test: {test_name}\")\n try:\n # Redirect output to /dev/null to suppress console output\n with open(os.devnull, \"w\") as devnull:\n result = subprocess.run(\n cmd, timeout=timeout, stdout=devnull, stderr=subprocess.STDOUT\n )\n return result.returncode == 0\n except subprocess.TimeoutExpired:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(f\"ERROR: Test timed out after {timeout / 60} minutes\\n\")\n return False\n except Exception as e:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(f\"ERROR: Failed to run test: {str(e)}\\n\")\n return False\n\n\ndef run_single_device_test(test_path, log_dir, gpu_id, dry_run=False):\n \"\"\"Run a single device test on specified GPU\"\"\"\n test_name = os.path.basename(test_path)\n log_file = log_dir / f\"{test_name}.log\"\n\n cmd = [test_path]\n env = os.environ.copy()\n env[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n\n if dry_run:\n print(f\"Would run: CUDA_VISIBLE_DEVICES={gpu_id} {' '.join(cmd)} > {log_file}\")\n return \"dry_run_process\"\n\n print(f\"Running test: {test_name} on GPU {gpu_id}\")\n try:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n process = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env)\n return process\n except Exception as e:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n f.write(f\"ERROR: Failed to start test: {str(e)}\\n\")\n return None\n\n\ndef run_python_multidevice_test(test_path, log_dir, num_gpus, dry_run=False):\n \"\"\"Run a Python multidevice test using mpirun\"\"\"\n test_name = os.path.basename(test_path)\n log_base = log_dir / f\"python_{test_name}\"\n\n cmd = [\n \"mpirun\",\n \"-np\",\n str(num_gpus), # Use available GPU count\n \"--output-filename\",\n f\"{log_base}\",\n \"--merge-stderr-to-stdout\",\n \"pytest\",\n test_path,\n \"-v\",\n ]\n\n if dry_run:\n print(f\"Would run: {' '.join(cmd)}\")\n return True\n\n print(f\"Running Python multidevice test: {test_name}\")\n try:\n # Redirect output to /dev/null to suppress console output\n with open(os.devnull, \"w\") as devnull:\n result = subprocess.run(\n cmd, timeout=1200, stdout=devnull, stderr=subprocess.STDOUT\n )\n return result.returncode == 0\n except subprocess.TimeoutExpired:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(\"ERROR: Test timed out after 20 minutes\\n\")\n return False\n except Exception as e:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(f\"ERROR: Failed to run test: {str(e)}\\n\")\n return False\n\n\ndef run_python_test(test_path, log_dir, gpu_id, dry_run=False):\n \"\"\"Run a Python test using pytest on specified GPU\"\"\"\n test_name = os.path.basename(test_path)\n log_file = log_dir / f\"python_{test_name}.log\"\n\n cmd = [\"pytest\", test_path, \"-v\"]\n env = os.environ.copy()\n env[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n\n if dry_run:\n print(f\"Would run: CUDA_VISIBLE_DEVICES={gpu_id} {' '.join(cmd)} > {log_file}\")\n return \"dry_run_process\"\n\n print(f\"Running Python test: {test_name} on GPU {gpu_id}\")\n try:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n process = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env)\n return process\n except Exception as e:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n f.write(f\"ERROR: Failed to start test: {str(e)}\\n\")\n return None\n\n\ndef run_parallel_tests(log_dir, num_gpus, test_infos, dry_run=False):\n \"\"\"Run tests in parallel across available GPUs using provided test configurations\"\"\"\n if dry_run:\n current_tests = {i: None for i in range(num_gpus)} # Simulate GPU allocation\n test_queue = test_infos.copy()\n\n print(f\"\\nSimulating parallel execution across {num_gpus} GPUs:\")\n\n # Initial allocation\n for gpu_id in range(num_gpus):\n if test_queue:\n test_path, run_func = test_queue.pop(0)\n current_tests[gpu_id] = (test_path, run_func)\n run_func(test_path, log_dir, gpu_id, dry_run=True)\n\n # Simulate rest of queue\n while test_queue:\n # Simulate round-robin GPU completion\n gpu_id = len(test_queue) % num_gpus\n current_test_path, _ = current_tests[gpu_id]\n print(f\"\\nGPU {gpu_id} finished {os.path.basename(current_test_path)}\")\n test_path, run_func = test_queue.pop(0)\n current_tests[gpu_id] = (test_path, run_func)\n run_func(test_path, log_dir, gpu_id, dry_run=True)\n\n # Show final tests completing\n for gpu_id in range(num_gpus):\n if current_tests[gpu_id]:\n test_path, _ = current_tests[gpu_id]\n print(f\"\\nGPU {gpu_id} finished {os.path.basename(test_path)}\")\n\n return [], []\n\n # Initialize test queue and tracking variables\n test_queue = test_infos.copy()\n current_processes = {i: None for i in range(num_gpus)}\n current_tests = {i: None for i in range(num_gpus)}\n start_times = {i: time.time() for i in range(num_gpus)}\n completed_tests = []\n failed_tests = []\n\n def start_test(test_info, gpu_id):\n \"\"\"Start a test on specified GPU\"\"\"\n test_path, run_func = test_info\n current_tests[gpu_id] = test_info\n process = run_func(test_path, log_dir, gpu_id)\n\n if process is None:\n failed_name = os.path.basename(test_path)\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n return False\n\n current_processes[gpu_id] = process\n start_times[gpu_id] = time.time()\n print(f\"Started {os.path.basename(test_path)} on GPU {gpu_id}\")\n return True\n\n def check_completion():\n \"\"\"Check if any running tests have completed and return list of free GPUs\"\"\"\n free_gpus = []\n for gpu_id in range(num_gpus):\n if current_processes[gpu_id] is None:\n free_gpus.append(gpu_id)\n continue\n\n # Get timeout for current test\n test_path, run_func = current_tests[gpu_id]\n test_name = os.path.basename(test_path)\n timeout = get_test_timeout(test_name)\n\n # Check for timeout\n if time.time() - start_times[gpu_id] > timeout:\n print(\n f\"Test {test_name} on GPU {gpu_id} timed out after {timeout / 60} minutes\"\n )\n current_processes[gpu_id].kill()\n log_file = log_dir / f\"{test_name}.log\"\n if run_func == run_python_test:\n log_file = log_dir / f\"python_{test_name}.log\"\n with open(log_file, \"a\") as f:\n f.write(f\"\\nERROR: Test timed out after {timeout / 60} minutes\\n\")\n\n failed_name = test_name\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n current_processes[gpu_id] = None\n current_tests[gpu_id] = None\n free_gpus.append(gpu_id)\n continue\n\n # Check if process completed\n if current_processes[gpu_id].poll() is not None:\n test_path, run_func = current_tests[gpu_id]\n test_name = os.path.basename(test_path)\n success = current_processes[gpu_id].returncode == 0\n print(\n f\"Completed {test_name} on GPU {gpu_id}: {'Success' if success else 'Failed'}\"\n )\n\n # Append completion status to log file\n log_file = log_dir / f\"{test_name}.log\"\n if run_func == run_python_test:\n log_file = log_dir / f\"python_{test_name}.log\"\n with open(log_file, \"a\") as f:\n f.write(\n f\"\\nTest completed with {'success' if success else 'failure'}\\n\"\n )\n f.write(f\"Return code: {current_processes[gpu_id].returncode}\\n\")\n\n if success:\n completed_tests.append(test_path)\n else:\n failed_name = test_name\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n\n current_processes[gpu_id] = None\n current_tests[gpu_id] = None\n free_gpus.append(gpu_id)\n\n return free_gpus\n\n # Initial test distribution\n for gpu_id in range(num_gpus):\n if test_queue and current_processes[gpu_id] is None:\n start_test(test_queue.pop(0), gpu_id)\n\n # Main loop\n try:\n while test_queue or any(p is not None for p in current_processes.values()):\n # Check for completed tests\n free_gpus = check_completion()\n\n # Start new tests on free GPUs\n for gpu_id in free_gpus:\n if test_queue: # If there are tests waiting to be run\n start_test(test_queue.pop(0), gpu_id)\n\n # Small sleep to prevent busy waiting\n time.sleep(1)\n\n return completed_tests, failed_tests\n\n finally:\n # Ensure all processes are cleaned up\n for process in current_processes.values():\n if process is not None:\n process.kill()\n\n\ndef collect_test_failures(log_dir, dry_run=False):\n \"\"\"Scan log files for test failures and collect context\"\"\"\n if dry_run:\n print(\n \"\\nWould scan log files for failures and create failure_summary.txt with:\"\n )\n print(\"- 5 lines of context before each failure\")\n print(\"- 20 lines of context after each failure\")\n print(\"- Coverage for both GTest and Pytest failures\")\n print(\"- Timeout failure information\")\n return False\n\n failure_summary = []\n\n for log_file in log_dir.glob(\"*.log\"):\n with open(log_file, \"r\") as f:\n lines = f.readlines()\n\n for i, line in enumerate(lines):\n # Look for GTest failures between square brackets\n if \"[\" in line and \"]\" in line:\n result_part = line[line.find(\"[\") : line.find(\"]\") + 1]\n if \"FAILED\" in result_part or \"TIMEOUT\" in result_part:\n failure_summary.append(\n f\"\\n=== GTest Failure in {log_file.name} ===\"\n )\n # Collect 5 lines before and 20 lines after the failure\n start = max(0, i - 5)\n end = min(len(lines), i + 21)\n failure_summary.extend(lines[start:end])\n continue # Skip other checks for this line if it was a bracketed result\n\n # Look for pytest failures\n if \"FAILED\" in line and \"test\" in line.lower():\n failure_summary.append(f\"\\n=== Pytest Failure in {log_file.name} ===\")\n # Collect 5 lines before and 20 lines after the failure\n start = max(0, i - 5)\n end = min(len(lines), i + 21)\n failure_summary.extend(lines[start:end])\n\n # Look for timeout failures\n if \"ERROR: Test timed out\" in line:\n failure_summary.append(f\"\\n=== Timeout in {log_file.name} ===\")\n failure_summary.append(line)\n\n # Write failure summary if there were any failures\n if failure_summary:\n with open(log_dir / \"failure_summary.txt\", \"w\") as f:\n f.write(\"=== Test Failure Summary ===\\n\")\n f.write(\"\".join(failure_summary))\n\n return True\n return False\n\n\ndef get_available_gpus():\n \"\"\"Check how many NVIDIA GPUs are available\"\"\"\n try:\n # Run nvidia-smi -L | wc -l to get GPU count\n output = subprocess.check_output(\"nvidia-smi -L | wc -l\", shell=True, text=True)\n return int(output.strip())\n except (subprocess.SubprocessError, ValueError):\n print(\"Warning: Could not query GPU count using nvidia-smi\")\n return 0\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Run nvFuser tests\")\n parser.add_argument(\n \"--dry-run\",\n action=\"store_true\",\n help=\"Show what tests would be run without executing them\",\n )\n args = parser.parse_args()\n\n # Check GPU availability\n gpu_count = get_available_gpus()\n if gpu_count < 1:\n print(\"Error: No GPUs found for testing\")\n return 1\n\n print(f\"Found {gpu_count} GPUs available for testing\")\n\n # Hardcode paths relative to current directory\n build_dir = \"bin\"\n python_test_dir = \"tests/python\"\n\n log_dir = setup_logging_dir()\n multidevice_tests, single_device_tests = get_cpp_test_executables(build_dir)\n # This is not catching all python multidevice tests like test_communication.py\n # TODO: Change test names to separate out multidevice tests, or update to support all multidevice python tests\n python_multidevice_tests, python_single_tests = get_python_tests(python_test_dir)\n\n if not (multidevice_tests or single_device_tests) and not (\n python_multidevice_tests or python_single_tests\n ):\n print(\"No tests found!\")\n return 0\n\n print(f\"Found {len(multidevice_tests)} C++ multidevice tests\")\n print(f\"Found {len(python_multidevice_tests)} Python multidevice tests\")\n print(f\"Found {len(single_device_tests)} C++ single device tests\")\n print(f\"Found {len(python_single_tests)} Python single device tests\")\n print(f\"Logs will be written to: {log_dir}\")\n\n success_count = 0\n failed_tests = []\n total_tests = (\n len(multidevice_tests)\n + len(single_device_tests)\n + len(python_multidevice_tests)\n + len(python_single_tests)\n )\n\n # Run all multidevice tests first\n print(\"\\nC++ multidevice tests:\")\n for test in multidevice_tests:\n if run_multidevice_test(test, log_dir, gpu_count, dry_run=args.dry_run):\n if not args.dry_run:\n success_count += 1\n else:\n if not args.dry_run:\n failed_tests.append(os.path.basename(test))\n\n print(\"\\nPython multidevice tests:\")\n for test in python_multidevice_tests:\n if run_python_multidevice_test(test, log_dir, gpu_count, dry_run=args.dry_run):\n if not args.dry_run:\n success_count += 1\n else:\n if not args.dry_run:\n failed_tests.append(f\"python_{os.path.basename(test)}\")\n\n # Run all single device tests (C++ and Python) in parallel\n print(\"\\nRunning all single device tests in parallel:\")\n\n # Create initial unordered test list\n test_infos = [(t, run_single_device_test) for t in single_device_tests] + [\n (t, run_python_test) for t in python_single_tests\n ]\n\n # Find and prioritize specific tests by name match in full path\n priority_names = [\"test_nvfuser\", \"test_matmul\", \"test_ops.py\"]\n priority_tests = []\n other_tests = []\n\n for test_info in test_infos:\n test_path, _ = test_info\n if any(name in test_path for name in priority_names):\n priority_tests.append(test_info)\n else:\n other_tests.append(test_info)\n\n test_infos = priority_tests + other_tests\n\n if not args.dry_run:\n completed, failed = run_parallel_tests(log_dir, gpu_count, test_infos)\n success_count += len(completed)\n failed_tests.extend(failed)\n else:\n run_parallel_tests(log_dir, gpu_count, test_infos, dry_run=True)\n\n if args.dry_run:\n # Show what would be written to summary.txt\n print(\"\\nWould create summary.txt with:\")\n print(f\"Total tests: {total_tests}\")\n print(f\"Multidevice tests: {len(multidevice_tests)}\")\n print(f\"Multidevice python tests: {len(python_multidevice_tests)}\")\n print(f\"C++ single device tests: {len(single_device_tests)}\")\n print(f\"Python single device tests: {len(python_single_tests)}\")\n\n # Show failure collection simulation\n collect_test_failures(log_dir, dry_run=True)\n\n print(\"\\nThis was a dry run. No tests were actually executed.\")\n return 0\n\n # Write summary\n with open(log_dir / \"summary.txt\", \"w\") as f:\n f.write(f\"Total tests: {total_tests}\\n\")\n f.write(f\"Multidevice tests: {len(multidevice_tests)}\\\n# ... truncated ...","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":true} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.setup_logging_dir","uri":"program://Fuser/function/tools.run_nvfuser_tests.setup_logging_dir#L13-L32","kind":"function","name":"setup_logging_dir","path":"tools/run_nvfuser_tests.py","language":"python","start_line":13,"end_line":32,"context_start_line":1,"context_end_line":52,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport subprocess\nimport os\nimport glob\nimport datetime\nfrom pathlib import Path\nimport time\nimport argparse\n\n\ndef setup_logging_dir():\n \"\"\"Create a timestamped directory for test logs and update latest symlink\"\"\"\n timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n log_dir = Path(f\"test_log_{timestamp}\")\n log_dir.mkdir(exist_ok=True)\n\n # Check and handle the 'latest' symlink\n latest_link = Path(\"test_log_latest\")\n if latest_link.exists():\n if not latest_link.is_symlink():\n raise RuntimeError(\n \"test_log_latest exists but is not a symlink. \"\n \"Please remove it manually to proceed.\"\n )\n latest_link.unlink() # Remove existing symlink\n\n # Create new symlink pointing to the new log directory\n latest_link.symlink_to(log_dir, target_is_directory=True)\n\n return log_dir\n\n\ndef get_cpp_test_executables(build_dir):\n \"\"\"Find all test executables in the build directory\"\"\"\n all_tests = glob.glob(os.path.join(build_dir, \"*test*\"))\n\n # Separate multidevice and single device tests\n multidevice_tests, single_device_tests = [], []\n for test in all_tests:\n (single_device_tests, multidevice_tests)[\n \"multidevice\" in os.path.basename(test).lower()\n ].append(test)\n\n return multidevice_tests, single_device_tests\n\n\ndef get_python_tests(python_test_dir):\n \"\"\"Find all Python test files\"\"\"\n all_tests = glob.glob(os.path.join(python_test_dir, \"test_*.py\"))\n","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.get_cpp_test_executables","uri":"program://Fuser/function/tools.run_nvfuser_tests.get_cpp_test_executables#L35-L46","kind":"function","name":"get_cpp_test_executables","path":"tools/run_nvfuser_tests.py","language":"python","start_line":35,"end_line":46,"context_start_line":15,"context_end_line":66,"code":" timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n log_dir = Path(f\"test_log_{timestamp}\")\n log_dir.mkdir(exist_ok=True)\n\n # Check and handle the 'latest' symlink\n latest_link = Path(\"test_log_latest\")\n if latest_link.exists():\n if not latest_link.is_symlink():\n raise RuntimeError(\n \"test_log_latest exists but is not a symlink. \"\n \"Please remove it manually to proceed.\"\n )\n latest_link.unlink() # Remove existing symlink\n\n # Create new symlink pointing to the new log directory\n latest_link.symlink_to(log_dir, target_is_directory=True)\n\n return log_dir\n\n\ndef get_cpp_test_executables(build_dir):\n \"\"\"Find all test executables in the build directory\"\"\"\n all_tests = glob.glob(os.path.join(build_dir, \"*test*\"))\n\n # Separate multidevice and single device tests\n multidevice_tests, single_device_tests = [], []\n for test in all_tests:\n (single_device_tests, multidevice_tests)[\n \"multidevice\" in os.path.basename(test).lower()\n ].append(test)\n\n return multidevice_tests, single_device_tests\n\n\ndef get_python_tests(python_test_dir):\n \"\"\"Find all Python test files\"\"\"\n all_tests = glob.glob(os.path.join(python_test_dir, \"test_*.py\"))\n\n # Separate multidevice and single device tests\n # This is not catching all python multidevice tests like test_communication.py\n # TODO: Change test names to separate out multidevice tests, or update to support all multidevice python tests\n multidevice_tests, single_device_tests = [], []\n for test in all_tests:\n (single_device_tests, multidevice_tests)[\n \"multidevice\" in os.path.basename(test).lower()\n ].append(test)\n\n return multidevice_tests, single_device_tests\n\n\ndef get_test_timeout(test_name):\n \"\"\"Return timeout in seconds for a given test\"\"\"","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.get_python_tests","uri":"program://Fuser/function/tools.run_nvfuser_tests.get_python_tests#L49-L62","kind":"function","name":"get_python_tests","path":"tools/run_nvfuser_tests.py","language":"python","start_line":49,"end_line":62,"context_start_line":29,"context_end_line":82,"code":" # Create new symlink pointing to the new log directory\n latest_link.symlink_to(log_dir, target_is_directory=True)\n\n return log_dir\n\n\ndef get_cpp_test_executables(build_dir):\n \"\"\"Find all test executables in the build directory\"\"\"\n all_tests = glob.glob(os.path.join(build_dir, \"*test*\"))\n\n # Separate multidevice and single device tests\n multidevice_tests, single_device_tests = [], []\n for test in all_tests:\n (single_device_tests, multidevice_tests)[\n \"multidevice\" in os.path.basename(test).lower()\n ].append(test)\n\n return multidevice_tests, single_device_tests\n\n\ndef get_python_tests(python_test_dir):\n \"\"\"Find all Python test files\"\"\"\n all_tests = glob.glob(os.path.join(python_test_dir, \"test_*.py\"))\n\n # Separate multidevice and single device tests\n # This is not catching all python multidevice tests like test_communication.py\n # TODO: Change test names to separate out multidevice tests, or update to support all multidevice python tests\n multidevice_tests, single_device_tests = [], []\n for test in all_tests:\n (single_device_tests, multidevice_tests)[\n \"multidevice\" in os.path.basename(test).lower()\n ].append(test)\n\n return multidevice_tests, single_device_tests\n\n\ndef get_test_timeout(test_name):\n \"\"\"Return timeout in seconds for a given test\"\"\"\n if test_name in [\"test_nvfuser\", \"test_matmul\", \"test_direct_ops.py\"]:\n return 3600 # 1 hour\n return 600 # 10 minutes\n\n\ndef run_multidevice_test(test_path, log_dir, num_gpus, dry_run=False):\n \"\"\"Run a multidevice test using mpirun\"\"\"\n test_name = os.path.basename(test_path)\n log_base = log_dir / test_name\n timeout = get_test_timeout(test_name)\n\n cmd = [\n \"mpirun\",\n \"-np\",\n str(num_gpus), # Use available GPU count\n \"--output-filename\",","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.get_test_timeout","uri":"program://Fuser/function/tools.run_nvfuser_tests.get_test_timeout#L65-L69","kind":"function","name":"get_test_timeout","path":"tools/run_nvfuser_tests.py","language":"python","start_line":65,"end_line":69,"context_start_line":45,"context_end_line":89,"code":"\n return multidevice_tests, single_device_tests\n\n\ndef get_python_tests(python_test_dir):\n \"\"\"Find all Python test files\"\"\"\n all_tests = glob.glob(os.path.join(python_test_dir, \"test_*.py\"))\n\n # Separate multidevice and single device tests\n # This is not catching all python multidevice tests like test_communication.py\n # TODO: Change test names to separate out multidevice tests, or update to support all multidevice python tests\n multidevice_tests, single_device_tests = [], []\n for test in all_tests:\n (single_device_tests, multidevice_tests)[\n \"multidevice\" in os.path.basename(test).lower()\n ].append(test)\n\n return multidevice_tests, single_device_tests\n\n\ndef get_test_timeout(test_name):\n \"\"\"Return timeout in seconds for a given test\"\"\"\n if test_name in [\"test_nvfuser\", \"test_matmul\", \"test_direct_ops.py\"]:\n return 3600 # 1 hour\n return 600 # 10 minutes\n\n\ndef run_multidevice_test(test_path, log_dir, num_gpus, dry_run=False):\n \"\"\"Run a multidevice test using mpirun\"\"\"\n test_name = os.path.basename(test_path)\n log_base = log_dir / test_name\n timeout = get_test_timeout(test_name)\n\n cmd = [\n \"mpirun\",\n \"-np\",\n str(num_gpus), # Use available GPU count\n \"--output-filename\",\n f\"{log_base}\",\n \"--merge-stderr-to-stdout\",\n test_path,\n ]\n\n if dry_run:\n print(f\"Would run: {' '.join(cmd)} (timeout: {timeout / 60} minutes)\")","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.run_multidevice_test","uri":"program://Fuser/function/tools.run_nvfuser_tests.run_multidevice_test#L72-L109","kind":"function","name":"run_multidevice_test","path":"tools/run_nvfuser_tests.py","language":"python","start_line":72,"end_line":109,"context_start_line":52,"context_end_line":129,"code":"\n # Separate multidevice and single device tests\n # This is not catching all python multidevice tests like test_communication.py\n # TODO: Change test names to separate out multidevice tests, or update to support all multidevice python tests\n multidevice_tests, single_device_tests = [], []\n for test in all_tests:\n (single_device_tests, multidevice_tests)[\n \"multidevice\" in os.path.basename(test).lower()\n ].append(test)\n\n return multidevice_tests, single_device_tests\n\n\ndef get_test_timeout(test_name):\n \"\"\"Return timeout in seconds for a given test\"\"\"\n if test_name in [\"test_nvfuser\", \"test_matmul\", \"test_direct_ops.py\"]:\n return 3600 # 1 hour\n return 600 # 10 minutes\n\n\ndef run_multidevice_test(test_path, log_dir, num_gpus, dry_run=False):\n \"\"\"Run a multidevice test using mpirun\"\"\"\n test_name = os.path.basename(test_path)\n log_base = log_dir / test_name\n timeout = get_test_timeout(test_name)\n\n cmd = [\n \"mpirun\",\n \"-np\",\n str(num_gpus), # Use available GPU count\n \"--output-filename\",\n f\"{log_base}\",\n \"--merge-stderr-to-stdout\",\n test_path,\n ]\n\n if dry_run:\n print(f\"Would run: {' '.join(cmd)} (timeout: {timeout / 60} minutes)\")\n return True\n\n print(f\"Running multidevice test: {test_name}\")\n try:\n # Redirect output to /dev/null to suppress console output\n with open(os.devnull, \"w\") as devnull:\n result = subprocess.run(\n cmd, timeout=timeout, stdout=devnull, stderr=subprocess.STDOUT\n )\n return result.returncode == 0\n except subprocess.TimeoutExpired:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(f\"ERROR: Test timed out after {timeout / 60} minutes\\n\")\n return False\n except Exception as e:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(f\"ERROR: Failed to run test: {str(e)}\\n\")\n return False\n\n\ndef run_single_device_test(test_path, log_dir, gpu_id, dry_run=False):\n \"\"\"Run a single device test on specified GPU\"\"\"\n test_name = os.path.basename(test_path)\n log_file = log_dir / f\"{test_name}.log\"\n\n cmd = [test_path]\n env = os.environ.copy()\n env[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n\n if dry_run:\n print(f\"Would run: CUDA_VISIBLE_DEVICES={gpu_id} {' '.join(cmd)} > {log_file}\")\n return \"dry_run_process\"\n\n print(f\"Running test: {test_name} on GPU {gpu_id}\")\n try:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n process = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env)","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.run_single_device_test","uri":"program://Fuser/function/tools.run_nvfuser_tests.run_single_device_test#L112-L135","kind":"function","name":"run_single_device_test","path":"tools/run_nvfuser_tests.py","language":"python","start_line":112,"end_line":135,"context_start_line":92,"context_end_line":155,"code":" print(f\"Running multidevice test: {test_name}\")\n try:\n # Redirect output to /dev/null to suppress console output\n with open(os.devnull, \"w\") as devnull:\n result = subprocess.run(\n cmd, timeout=timeout, stdout=devnull, stderr=subprocess.STDOUT\n )\n return result.returncode == 0\n except subprocess.TimeoutExpired:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(f\"ERROR: Test timed out after {timeout / 60} minutes\\n\")\n return False\n except Exception as e:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(f\"ERROR: Failed to run test: {str(e)}\\n\")\n return False\n\n\ndef run_single_device_test(test_path, log_dir, gpu_id, dry_run=False):\n \"\"\"Run a single device test on specified GPU\"\"\"\n test_name = os.path.basename(test_path)\n log_file = log_dir / f\"{test_name}.log\"\n\n cmd = [test_path]\n env = os.environ.copy()\n env[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n\n if dry_run:\n print(f\"Would run: CUDA_VISIBLE_DEVICES={gpu_id} {' '.join(cmd)} > {log_file}\")\n return \"dry_run_process\"\n\n print(f\"Running test: {test_name} on GPU {gpu_id}\")\n try:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n process = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env)\n return process\n except Exception as e:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n f.write(f\"ERROR: Failed to start test: {str(e)}\\n\")\n return None\n\n\ndef run_python_multidevice_test(test_path, log_dir, num_gpus, dry_run=False):\n \"\"\"Run a Python multidevice test using mpirun\"\"\"\n test_name = os.path.basename(test_path)\n log_base = log_dir / f\"python_{test_name}\"\n\n cmd = [\n \"mpirun\",\n \"-np\",\n str(num_gpus), # Use available GPU count\n \"--output-filename\",\n f\"{log_base}\",\n \"--merge-stderr-to-stdout\",\n \"pytest\",\n test_path,\n \"-v\",\n ]\n\n if dry_run:","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.run_python_multidevice_test","uri":"program://Fuser/function/tools.run_nvfuser_tests.run_python_multidevice_test#L138-L176","kind":"function","name":"run_python_multidevice_test","path":"tools/run_nvfuser_tests.py","language":"python","start_line":138,"end_line":176,"context_start_line":118,"context_end_line":196,"code":" env = os.environ.copy()\n env[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n\n if dry_run:\n print(f\"Would run: CUDA_VISIBLE_DEVICES={gpu_id} {' '.join(cmd)} > {log_file}\")\n return \"dry_run_process\"\n\n print(f\"Running test: {test_name} on GPU {gpu_id}\")\n try:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n process = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env)\n return process\n except Exception as e:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n f.write(f\"ERROR: Failed to start test: {str(e)}\\n\")\n return None\n\n\ndef run_python_multidevice_test(test_path, log_dir, num_gpus, dry_run=False):\n \"\"\"Run a Python multidevice test using mpirun\"\"\"\n test_name = os.path.basename(test_path)\n log_base = log_dir / f\"python_{test_name}\"\n\n cmd = [\n \"mpirun\",\n \"-np\",\n str(num_gpus), # Use available GPU count\n \"--output-filename\",\n f\"{log_base}\",\n \"--merge-stderr-to-stdout\",\n \"pytest\",\n test_path,\n \"-v\",\n ]\n\n if dry_run:\n print(f\"Would run: {' '.join(cmd)}\")\n return True\n\n print(f\"Running Python multidevice test: {test_name}\")\n try:\n # Redirect output to /dev/null to suppress console output\n with open(os.devnull, \"w\") as devnull:\n result = subprocess.run(\n cmd, timeout=1200, stdout=devnull, stderr=subprocess.STDOUT\n )\n return result.returncode == 0\n except subprocess.TimeoutExpired:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(\"ERROR: Test timed out after 20 minutes\\n\")\n return False\n except Exception as e:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(f\"ERROR: Failed to run test: {str(e)}\\n\")\n return False\n\n\ndef run_python_test(test_path, log_dir, gpu_id, dry_run=False):\n \"\"\"Run a Python test using pytest on specified GPU\"\"\"\n test_name = os.path.basename(test_path)\n log_file = log_dir / f\"python_{test_name}.log\"\n\n cmd = [\"pytest\", test_path, \"-v\"]\n env = os.environ.copy()\n env[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n\n if dry_run:\n print(f\"Would run: CUDA_VISIBLE_DEVICES={gpu_id} {' '.join(cmd)} > {log_file}\")\n return \"dry_run_process\"\n\n print(f\"Running Python test: {test_name} on GPU {gpu_id}\")\n try:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n process = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env)","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.run_python_test","uri":"program://Fuser/function/tools.run_nvfuser_tests.run_python_test#L179-L202","kind":"function","name":"run_python_test","path":"tools/run_nvfuser_tests.py","language":"python","start_line":179,"end_line":202,"context_start_line":159,"context_end_line":222,"code":" print(f\"Running Python multidevice test: {test_name}\")\n try:\n # Redirect output to /dev/null to suppress console output\n with open(os.devnull, \"w\") as devnull:\n result = subprocess.run(\n cmd, timeout=1200, stdout=devnull, stderr=subprocess.STDOUT\n )\n return result.returncode == 0\n except subprocess.TimeoutExpired:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(\"ERROR: Test timed out after 20 minutes\\n\")\n return False\n except Exception as e:\n with open(f\"{log_base}.log\", \"w\") as f:\n f.write(f\"Test: {test_name}\\n\")\n f.write(f\"ERROR: Failed to run test: {str(e)}\\n\")\n return False\n\n\ndef run_python_test(test_path, log_dir, gpu_id, dry_run=False):\n \"\"\"Run a Python test using pytest on specified GPU\"\"\"\n test_name = os.path.basename(test_path)\n log_file = log_dir / f\"python_{test_name}.log\"\n\n cmd = [\"pytest\", test_path, \"-v\"]\n env = os.environ.copy()\n env[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n\n if dry_run:\n print(f\"Would run: CUDA_VISIBLE_DEVICES={gpu_id} {' '.join(cmd)} > {log_file}\")\n return \"dry_run_process\"\n\n print(f\"Running Python test: {test_name} on GPU {gpu_id}\")\n try:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n process = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env)\n return process\n except Exception as e:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n f.write(f\"ERROR: Failed to start test: {str(e)}\\n\")\n return None\n\n\ndef run_parallel_tests(log_dir, num_gpus, test_infos, dry_run=False):\n \"\"\"Run tests in parallel across available GPUs using provided test configurations\"\"\"\n if dry_run:\n current_tests = {i: None for i in range(num_gpus)} # Simulate GPU allocation\n test_queue = test_infos.copy()\n\n print(f\"\\nSimulating parallel execution across {num_gpus} GPUs:\")\n\n # Initial allocation\n for gpu_id in range(num_gpus):\n if test_queue:\n test_path, run_func = test_queue.pop(0)\n current_tests[gpu_id] = (test_path, run_func)\n run_func(test_path, log_dir, gpu_id, dry_run=True)\n\n # Simulate rest of queue\n while test_queue:\n # Simulate round-robin GPU completion","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.run_parallel_tests","uri":"program://Fuser/function/tools.run_nvfuser_tests.run_parallel_tests#L205-L356","kind":"function","name":"run_parallel_tests","path":"tools/run_nvfuser_tests.py","language":"python","start_line":205,"end_line":356,"context_start_line":185,"context_end_line":376,"code":" env = os.environ.copy()\n env[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n\n if dry_run:\n print(f\"Would run: CUDA_VISIBLE_DEVICES={gpu_id} {' '.join(cmd)} > {log_file}\")\n return \"dry_run_process\"\n\n print(f\"Running Python test: {test_name} on GPU {gpu_id}\")\n try:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n process = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env)\n return process\n except Exception as e:\n with open(log_file, \"w\") as f:\n f.write(f\"Test: {test_name} on GPU {gpu_id}\\n\")\n f.write(f\"ERROR: Failed to start test: {str(e)}\\n\")\n return None\n\n\ndef run_parallel_tests(log_dir, num_gpus, test_infos, dry_run=False):\n \"\"\"Run tests in parallel across available GPUs using provided test configurations\"\"\"\n if dry_run:\n current_tests = {i: None for i in range(num_gpus)} # Simulate GPU allocation\n test_queue = test_infos.copy()\n\n print(f\"\\nSimulating parallel execution across {num_gpus} GPUs:\")\n\n # Initial allocation\n for gpu_id in range(num_gpus):\n if test_queue:\n test_path, run_func = test_queue.pop(0)\n current_tests[gpu_id] = (test_path, run_func)\n run_func(test_path, log_dir, gpu_id, dry_run=True)\n\n # Simulate rest of queue\n while test_queue:\n # Simulate round-robin GPU completion\n gpu_id = len(test_queue) % num_gpus\n current_test_path, _ = current_tests[gpu_id]\n print(f\"\\nGPU {gpu_id} finished {os.path.basename(current_test_path)}\")\n test_path, run_func = test_queue.pop(0)\n current_tests[gpu_id] = (test_path, run_func)\n run_func(test_path, log_dir, gpu_id, dry_run=True)\n\n # Show final tests completing\n for gpu_id in range(num_gpus):\n if current_tests[gpu_id]:\n test_path, _ = current_tests[gpu_id]\n print(f\"\\nGPU {gpu_id} finished {os.path.basename(test_path)}\")\n\n return [], []\n\n # Initialize test queue and tracking variables\n test_queue = test_infos.copy()\n current_processes = {i: None for i in range(num_gpus)}\n current_tests = {i: None for i in range(num_gpus)}\n start_times = {i: time.time() for i in range(num_gpus)}\n completed_tests = []\n failed_tests = []\n\n def start_test(test_info, gpu_id):\n \"\"\"Start a test on specified GPU\"\"\"\n test_path, run_func = test_info\n current_tests[gpu_id] = test_info\n process = run_func(test_path, log_dir, gpu_id)\n\n if process is None:\n failed_name = os.path.basename(test_path)\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n return False\n\n current_processes[gpu_id] = process\n start_times[gpu_id] = time.time()\n print(f\"Started {os.path.basename(test_path)} on GPU {gpu_id}\")\n return True\n\n def check_completion():\n \"\"\"Check if any running tests have completed and return list of free GPUs\"\"\"\n free_gpus = []\n for gpu_id in range(num_gpus):\n if current_processes[gpu_id] is None:\n free_gpus.append(gpu_id)\n continue\n\n # Get timeout for current test\n test_path, run_func = current_tests[gpu_id]\n test_name = os.path.basename(test_path)\n timeout = get_test_timeout(test_name)\n\n # Check for timeout\n if time.time() - start_times[gpu_id] > timeout:\n print(\n f\"Test {test_name} on GPU {gpu_id} timed out after {timeout / 60} minutes\"\n )\n current_processes[gpu_id].kill()\n log_file = log_dir / f\"{test_name}.log\"\n if run_func == run_python_test:\n log_file = log_dir / f\"python_{test_name}.log\"\n with open(log_file, \"a\") as f:\n f.write(f\"\\nERROR: Test timed out after {timeout / 60} minutes\\n\")\n\n failed_name = test_name\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n current_processes[gpu_id] = None\n current_tests[gpu_id] = None\n free_gpus.append(gpu_id)\n continue\n\n # Check if process completed\n if current_processes[gpu_id].poll() is not None:\n test_path, run_func = current_tests[gpu_id]\n test_name = os.path.basename(test_path)\n success = current_processes[gpu_id].returncode == 0\n print(\n f\"Completed {test_name} on GPU {gpu_id}: {'Success' if success else 'Failed'}\"\n )\n\n # Append completion status to log file\n log_file = log_dir / f\"{test_name}.log\"\n if run_func == run_python_test:\n log_file = log_dir / f\"python_{test_name}.log\"\n with open(log_file, \"a\") as f:\n f.write(\n f\"\\nTest completed with {'success' if success else 'failure'}\\n\"\n )\n f.write(f\"Return code: {current_processes[gpu_id].returncode}\\n\")\n\n if success:\n completed_tests.append(test_path)\n else:\n failed_name = test_name\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n\n current_processes[gpu_id] = None\n current_tests[gpu_id] = None\n free_gpus.append(gpu_id)\n\n return free_gpus\n\n # Initial test distribution\n for gpu_id in range(num_gpus):\n if test_queue and current_processes[gpu_id] is None:\n start_test(test_queue.pop(0), gpu_id)\n\n # Main loop\n try:\n while test_queue or any(p is not None for p in current_processes.values()):\n # Check for completed tests\n free_gpus = check_completion()\n\n # Start new tests on free GPUs\n for gpu_id in free_gpus:\n if test_queue: # If there are tests waiting to be run\n start_test(test_queue.pop(0), gpu_id)\n\n # Small sleep to prevent busy waiting\n time.sleep(1)\n\n return completed_tests, failed_tests\n\n finally:\n # Ensure all processes are cleaned up\n for process in current_processes.values():\n if process is not None:\n process.kill()\n\n\ndef collect_test_failures(log_dir, dry_run=False):\n \"\"\"Scan log files for test failures and collect context\"\"\"\n if dry_run:\n print(\n \"\\nWould scan log files for failures and create failure_summary.txt with:\"\n )\n print(\"- 5 lines of context before each failure\")\n print(\"- 20 lines of context after each failure\")\n print(\"- Coverage for both GTest and Pytest failures\")\n print(\"- Timeout failure information\")\n return False\n\n failure_summary = []\n\n for log_file in log_dir.glob(\"*.log\"):\n with open(log_file, \"r\") as f:\n lines = f.readlines()\n","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.collect_test_failures","uri":"program://Fuser/function/tools.run_nvfuser_tests.collect_test_failures#L359-L411","kind":"function","name":"collect_test_failures","path":"tools/run_nvfuser_tests.py","language":"python","start_line":359,"end_line":411,"context_start_line":339,"context_end_line":431,"code":" # Check for completed tests\n free_gpus = check_completion()\n\n # Start new tests on free GPUs\n for gpu_id in free_gpus:\n if test_queue: # If there are tests waiting to be run\n start_test(test_queue.pop(0), gpu_id)\n\n # Small sleep to prevent busy waiting\n time.sleep(1)\n\n return completed_tests, failed_tests\n\n finally:\n # Ensure all processes are cleaned up\n for process in current_processes.values():\n if process is not None:\n process.kill()\n\n\ndef collect_test_failures(log_dir, dry_run=False):\n \"\"\"Scan log files for test failures and collect context\"\"\"\n if dry_run:\n print(\n \"\\nWould scan log files for failures and create failure_summary.txt with:\"\n )\n print(\"- 5 lines of context before each failure\")\n print(\"- 20 lines of context after each failure\")\n print(\"- Coverage for both GTest and Pytest failures\")\n print(\"- Timeout failure information\")\n return False\n\n failure_summary = []\n\n for log_file in log_dir.glob(\"*.log\"):\n with open(log_file, \"r\") as f:\n lines = f.readlines()\n\n for i, line in enumerate(lines):\n # Look for GTest failures between square brackets\n if \"[\" in line and \"]\" in line:\n result_part = line[line.find(\"[\") : line.find(\"]\") + 1]\n if \"FAILED\" in result_part or \"TIMEOUT\" in result_part:\n failure_summary.append(\n f\"\\n=== GTest Failure in {log_file.name} ===\"\n )\n # Collect 5 lines before and 20 lines after the failure\n start = max(0, i - 5)\n end = min(len(lines), i + 21)\n failure_summary.extend(lines[start:end])\n continue # Skip other checks for this line if it was a bracketed result\n\n # Look for pytest failures\n if \"FAILED\" in line and \"test\" in line.lower():\n failure_summary.append(f\"\\n=== Pytest Failure in {log_file.name} ===\")\n # Collect 5 lines before and 20 lines after the failure\n start = max(0, i - 5)\n end = min(len(lines), i + 21)\n failure_summary.extend(lines[start:end])\n\n # Look for timeout failures\n if \"ERROR: Test timed out\" in line:\n failure_summary.append(f\"\\n=== Timeout in {log_file.name} ===\")\n failure_summary.append(line)\n\n # Write failure summary if there were any failures\n if failure_summary:\n with open(log_dir / \"failure_summary.txt\", \"w\") as f:\n f.write(\"=== Test Failure Summary ===\\n\")\n f.write(\"\".join(failure_summary))\n\n return True\n return False\n\n\ndef get_available_gpus():\n \"\"\"Check how many NVIDIA GPUs are available\"\"\"\n try:\n # Run nvidia-smi -L | wc -l to get GPU count\n output = subprocess.check_output(\"nvidia-smi -L | wc -l\", shell=True, text=True)\n return int(output.strip())\n except (subprocess.SubprocessError, ValueError):\n print(\"Warning: Could not query GPU count using nvidia-smi\")\n return 0\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Run nvFuser tests\")\n parser.add_argument(\n \"--dry-run\",\n action=\"store_true\",\n help=\"Show what tests would be run without executing them\",\n )","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.get_available_gpus","uri":"program://Fuser/function/tools.run_nvfuser_tests.get_available_gpus#L414-L422","kind":"function","name":"get_available_gpus","path":"tools/run_nvfuser_tests.py","language":"python","start_line":414,"end_line":422,"context_start_line":394,"context_end_line":442,"code":" # Collect 5 lines before and 20 lines after the failure\n start = max(0, i - 5)\n end = min(len(lines), i + 21)\n failure_summary.extend(lines[start:end])\n\n # Look for timeout failures\n if \"ERROR: Test timed out\" in line:\n failure_summary.append(f\"\\n=== Timeout in {log_file.name} ===\")\n failure_summary.append(line)\n\n # Write failure summary if there were any failures\n if failure_summary:\n with open(log_dir / \"failure_summary.txt\", \"w\") as f:\n f.write(\"=== Test Failure Summary ===\\n\")\n f.write(\"\".join(failure_summary))\n\n return True\n return False\n\n\ndef get_available_gpus():\n \"\"\"Check how many NVIDIA GPUs are available\"\"\"\n try:\n # Run nvidia-smi -L | wc -l to get GPU count\n output = subprocess.check_output(\"nvidia-smi -L | wc -l\", shell=True, text=True)\n return int(output.strip())\n except (subprocess.SubprocessError, ValueError):\n print(\"Warning: Could not query GPU count using nvidia-smi\")\n return 0\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Run nvFuser tests\")\n parser.add_argument(\n \"--dry-run\",\n action=\"store_true\",\n help=\"Show what tests would be run without executing them\",\n )\n args = parser.parse_args()\n\n # Check GPU availability\n gpu_count = get_available_gpus()\n if gpu_count < 1:\n print(\"Error: No GPUs found for testing\")\n return 1\n\n print(f\"Found {gpu_count} GPUs available for testing\")\n\n # Hardcode paths relative to current directory","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.main","uri":"program://Fuser/function/tools.run_nvfuser_tests.main#L425-L563","kind":"function","name":"main","path":"tools/run_nvfuser_tests.py","language":"python","start_line":425,"end_line":563,"context_start_line":405,"context_end_line":567,"code":" if failure_summary:\n with open(log_dir / \"failure_summary.txt\", \"w\") as f:\n f.write(\"=== Test Failure Summary ===\\n\")\n f.write(\"\".join(failure_summary))\n\n return True\n return False\n\n\ndef get_available_gpus():\n \"\"\"Check how many NVIDIA GPUs are available\"\"\"\n try:\n # Run nvidia-smi -L | wc -l to get GPU count\n output = subprocess.check_output(\"nvidia-smi -L | wc -l\", shell=True, text=True)\n return int(output.strip())\n except (subprocess.SubprocessError, ValueError):\n print(\"Warning: Could not query GPU count using nvidia-smi\")\n return 0\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Run nvFuser tests\")\n parser.add_argument(\n \"--dry-run\",\n action=\"store_true\",\n help=\"Show what tests would be run without executing them\",\n )\n args = parser.parse_args()\n\n # Check GPU availability\n gpu_count = get_available_gpus()\n if gpu_count < 1:\n print(\"Error: No GPUs found for testing\")\n return 1\n\n print(f\"Found {gpu_count} GPUs available for testing\")\n\n # Hardcode paths relative to current directory\n build_dir = \"bin\"\n python_test_dir = \"tests/python\"\n\n log_dir = setup_logging_dir()\n multidevice_tests, single_device_tests = get_cpp_test_executables(build_dir)\n # This is not catching all python multidevice tests like test_communication.py\n # TODO: Change test names to separate out multidevice tests, or update to support all multidevice python tests\n python_multidevice_tests, python_single_tests = get_python_tests(python_test_dir)\n\n if not (multidevice_tests or single_device_tests) and not (\n python_multidevice_tests or python_single_tests\n ):\n print(\"No tests found!\")\n return 0\n\n print(f\"Found {len(multidevice_tests)} C++ multidevice tests\")\n print(f\"Found {len(python_multidevice_tests)} Python multidevice tests\")\n print(f\"Found {len(single_device_tests)} C++ single device tests\")\n print(f\"Found {len(python_single_tests)} Python single device tests\")\n print(f\"Logs will be written to: {log_dir}\")\n\n success_count = 0\n failed_tests = []\n total_tests = (\n len(multidevice_tests)\n + len(single_device_tests)\n + len(python_multidevice_tests)\n + len(python_single_tests)\n )\n\n # Run all multidevice tests first\n print(\"\\nC++ multidevice tests:\")\n for test in multidevice_tests:\n if run_multidevice_test(test, log_dir, gpu_count, dry_run=args.dry_run):\n if not args.dry_run:\n success_count += 1\n else:\n if not args.dry_run:\n failed_tests.append(os.path.basename(test))\n\n print(\"\\nPython multidevice tests:\")\n for test in python_multidevice_tests:\n if run_python_multidevice_test(test, log_dir, gpu_count, dry_run=args.dry_run):\n if not args.dry_run:\n success_count += 1\n else:\n if not args.dry_run:\n failed_tests.append(f\"python_{os.path.basename(test)}\")\n\n # Run all single device tests (C++ and Python) in parallel\n print(\"\\nRunning all single device tests in parallel:\")\n\n # Create initial unordered test list\n test_infos = [(t, run_single_device_test) for t in single_device_tests] + [\n (t, run_python_test) for t in python_single_tests\n ]\n\n # Find and prioritize specific tests by name match in full path\n priority_names = [\"test_nvfuser\", \"test_matmul\", \"test_ops.py\"]\n priority_tests = []\n other_tests = []\n\n for test_info in test_infos:\n test_path, _ = test_info\n if any(name in test_path for name in priority_names):\n priority_tests.append(test_info)\n else:\n other_tests.append(test_info)\n\n test_infos = priority_tests + other_tests\n\n if not args.dry_run:\n completed, failed = run_parallel_tests(log_dir, gpu_count, test_infos)\n success_count += len(completed)\n failed_tests.extend(failed)\n else:\n run_parallel_tests(log_dir, gpu_count, test_infos, dry_run=True)\n\n if args.dry_run:\n # Show what would be written to summary.txt\n print(\"\\nWould create summary.txt with:\")\n print(f\"Total tests: {total_tests}\")\n print(f\"Multidevice tests: {len(multidevice_tests)}\")\n print(f\"Multidevice python tests: {len(python_multidevice_tests)}\")\n print(f\"C++ single device tests: {len(single_device_tests)}\")\n print(f\"Python single device tests: {len(python_single_tests)}\")\n\n # Show failure collection simulation\n collect_test_failures(log_dir, dry_run=True)\n\n print(\"\\nThis was a dry run. No tests were actually executed.\")\n return 0\n\n # Write summary\n with open(log_dir / \"summary.txt\", \"w\") as f:\n f.write(f\"Total tests: {total_tests}\\n\")\n f.write(f\"Multidevice tests: {len(multidevice_tests)}\\n\")\n f.write(f\"Single device tests: {len(single_device_tests)}\\n\")\n f.write(f\"Python tests: {len(python_multidevice_tests)}\\n\")\n f.write(f\"Successful: {success_count}\\n\")\n f.write(f\"Failed: {len(failed_tests)}\\n\")\n if failed_tests:\n f.write(\"\\nFailed tests:\\n\")\n for test in failed_tests:\n f.write(f\"- {test}\\n\")\n\n # Collect and summarize failures\n if failed_tests:\n if collect_test_failures(log_dir):\n print(\n f\"Detailed failure information available in: {log_dir}/failure_summary.txt\"\n )\n\n print(f\"\\nTest run complete. {success_count}/{total_tests} tests passed.\")\n if failed_tests:\n print(\"Failed tests:\")\n for test in failed_tests:\n print(f\"- {test}\")\n print(f\"Logs available in: {log_dir}\")\n\n return 0 if not failed_tests else 1\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.start_test","uri":"program://Fuser/function/tools.run_nvfuser_tests.start_test#L246-L262","kind":"function","name":"start_test","path":"tools/run_nvfuser_tests.py","language":"python","start_line":246,"end_line":262,"context_start_line":226,"context_end_line":282,"code":" test_path, run_func = test_queue.pop(0)\n current_tests[gpu_id] = (test_path, run_func)\n run_func(test_path, log_dir, gpu_id, dry_run=True)\n\n # Show final tests completing\n for gpu_id in range(num_gpus):\n if current_tests[gpu_id]:\n test_path, _ = current_tests[gpu_id]\n print(f\"\\nGPU {gpu_id} finished {os.path.basename(test_path)}\")\n\n return [], []\n\n # Initialize test queue and tracking variables\n test_queue = test_infos.copy()\n current_processes = {i: None for i in range(num_gpus)}\n current_tests = {i: None for i in range(num_gpus)}\n start_times = {i: time.time() for i in range(num_gpus)}\n completed_tests = []\n failed_tests = []\n\n def start_test(test_info, gpu_id):\n \"\"\"Start a test on specified GPU\"\"\"\n test_path, run_func = test_info\n current_tests[gpu_id] = test_info\n process = run_func(test_path, log_dir, gpu_id)\n\n if process is None:\n failed_name = os.path.basename(test_path)\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n return False\n\n current_processes[gpu_id] = process\n start_times[gpu_id] = time.time()\n print(f\"Started {os.path.basename(test_path)} on GPU {gpu_id}\")\n return True\n\n def check_completion():\n \"\"\"Check if any running tests have completed and return list of free GPUs\"\"\"\n free_gpus = []\n for gpu_id in range(num_gpus):\n if current_processes[gpu_id] is None:\n free_gpus.append(gpu_id)\n continue\n\n # Get timeout for current test\n test_path, run_func = current_tests[gpu_id]\n test_name = os.path.basename(test_path)\n timeout = get_test_timeout(test_name)\n\n # Check for timeout\n if time.time() - start_times[gpu_id] > timeout:\n print(\n f\"Test {test_name} on GPU {gpu_id} timed out after {timeout / 60} minutes\"\n )\n current_processes[gpu_id].kill()","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.run_nvfuser_tests.check_completion","uri":"program://Fuser/function/tools.run_nvfuser_tests.check_completion#L264-L329","kind":"function","name":"check_completion","path":"tools/run_nvfuser_tests.py","language":"python","start_line":264,"end_line":329,"context_start_line":244,"context_end_line":349,"code":" failed_tests = []\n\n def start_test(test_info, gpu_id):\n \"\"\"Start a test on specified GPU\"\"\"\n test_path, run_func = test_info\n current_tests[gpu_id] = test_info\n process = run_func(test_path, log_dir, gpu_id)\n\n if process is None:\n failed_name = os.path.basename(test_path)\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n return False\n\n current_processes[gpu_id] = process\n start_times[gpu_id] = time.time()\n print(f\"Started {os.path.basename(test_path)} on GPU {gpu_id}\")\n return True\n\n def check_completion():\n \"\"\"Check if any running tests have completed and return list of free GPUs\"\"\"\n free_gpus = []\n for gpu_id in range(num_gpus):\n if current_processes[gpu_id] is None:\n free_gpus.append(gpu_id)\n continue\n\n # Get timeout for current test\n test_path, run_func = current_tests[gpu_id]\n test_name = os.path.basename(test_path)\n timeout = get_test_timeout(test_name)\n\n # Check for timeout\n if time.time() - start_times[gpu_id] > timeout:\n print(\n f\"Test {test_name} on GPU {gpu_id} timed out after {timeout / 60} minutes\"\n )\n current_processes[gpu_id].kill()\n log_file = log_dir / f\"{test_name}.log\"\n if run_func == run_python_test:\n log_file = log_dir / f\"python_{test_name}.log\"\n with open(log_file, \"a\") as f:\n f.write(f\"\\nERROR: Test timed out after {timeout / 60} minutes\\n\")\n\n failed_name = test_name\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n current_processes[gpu_id] = None\n current_tests[gpu_id] = None\n free_gpus.append(gpu_id)\n continue\n\n # Check if process completed\n if current_processes[gpu_id].poll() is not None:\n test_path, run_func = current_tests[gpu_id]\n test_name = os.path.basename(test_path)\n success = current_processes[gpu_id].returncode == 0\n print(\n f\"Completed {test_name} on GPU {gpu_id}: {'Success' if success else 'Failed'}\"\n )\n\n # Append completion status to log file\n log_file = log_dir / f\"{test_name}.log\"\n if run_func == run_python_test:\n log_file = log_dir / f\"python_{test_name}.log\"\n with open(log_file, \"a\") as f:\n f.write(\n f\"\\nTest completed with {'success' if success else 'failure'}\\n\"\n )\n f.write(f\"Return code: {current_processes[gpu_id].returncode}\\n\")\n\n if success:\n completed_tests.append(test_path)\n else:\n failed_name = test_name\n if run_func == run_python_test:\n failed_name = f\"python_{failed_name}\"\n failed_tests.append(failed_name)\n\n current_processes[gpu_id] = None\n current_tests[gpu_id] = None\n free_gpus.append(gpu_id)\n\n return free_gpus\n\n # Initial test distribution\n for gpu_id in range(num_gpus):\n if test_queue and current_processes[gpu_id] is None:\n start_test(test_queue.pop(0), gpu_id)\n\n # Main loop\n try:\n while test_queue or any(p is not None for p in current_processes.values()):\n # Check for completed tests\n free_gpus = check_completion()\n\n # Start new tests on free GPUs\n for gpu_id in free_gpus:\n if test_queue: # If there are tests waiting to be run\n start_test(test_queue.pop(0), gpu_id)\n\n # Small sleep to prevent busy waiting\n time.sleep(1)\n","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.gen_nvfuser_version","uri":"program://Fuser/module/tools.gen_nvfuser_version#L1-L78","kind":"module","name":"tools.gen_nvfuser_version","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":1,"end_line":78,"context_start_line":1,"context_end_line":78,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nUNKNOWN = \"Unknown\"\nnvfuser_root = Path(__file__).parent.parent\n\n\n# note that this root currently is still part of pytorch.\ndef get_sha() -> str:\n try:\n return (\n subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=nvfuser_root)\n .decode(\"ascii\")\n .strip()\n )\n except Exception:\n import os\n\n # assume the $NVFUSER_VERSION is in sha form\n if nvfuser_version := os.environ.get(\"NVFUSER_VERSION\"):\n assert (\n len(nvfuser_version) < 11\n ), \"The NVFUSER_VERSION should be in sha form\"\n return nvfuser_version\n return UNKNOWN\n\n\ndef get_version() -> str:\n sha = get_sha()\n version = (\n open((nvfuser_root / \"version.txt\"), \"r\").read().strip() + \"+git\" + sha[:7]\n )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\ndef get_pytorch_use_distributed():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch; print(torch._C._has_distributed())\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\nif __name__ == \"__main__\":\n assert len(sys.argv) == 2\n assert sys.argv[1] == \"nvfuser\" or sys.argv[1] == \"nvfuser_direct\"\n python_module = sys.argv[1]\n version_file = nvfuser_root / python_module / \"version.py\"\n with open(version_file, \"w\") as f:\n f.write(\"_version_str = '{}'\\n\".format(get_version()))","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.gen_nvfuser_version.get_sha","uri":"program://Fuser/function/tools.gen_nvfuser_version.get_sha#L13-L29","kind":"function","name":"get_sha","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":13,"end_line":29,"context_start_line":1,"context_end_line":49,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nUNKNOWN = \"Unknown\"\nnvfuser_root = Path(__file__).parent.parent\n\n\n# note that this root currently is still part of pytorch.\ndef get_sha() -> str:\n try:\n return (\n subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=nvfuser_root)\n .decode(\"ascii\")\n .strip()\n )\n except Exception:\n import os\n\n # assume the $NVFUSER_VERSION is in sha form\n if nvfuser_version := os.environ.get(\"NVFUSER_VERSION\"):\n assert (\n len(nvfuser_version) < 11\n ), \"The NVFUSER_VERSION should be in sha form\"\n return nvfuser_version\n return UNKNOWN\n\n\ndef get_version() -> str:\n sha = get_sha()\n version = (\n open((nvfuser_root / \"version.txt\"), \"r\").read().strip() + \"+git\" + sha[:7]\n )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.gen_nvfuser_version.get_version","uri":"program://Fuser/function/tools.gen_nvfuser_version.get_version#L32-L37","kind":"function","name":"get_version","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":32,"end_line":37,"context_start_line":12,"context_end_line":57,"code":"# note that this root currently is still part of pytorch.\ndef get_sha() -> str:\n try:\n return (\n subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=nvfuser_root)\n .decode(\"ascii\")\n .strip()\n )\n except Exception:\n import os\n\n # assume the $NVFUSER_VERSION is in sha form\n if nvfuser_version := os.environ.get(\"NVFUSER_VERSION\"):\n assert (\n len(nvfuser_version) < 11\n ), \"The NVFUSER_VERSION should be in sha form\"\n return nvfuser_version\n return UNKNOWN\n\n\ndef get_version() -> str:\n sha = get_sha()\n version = (\n open((nvfuser_root / \"version.txt\"), \"r\").read().strip() + \"+git\" + sha[:7]\n )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\ndef get_pytorch_use_distributed():\n from subprocess import Popen, PIPE","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.gen_nvfuser_version.get_pytorch_cmake_prefix","uri":"program://Fuser/function/tools.gen_nvfuser_version.get_pytorch_cmake_prefix#L40-L53","kind":"function","name":"get_pytorch_cmake_prefix","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":40,"end_line":53,"context_start_line":20,"context_end_line":73,"code":" except Exception:\n import os\n\n # assume the $NVFUSER_VERSION is in sha form\n if nvfuser_version := os.environ.get(\"NVFUSER_VERSION\"):\n assert (\n len(nvfuser_version) < 11\n ), \"The NVFUSER_VERSION should be in sha form\"\n return nvfuser_version\n return UNKNOWN\n\n\ndef get_version() -> str:\n sha = get_sha()\n version = (\n open((nvfuser_root / \"version.txt\"), \"r\").read().strip() + \"+git\" + sha[:7]\n )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\ndef get_pytorch_use_distributed():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch; print(torch._C._has_distributed())\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\nif __name__ == \"__main__\":\n assert len(sys.argv) == 2","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.gen_nvfuser_version.get_pytorch_use_distributed","uri":"program://Fuser/function/tools.gen_nvfuser_version.get_pytorch_use_distributed#L56-L69","kind":"function","name":"get_pytorch_use_distributed","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":56,"end_line":69,"context_start_line":36,"context_end_line":78,"code":" )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\ndef get_pytorch_use_distributed():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch; print(torch._C._has_distributed())\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\nif __name__ == \"__main__\":\n assert len(sys.argv) == 2\n assert sys.argv[1] == \"nvfuser\" or sys.argv[1] == \"nvfuser_direct\"\n python_module = sys.argv[1]\n version_file = nvfuser_root / python_module / \"version.py\"\n with open(version_file, \"w\") as f:\n f.write(\"_version_str = '{}'\\n\".format(get_version()))","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.generate_validation_tolerances","uri":"program://Fuser/module/tools.generate_validation_tolerances#L1-L70","kind":"module","name":"tools.generate_validation_tolerances","path":"tools/generate_validation_tolerances.py","language":"python","start_line":1,"end_line":70,"context_start_line":1,"context_end_line":70,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nThis script reproduces the computation used for generating the validation tolerances in csrc/validator_utils.h:\nhttps://github.com/NVIDIA/Fuser/blob/892b7ac5646b3b873f13f2b2ea1db15fa9b9effb/csrc/validator_utils.h#L25-L46\n\nThe computation (randn + mul + sum) is repeated a large number of times.\nThe base tolerance is the max error seen when comparing the desired precision type with the next higher precision.\nThe final tolerances are computed by adding a safety factor of 3/4 to this base tolerance.\n\nThe output of this file is a .npy file corresponding to each dtype, containing a {size: safety_factor * base_tolerances} dict.\n\nNote: The script may take a long time for a high number of num_iters, so it may be useful to only run the script for one dtype at a time. Modify `dtype_to_ref_dtypes` accordingly.\n\nTo run: python tools/generate_validation_tolerances.py\nTo load the files:\n ```\n import numpy as np\n tol_dict = np.load(file_name.npy, allow_pickle=True).item()\n ```\n\"\"\"\n\nimport numpy as np\nimport torch\nfrom datetime import datetime\n\nsizes = [2**i for i in range(2, 22)] # {4, 2097152}\nnum_iters = 10**6\n\n\ndef compute_max_error(size, dtype, ref_dtype):\n a, b = [torch.randn(size, dtype=dtype, device=\"cuda\") for _ in range(2)]\n out = (a * b).sum()\n ref = (a.to(ref_dtype) * b.to(ref_dtype)).sum()\n max_error = out.sub(ref).abs().max().to(torch.double).item()\n return max_error\n\n\nif __name__ == \"__main__\":\n assert torch.cuda.is_available(), \"A CUDA device is required.\"\n\n device = torch.cuda.get_device_name(torch.cuda.current_device())\n # Comparison is made against the next higher precision,\n # since it seems sufficient and avoids incurring extra memory.\n dtype_to_ref_dtypes = {\n torch.bfloat16: torch.float32,\n torch.float16: torch.float32,\n torch.float32: torch.float64,\n }\n\n # The original safety factor used is not known, but reverse-engineering estimates it between 3-5.\n safety_factor = 4\n\n for dtype, ref_dtype in dtype_to_ref_dtypes.items():\n tolerances = {}\n for size in sizes:\n print(f\"Computing validation constant for size:{size}\")\n base_tolerance = torch.finfo(torch.double).min\n for i in range(num_iters):\n base_tolerance = max(\n base_tolerance, compute_max_error(size, dtype, ref_dtype)\n )\n tolerances[size] = safety_factor * base_tolerance\n date = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n np.save(f\"validation_consts_{dtype}_{device}_{date}.npy\", tolerances)\n print(\n f\"dtype:{dtype} device:{device} safety_factor:{safety_factor}\\n{tolerances}\\n\"\n )","source_hash":"e11585f0ec672f95b20b5c0f544f1ab470a89899391aff47b61ed684e120b193","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.generate_validation_tolerances.compute_max_error","uri":"program://Fuser/function/tools.generate_validation_tolerances.compute_max_error#L33-L38","kind":"function","name":"compute_max_error","path":"tools/generate_validation_tolerances.py","language":"python","start_line":33,"end_line":38,"context_start_line":13,"context_end_line":58,"code":"The output of this file is a .npy file corresponding to each dtype, containing a {size: safety_factor * base_tolerances} dict.\n\nNote: The script may take a long time for a high number of num_iters, so it may be useful to only run the script for one dtype at a time. Modify `dtype_to_ref_dtypes` accordingly.\n\nTo run: python tools/generate_validation_tolerances.py\nTo load the files:\n ```\n import numpy as np\n tol_dict = np.load(file_name.npy, allow_pickle=True).item()\n ```\n\"\"\"\n\nimport numpy as np\nimport torch\nfrom datetime import datetime\n\nsizes = [2**i for i in range(2, 22)] # {4, 2097152}\nnum_iters = 10**6\n\n\ndef compute_max_error(size, dtype, ref_dtype):\n a, b = [torch.randn(size, dtype=dtype, device=\"cuda\") for _ in range(2)]\n out = (a * b).sum()\n ref = (a.to(ref_dtype) * b.to(ref_dtype)).sum()\n max_error = out.sub(ref).abs().max().to(torch.double).item()\n return max_error\n\n\nif __name__ == \"__main__\":\n assert torch.cuda.is_available(), \"A CUDA device is required.\"\n\n device = torch.cuda.get_device_name(torch.cuda.current_device())\n # Comparison is made against the next higher precision,\n # since it seems sufficient and avoids incurring extra memory.\n dtype_to_ref_dtypes = {\n torch.bfloat16: torch.float32,\n torch.float16: torch.float32,\n torch.float32: torch.float64,\n }\n\n # The original safety factor used is not known, but reverse-engineering estimates it between 3-5.\n safety_factor = 4\n\n for dtype, ref_dtype in dtype_to_ref_dtypes.items():\n tolerances = {}\n for size in sizes:","source_hash":"e11585f0ec672f95b20b5c0f544f1ab470a89899391aff47b61ed684e120b193","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff","uri":"program://Fuser/module/tools.codediff.codediff#L1-L1139","kind":"module","name":"tools.codediff.codediff","path":"tools/codediff/codediff.py","language":"python","start_line":1,"end_line":1139,"context_start_line":1,"context_end_line":1139,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nFind corresponding .cu files for matching tests, even when new tests are\nintroduced between two commits. Diffs are displayed and the return value is the\nnumber of mismatched corresponding tests.\n\nTests are skipped if they produce different numbers of .cu files, or if they\nexist in only one of the given runs.\n\nExample usage:\n python tools/diff_codegen_nvfuser_tests.py \\\n codegen_comparison/{$commit1,$commit2}/binary_tests\n\"\"\"\n\nfrom dataclasses import asdict, dataclass, field, InitVar\nimport difflib\nfrom enum import Enum\nimport os\nimport re\nimport subprocess\nimport sys\n\nimport cxxfilt\nfrom dataclasses_json import dataclass_json\n\n\n@dataclass_json\n@dataclass\nclass GitRev:\n full_hash: str\n diff: str | None = None\n abbrev: str | None = None\n title: str | None = None\n author_name: str | None = None\n author_email: str | None = None\n author_time: str | None = None\n commit_time: str | None = None\n\n def __post_init__(self):\n if self.abbrev is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n self.abbrev = (\n subprocess.run(\n [\"git\", \"rev-parse\", \"--short\", self.full_hash], capture_output=True\n )\n .stdout.strip()\n .decode(\"utf-8\")\n )\n for line in (\n subprocess.run(\n [\"git\", \"branch\", \"--quiet\", \"--color=never\", self.full_hash],\n capture_output=True,\n )\n .stdout.strip()\n .decode(\"utf-8\")\n .splitlines()\n ):\n # Possible output:\n #\n # main\n # * scalar_seg_edges\n #\n # In this case, we have checked out the HEAD of the\n # scalar_seg_edges branch. Here we just strip the *.\n if line[0] == \"*\":\n line = line[2:]\n in_branches.append(line)\n\n def git_show(fmt) -> str:\n return (\n subprocess.run(\n [\n \"git\",\n \"show\",\n \"--no-patch\",\n f\"--format={fmt}\",\n self.full_hash,\n ],\n capture_output=True,\n )\n .stdout.strip()\n .decode(\"utf-8\")\n )\n\n self.title = git_show(\"%s\")\n self.author_name = git_show(\"%an\")\n self.author_email = git_show(\"%ae\")\n self.author_time = git_show(\"%ad\")\n self.commit_time = git_show(\"%cd\")\n\n\n@dataclass_json\n@dataclass\nclass LaunchParams:\n blockDim: tuple[int]\n gridDim: tuple[int]\n dynamic_smem_bytes: int\n\n\n@dataclass_json\n@dataclass\nclass CompiledKernel:\n filename: str\n code: str | None = None\n ptx: str | None = None\n ptxas_info: str | None = None\n launch_params_str: str | None = None\n launch_params: LaunchParams | None = None\n gmem_bytes: int = 0\n smem_bytes: int = 0\n cmem_bank_bytes: list[int] | None = None\n registers: int | None = None\n stack_frame_bytes: int = 0\n spill_store_bytes: int = 0\n spill_load_bytes: int = 0\n mangled_name: str | None = None\n arch: str | None = None\n index_type: str | None = None\n\n def __post_init__(self):\n if self.launch_params is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n self.parse_ptxas()\n self.parse_launch_params()\n\n def parse_ptxas(self):\n # Example input:\n #\n # ptxas info : 307 bytes gmem\n # ptxas info : Compiling entry function\n # '_ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_'\n # for 'sm_86'\n # ptxas info : Function properties for\n # _ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_\n # ptxas . 0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads\n # ptxas info : Used 203 registers, 16 bytes smem, 472 bytes cmem[0], 8 bytes cmem[2]\n #\n # Here we parse this into the fields presented, and we replace the\n # mangled kernel name since it includes the kernel number and is\n # useless for the purposes of diffing since the kernel signature is\n # already included.\n if self.ptxas_info is None:\n return\n\n m = re.search(r\"Compiling entry function '(.*)' for '(.*)'\", self.ptxas_info)\n if m is not None:\n self.mangled_name, self.arch = m.groups()\n\n def find_unique_int(pattern) -> int | None:\n assert self.ptxas_info is not None\n m = re.search(pattern, self.ptxas_info)\n return 0 if m is None else int(m.groups()[0])\n\n self.stack_frame_bytes = find_unique_int(r\"(\\d+) bytes stack frame\")\n self.spill_store_bytes = find_unique_int(r\"(\\d+) bytes spill stores\")\n self.spill_load_bytes = find_unique_int(r\"(\\d+) bytes spill loads\")\n self.registers = find_unique_int(r\"(\\d+) registers\")\n self.gmem_bytes = find_unique_int(r\"(\\d+) bytes gmem\")\n self.smem_bytes = find_unique_int(r\"(\\d+) bytes smem\")\n\n self.cmem_bank_bytes = []\n cmem_banks = 0\n for m in re.finditer(r\"(\\d+) bytes cmem\\[(\\d+)\\]\", self.ptxas_info):\n nbytes_str, bank_str = m.groups()\n bank = int(bank_str)\n if len(self.cmem_bank_bytes) <= bank:\n self.cmem_bank_bytes += [0] * (bank + 1 - len(self.cmem_bank_bytes))\n self.cmem_bank_bytes[bank] = int(nbytes_str)\n cmem_banks += 1\n\n def parse_launch_params(self):\n # If NVFUSER_DUMP=launch_param is given we will get a line like this for every launch:\n # Launch Parameters: BlockDim.x = 32, BlockDim.y = 2, BlockDim.z = 2, GridDim.x = 8, GridDim.y = 8, GridDim.z = -1, Smem Size = 49152\n # This is not done by default since we might have hundreds of thousands of these lines.\n # Still, if we recognize it, we will parse this info. If there are\n # multiple lines, we just check that they are all equal and if not then\n # we keep the first version and print a warning.\n if self.launch_params_str is None:\n return\n\n self.launch_params = None\n for line in self.launch_params_str.splitlines():\n m = re.search(\n r\"Launch Parameters: BlockDim.x = (.*), BlockDim.y = (.*), BlockDim.z = (.*), \"\n r\"GridDim.x = (.*), GridDim.y = (.*), GridDim.z = (.*), Smem Size = (.*)$\",\n line,\n )\n bx, by, bz, gx, gy, gz, s = m.groups()\n lp = LaunchParams((bx, by, bz), (gx, gy, gz), s)\n if self.launch_params is None:\n self.launch_params = lp\n else:\n if lp != self.launch_params:\n # Found multiple mismatched launch params for one kernel. Only using first\n return\n\n\n@dataclass_json\n@dataclass\nclass BenchmarkResult:\n gpu_time: float\n gpu_time_unit: str\n cpu_time: float\n cpu_time_unit: float\n iterations: int | None = None\n\n\n@dataclass_json\n@dataclass\nclass CompiledTest:\n \"\"\"One grouping of kernels. A run holds multiple of these\"\"\"\n\n name: str\n kernels: list[CompiledKernel]\n passed: bool = True\n benchmark_result: BenchmarkResult | None = None\n\n\nclass CommandType(str, Enum):\n \"\"\"Denotes what type of command was run\"\"\"\n\n UNKNOWN = \"UNKNOWN\"\n GOOGLETEST = \"GOOGLETEST\"\n GOOGLEBENCH = \"GOOGLEBENCH\"\n PYTEST = \"PYTEST\"\n\n def __str__(self):\n return self.name\n\n @classmethod\n def from_string(cls, type_str: str):\n l = type_str.lower()\n if l[:3] == \"unk\":\n # Specified unknown. Don't print warning\n return cls.UNKNOWN\n elif l == \"gtest\" or l == \"googletest\":\n return cls.GOOGLETEST\n elif l == \"gbench\" or l == \"googlebench\":\n return cls.GOOGLEBENCH\n elif l == \"pytest\":\n return cls.PYTEST\n else:\n print(\n f\"WARNING: Unrecognized command type '{type_str}'. Parsing as UNKNOWN.\",\n file=sys.stderr,\n )\n return cls.UNKNOWN\n\n\nclass LogParser:\n \"\"\"General parser for STDOUT of NVFuser commands\n\n This parser does not group into individual tests, but rather places all\n kernels into a single CompiledTest whose name is \"Ungrouped Kernels\".\n \"\"\"\n\n def __init__(self, log_file: str):\n self.compile_regex()\n\n self.kernel_map: dict[str, CompiledTest] = {}\n\n self.reset_test_state()\n\n self.parse(log_file)\n\n def compile_regex(self):\n # regex for stripping ANSI color codes\n self.ansi_re = re.compile(r\"(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]\")\n\n def reset_kernel_state(self):\n self.current_file = None\n self.ptxas_info = \"\"\n self.launch_params_str = \"\"\n\n def reset_test_state(self):\n \"\"\"Initialize temporary variables used during parsing pass\"\"\"\n self.reset_kernel_state()\n self.current_test = None\n self.kernels = []\n\n def parse(self, log_file: str):\n for line in open(log_file, \"r\").readlines():\n line = self.ansi_re.sub(\"\", line.rstrip())\n self.parse_line(line)\n self.finalize()\n\n def finalize_kernel(self):\n if self.current_file is not None:\n k = CompiledKernel(\n self.current_file,\n ptxas_info=self.ptxas_info,\n launch_params_str=self.launch_params_str,\n )\n self.kernels.append(k)\n self.reset_kernel_state()\n\n def finalize_test(self, passed: bool):\n assert self.current_test is not None\n self.finalize_kernel()\n new_test = CompiledTest(self.current_test, self.kernels, passed)\n self.kernel_map[self.current_test] = new_test\n self.reset_test_state()\n return new_test\n\n def finalize(self):\n if len(self.kernels) > 0:\n group_name = \"Ungrouped Kernels\"\n self.kernel_map[group_name] = CompiledTest(group_name, self.kernels)\n\n def parse_line(self, line):\n \"\"\"Parse a line of log. Return True if consumed\"\"\"\n if line[:10] == \"PRINTING: \":\n if line[-3:] == \".cu\":\n self.finalize_kernel()\n # This avoids comparing the .ptx files that are created then\n # removed by the MemoryTest.LoadCache tests\n self.current_file = line[10:]\n elif line[:6] == \"ptxas \":\n # NVFUSER_DUMP=ptxas_verbose corresponds to nvcc --ptxas-options=-v\n # or --resources-usage. This always prints after printing the cuda\n # filename\n if self.current_file is None:\n print(\"WARNING: Cannot associate ptxas info with CUDA kernel\")\n return False\n self.ptxas_info += line + \"\\n\"\n elif line[:19] == \"Launch Parameters: \":\n if self.current_file is None:\n print(\"WARNING: Cannot associate launch params with CUDA kernel\")\n return False\n self.launch_params_str += line + \"\\n\"\n else:\n return False\n return True\n\n\nclass LogParserGTest(LogParser):\n \"\"\"Parse output of googletest binaries like test_nvfuser\"\"\"\n\n def parse_line(self, line):\n if super().parse_line(line):\n return True\n\n if line[:13] == \"[ RUN ] \":\n self.current_test = line[13:]\n elif line[:13] == \"[ OK ] \":\n self.finalize_test(True)\n elif line[:13] == \"[ FAILED ] \":\n if self.current_test is not None and self.current_file is not None:\n # Avoid the summary of failed tests, such as\n # [ FAILED ] 1 test, listed below:\n # [ FAILED ] NVFuserTest.FusionTuringMatmulSplitK_CUDA\n self.finalize_test(False)\n else:\n return False\n return True\n\n\nclass LogParserGBench(LogParser):\n \"\"\"Parse output of google benchmark binaries like nvfuser_bench\"\"\"\n\n def compile_regex(self):\n super().compile_regex()\n\n # Example line:\n # benchmark_name 34.0 us 1.53 ms 2007 /Launch_Parameters[block(2/2/32)/grid(32/2/2)/49664]\n # This is the only kind of line we match for benchmarks. Note that this is printed at the end of each benchmark\n self.result_re = re.compile(\n r\"^(?P\\S+)\\s+(?P[-+\\.\\d]+)\\s+(?P\\S+)\\s+(?P[-+\\.\\d]+)\\s+(?P\\S+)\\s+(?P\\d+).*$\"\n )\n\n def parse_line(self, line):\n if super().parse_line(line):\n return True\n\n m = re.match(self.result_re, line)\n if m is not None:\n d = m.groupdict()\n self.current_test = d[\"testname\"]\n time = d[\"gputime\"]\n time_unit = d[\"gputimeunit\"]\n cpu = d[\"cputime\"]\n cpu_unit = d[\"cputimeunit\"]\n iterations = d[\"iterations\"]\n # Skip metadata which for nvfuser_bench sometimes includes LaunchParams\n # meta = m.groups()[6]\n new_test = self.finalize_test(True)\n new_test.benchmark_result = BenchmarkResult(\n time, time_unit, cpu, cpu_unit, iterations\n )\n return True\n return False\n\n\nclass LogParserPyTest(LogParser):\n \"\"\"Parse output of pytest tests.\n\n Note that the tests must be run with both the -v and -s options\n \"\"\"\n\n def compile_regex(self):\n super().compile_regex()\n\n self.itemlist_re = re.compile(r\"Running \\d+ items in this shard: (.*)$\")\n\n # match lines like these:\n # [2024-10-23 02:00:20] tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears PASSED\n\n self.wildcard_testname_re = re.compile(\n r\"^((?P\\[[\\d\\-: ]+\\]) )?(?P\\S+\\.py::\\S+)\\s?(?P.*)$\"\n )\n\n self.extra_wildcard_testname_re = re.compile(\n r\".*?(?P\\S+::\\S+) (?P.*)$\"\n )\n\n self.all_test_names: list[str] | None = None\n\n def parse_line(self, line):\n if self.all_test_names is None:\n m = re.match(self.itemlist_re, line)\n if m is not None:\n # grab the test list\n self.all_test_names = m.groups()[0].split(\", \")\n return True\n\n m = re.match(self.wildcard_testname_re, line)\n if m is not None:\n d = m.groupdict()\n self.current_test = d[\"testname\"]\n line = d[\"line\"]\n\n if line == \"PASSED\":\n self.finalize_test(True)\n elif line == \"FAILED\" and self.current_test is not None:\n self.finalize_test(False)\n\n if super().parse_line(line):\n return True\n\n return False\n\n\n@dataclass_json\n@dataclass\nclass TestRun:\n \"\"\"A single process that might contain many kernels, grouped into tests\"\"\"\n\n directory: str\n git: GitRev | None = None\n name: str | None = None\n command: str | None = None\n command_type: CommandType | None = None\n exit_code: int | None = None\n env: str | None = None\n gpu_names: str | None = None\n nvcc_version: str | None = None\n # map from name of test to list of kernel base filenames\n kernel_map: dict[str, CompiledTest] | None = None\n # collecting the preamble lets us skip it when diffing, and lets us compare\n # only the preamble between runs\n preamble: str | None = None\n # The following lets us skip preamble when loading kernels. Note that the\n # preamble can change length due to differing index types, so we can't rely\n # on f.seek()\n preamble_size_lines: int | None = None\n\n def __post_init__(self):\n if self.git is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n if not os.path.isdir(self.directory):\n print(f\"ERROR: {self.directory} does not name a directory\")\n sys.exit(1)\n\n try:\n self.name = (\n open(os.path.join(self.directory, \"run_name\"), \"r\").read().rstrip()\n )\n except FileNotFoundError:\n self.name = os.path.basename(self.directory)\n\n # get description of this git rev\n gitdiff = None\n try:\n gitdiff = open(os.path.join(self.directory, \"git_diff\"), \"r\").read()\n except FileNotFoundError:\n pass\n git_hash = open(os.path.join(self.directory, \"git_hash\"), \"r\").read().rstrip()\n self.git = GitRev(git_hash, diff=gitdiff)\n\n self.command = open(os.path.join(self.directory, \"command\"), \"r\").read()\n\n try:\n self.command_type = CommandType.from_string(\n open(os.path.join(self.directory, \"command_type\"), \"r\").read().rstrip()\n )\n except FileNotFoundError:\n print(\n f\"WARNING: Could not find {os.path.join(self.directory, 'command_type')}. \"\n \"Parsing as UNKNOWN command type means kernels will be ungrouped.\",\n file=sys.stderr,\n )\n self.command_type = CommandType.UNKNOWN\n\n try:\n self.env = \"\"\n for line in open(os.path.join(self.directory, \"env\"), \"r\").readlines():\n # remove $testdir which is set by compare_codegen.sh\n # NOTE: compare_codegen.sh should have already removed these lines\n if re.search(r\"^testdir=\", line) is None:\n self.env += line\n except FileNotFoundError:\n self.env = None\n\n try:\n self.nvcc_version = open(\n os.path.join(self.directory, \"nvcc_version\"), \"r\"\n ).read()\n except FileNotFoundError:\n self.nvcc_version = None\n\n try:\n self.gpu_names = list(\n open(os.path.join(self.directory, \"gpu_names\"), \"r\").readlines()\n )\n except FileNotFoundError:\n self.gpu_names = None\n\n self.exit_code = int(open(os.path.join(self.directory, \"exitcode\"), \"r\").read())\n\n self.compute_kernel_map()\n\n self.find_preamble()\n\n def compute_kernel_map(self):\n \"\"\"\n Compute a map from test name to list of cuda filenames\n \"\"\"\n logfile = os.path.join(self.directory, \"stdout\")\n if not os.path.isfile(logfile):\n raise RuntimeError(\n f\"Input directory {self.directory} contains no file named 'stdout'\"\n )\n\n if self.command_type == CommandType.GOOGLETEST:\n parser = LogParserGTest(logfile)\n elif self.command_type == CommandType.GOOGLEBENCH:\n parser = LogParserGBench(logfile)\n elif self.command_type == CommandType.PYTEST:\n parser = LogParserPyTest(logfile)\n else:\n # The base class provides a parser that groups everything into a\n # single \"test\" called \"Ungrouped Kernels\"\n parser = LogParser(logfile)\n\n self.kernel_map = parser.kernel_map\n\n def find_preamble(self):\n \"\"\"Look for common preamble in collected kernels\"\"\"\n preamble_lines = []\n first = True\n files_processed = 0 # limit how many files to check\n for cufile in os.listdir(os.path.join(self.directory, \"cuda\")):\n cufil\n# ... truncated ...","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":true} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.GitRev","uri":"program://Fuser/class/tools.codediff.codediff.GitRev#L31-L93","kind":"class","name":"GitRev","path":"tools/codediff/codediff.py","language":"python","start_line":31,"end_line":93,"context_start_line":11,"context_end_line":113,"code":"\nExample usage:\n python tools/diff_codegen_nvfuser_tests.py \\\n codegen_comparison/{$commit1,$commit2}/binary_tests\n\"\"\"\n\nfrom dataclasses import asdict, dataclass, field, InitVar\nimport difflib\nfrom enum import Enum\nimport os\nimport re\nimport subprocess\nimport sys\n\nimport cxxfilt\nfrom dataclasses_json import dataclass_json\n\n\n@dataclass_json\n@dataclass\nclass GitRev:\n full_hash: str\n diff: str | None = None\n abbrev: str | None = None\n title: str | None = None\n author_name: str | None = None\n author_email: str | None = None\n author_time: str | None = None\n commit_time: str | None = None\n\n def __post_init__(self):\n if self.abbrev is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n self.abbrev = (\n subprocess.run(\n [\"git\", \"rev-parse\", \"--short\", self.full_hash], capture_output=True\n )\n .stdout.strip()\n .decode(\"utf-8\")\n )\n for line in (\n subprocess.run(\n [\"git\", \"branch\", \"--quiet\", \"--color=never\", self.full_hash],\n capture_output=True,\n )\n .stdout.strip()\n .decode(\"utf-8\")\n .splitlines()\n ):\n # Possible output:\n #\n # main\n # * scalar_seg_edges\n #\n # In this case, we have checked out the HEAD of the\n # scalar_seg_edges branch. Here we just strip the *.\n if line[0] == \"*\":\n line = line[2:]\n in_branches.append(line)\n\n def git_show(fmt) -> str:\n return (\n subprocess.run(\n [\n \"git\",\n \"show\",\n \"--no-patch\",\n f\"--format={fmt}\",\n self.full_hash,\n ],\n capture_output=True,\n )\n .stdout.strip()\n .decode(\"utf-8\")\n )\n\n self.title = git_show(\"%s\")\n self.author_name = git_show(\"%an\")\n self.author_email = git_show(\"%ae\")\n self.author_time = git_show(\"%ad\")\n self.commit_time = git_show(\"%cd\")\n\n\n@dataclass_json\n@dataclass\nclass LaunchParams:\n blockDim: tuple[int]\n gridDim: tuple[int]\n dynamic_smem_bytes: int\n\n\n@dataclass_json\n@dataclass\nclass CompiledKernel:\n filename: str\n code: str | None = None\n ptx: str | None = None\n ptxas_info: str | None = None\n launch_params_str: str | None = None\n launch_params: LaunchParams | None = None\n gmem_bytes: int = 0","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.LaunchParams","uri":"program://Fuser/class/tools.codediff.codediff.LaunchParams#L98-L101","kind":"class","name":"LaunchParams","path":"tools/codediff/codediff.py","language":"python","start_line":98,"end_line":101,"context_start_line":78,"context_end_line":121,"code":" \"show\",\n \"--no-patch\",\n f\"--format={fmt}\",\n self.full_hash,\n ],\n capture_output=True,\n )\n .stdout.strip()\n .decode(\"utf-8\")\n )\n\n self.title = git_show(\"%s\")\n self.author_name = git_show(\"%an\")\n self.author_email = git_show(\"%ae\")\n self.author_time = git_show(\"%ad\")\n self.commit_time = git_show(\"%cd\")\n\n\n@dataclass_json\n@dataclass\nclass LaunchParams:\n blockDim: tuple[int]\n gridDim: tuple[int]\n dynamic_smem_bytes: int\n\n\n@dataclass_json\n@dataclass\nclass CompiledKernel:\n filename: str\n code: str | None = None\n ptx: str | None = None\n ptxas_info: str | None = None\n launch_params_str: str | None = None\n launch_params: LaunchParams | None = None\n gmem_bytes: int = 0\n smem_bytes: int = 0\n cmem_bank_bytes: list[int] | None = None\n registers: int | None = None\n stack_frame_bytes: int = 0\n spill_store_bytes: int = 0\n spill_load_bytes: int = 0\n mangled_name: str | None = None\n arch: str | None = None","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.CompiledKernel","uri":"program://Fuser/class/tools.codediff.codediff.CompiledKernel#L106-L201","kind":"class","name":"CompiledKernel","path":"tools/codediff/codediff.py","language":"python","start_line":106,"end_line":201,"context_start_line":86,"context_end_line":221,"code":" .decode(\"utf-8\")\n )\n\n self.title = git_show(\"%s\")\n self.author_name = git_show(\"%an\")\n self.author_email = git_show(\"%ae\")\n self.author_time = git_show(\"%ad\")\n self.commit_time = git_show(\"%cd\")\n\n\n@dataclass_json\n@dataclass\nclass LaunchParams:\n blockDim: tuple[int]\n gridDim: tuple[int]\n dynamic_smem_bytes: int\n\n\n@dataclass_json\n@dataclass\nclass CompiledKernel:\n filename: str\n code: str | None = None\n ptx: str | None = None\n ptxas_info: str | None = None\n launch_params_str: str | None = None\n launch_params: LaunchParams | None = None\n gmem_bytes: int = 0\n smem_bytes: int = 0\n cmem_bank_bytes: list[int] | None = None\n registers: int | None = None\n stack_frame_bytes: int = 0\n spill_store_bytes: int = 0\n spill_load_bytes: int = 0\n mangled_name: str | None = None\n arch: str | None = None\n index_type: str | None = None\n\n def __post_init__(self):\n if self.launch_params is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n self.parse_ptxas()\n self.parse_launch_params()\n\n def parse_ptxas(self):\n # Example input:\n #\n # ptxas info : 307 bytes gmem\n # ptxas info : Compiling entry function\n # '_ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_'\n # for 'sm_86'\n # ptxas info : Function properties for\n # _ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_\n # ptxas . 0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads\n # ptxas info : Used 203 registers, 16 bytes smem, 472 bytes cmem[0], 8 bytes cmem[2]\n #\n # Here we parse this into the fields presented, and we replace the\n # mangled kernel name since it includes the kernel number and is\n # useless for the purposes of diffing since the kernel signature is\n # already included.\n if self.ptxas_info is None:\n return\n\n m = re.search(r\"Compiling entry function '(.*)' for '(.*)'\", self.ptxas_info)\n if m is not None:\n self.mangled_name, self.arch = m.groups()\n\n def find_unique_int(pattern) -> int | None:\n assert self.ptxas_info is not None\n m = re.search(pattern, self.ptxas_info)\n return 0 if m is None else int(m.groups()[0])\n\n self.stack_frame_bytes = find_unique_int(r\"(\\d+) bytes stack frame\")\n self.spill_store_bytes = find_unique_int(r\"(\\d+) bytes spill stores\")\n self.spill_load_bytes = find_unique_int(r\"(\\d+) bytes spill loads\")\n self.registers = find_unique_int(r\"(\\d+) registers\")\n self.gmem_bytes = find_unique_int(r\"(\\d+) bytes gmem\")\n self.smem_bytes = find_unique_int(r\"(\\d+) bytes smem\")\n\n self.cmem_bank_bytes = []\n cmem_banks = 0\n for m in re.finditer(r\"(\\d+) bytes cmem\\[(\\d+)\\]\", self.ptxas_info):\n nbytes_str, bank_str = m.groups()\n bank = int(bank_str)\n if len(self.cmem_bank_bytes) <= bank:\n self.cmem_bank_bytes += [0] * (bank + 1 - len(self.cmem_bank_bytes))\n self.cmem_bank_bytes[bank] = int(nbytes_str)\n cmem_banks += 1\n\n def parse_launch_params(self):\n # If NVFUSER_DUMP=launch_param is given we will get a line like this for every launch:\n # Launch Parameters: BlockDim.x = 32, BlockDim.y = 2, BlockDim.z = 2, GridDim.x = 8, GridDim.y = 8, GridDim.z = -1, Smem Size = 49152\n # This is not done by default since we might have hundreds of thousands of these lines.\n # Still, if we recognize it, we will parse this info. If there are\n # multiple lines, we just check that they are all equal and if not then\n # we keep the first version and print a warning.\n if self.launch_params_str is None:\n return\n\n self.launch_params = None\n for line in self.launch_params_str.splitlines():\n m = re.search(\n r\"Launch Parameters: BlockDim.x = (.*), BlockDim.y = (.*), BlockDim.z = (.*), \"\n r\"GridDim.x = (.*), GridDim.y = (.*), GridDim.z = (.*), Smem Size = (.*)$\",\n line,\n )\n bx, by, bz, gx, gy, gz, s = m.groups()\n lp = LaunchParams((bx, by, bz), (gx, gy, gz), s)\n if self.launch_params is None:\n self.launch_params = lp\n else:\n if lp != self.launch_params:\n # Found multiple mismatched launch params for one kernel. Only using first\n return\n\n\n@dataclass_json\n@dataclass\nclass BenchmarkResult:\n gpu_time: float\n gpu_time_unit: str\n cpu_time: float\n cpu_time_unit: float\n iterations: int | None = None\n\n\n@dataclass_json\n@dataclass\nclass CompiledTest:\n \"\"\"One grouping of kernels. A run holds multiple of these\"\"\"\n\n name: str\n kernels: list[CompiledKernel]\n passed: bool = True","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.BenchmarkResult","uri":"program://Fuser/class/tools.codediff.codediff.BenchmarkResult#L206-L211","kind":"class","name":"BenchmarkResult","path":"tools/codediff/codediff.py","language":"python","start_line":206,"end_line":211,"context_start_line":186,"context_end_line":231,"code":"\n self.launch_params = None\n for line in self.launch_params_str.splitlines():\n m = re.search(\n r\"Launch Parameters: BlockDim.x = (.*), BlockDim.y = (.*), BlockDim.z = (.*), \"\n r\"GridDim.x = (.*), GridDim.y = (.*), GridDim.z = (.*), Smem Size = (.*)$\",\n line,\n )\n bx, by, bz, gx, gy, gz, s = m.groups()\n lp = LaunchParams((bx, by, bz), (gx, gy, gz), s)\n if self.launch_params is None:\n self.launch_params = lp\n else:\n if lp != self.launch_params:\n # Found multiple mismatched launch params for one kernel. Only using first\n return\n\n\n@dataclass_json\n@dataclass\nclass BenchmarkResult:\n gpu_time: float\n gpu_time_unit: str\n cpu_time: float\n cpu_time_unit: float\n iterations: int | None = None\n\n\n@dataclass_json\n@dataclass\nclass CompiledTest:\n \"\"\"One grouping of kernels. A run holds multiple of these\"\"\"\n\n name: str\n kernels: list[CompiledKernel]\n passed: bool = True\n benchmark_result: BenchmarkResult | None = None\n\n\nclass CommandType(str, Enum):\n \"\"\"Denotes what type of command was run\"\"\"\n\n UNKNOWN = \"UNKNOWN\"\n GOOGLETEST = \"GOOGLETEST\"\n GOOGLEBENCH = \"GOOGLEBENCH\"\n PYTEST = \"PYTEST\"","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.CompiledTest","uri":"program://Fuser/class/tools.codediff.codediff.CompiledTest#L216-L222","kind":"class","name":"CompiledTest","path":"tools/codediff/codediff.py","language":"python","start_line":216,"end_line":222,"context_start_line":196,"context_end_line":242,"code":" if self.launch_params is None:\n self.launch_params = lp\n else:\n if lp != self.launch_params:\n # Found multiple mismatched launch params for one kernel. Only using first\n return\n\n\n@dataclass_json\n@dataclass\nclass BenchmarkResult:\n gpu_time: float\n gpu_time_unit: str\n cpu_time: float\n cpu_time_unit: float\n iterations: int | None = None\n\n\n@dataclass_json\n@dataclass\nclass CompiledTest:\n \"\"\"One grouping of kernels. A run holds multiple of these\"\"\"\n\n name: str\n kernels: list[CompiledKernel]\n passed: bool = True\n benchmark_result: BenchmarkResult | None = None\n\n\nclass CommandType(str, Enum):\n \"\"\"Denotes what type of command was run\"\"\"\n\n UNKNOWN = \"UNKNOWN\"\n GOOGLETEST = \"GOOGLETEST\"\n GOOGLEBENCH = \"GOOGLEBENCH\"\n PYTEST = \"PYTEST\"\n\n def __str__(self):\n return self.name\n\n @classmethod\n def from_string(cls, type_str: str):\n l = type_str.lower()\n if l[:3] == \"unk\":\n # Specified unknown. Don't print warning\n return cls.UNKNOWN\n elif l == \"gtest\" or l == \"googletest\":","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.CommandType","uri":"program://Fuser/class/tools.codediff.codediff.CommandType#L225-L253","kind":"class","name":"CommandType","path":"tools/codediff/codediff.py","language":"python","start_line":225,"end_line":253,"context_start_line":205,"context_end_line":273,"code":"@dataclass\nclass BenchmarkResult:\n gpu_time: float\n gpu_time_unit: str\n cpu_time: float\n cpu_time_unit: float\n iterations: int | None = None\n\n\n@dataclass_json\n@dataclass\nclass CompiledTest:\n \"\"\"One grouping of kernels. A run holds multiple of these\"\"\"\n\n name: str\n kernels: list[CompiledKernel]\n passed: bool = True\n benchmark_result: BenchmarkResult | None = None\n\n\nclass CommandType(str, Enum):\n \"\"\"Denotes what type of command was run\"\"\"\n\n UNKNOWN = \"UNKNOWN\"\n GOOGLETEST = \"GOOGLETEST\"\n GOOGLEBENCH = \"GOOGLEBENCH\"\n PYTEST = \"PYTEST\"\n\n def __str__(self):\n return self.name\n\n @classmethod\n def from_string(cls, type_str: str):\n l = type_str.lower()\n if l[:3] == \"unk\":\n # Specified unknown. Don't print warning\n return cls.UNKNOWN\n elif l == \"gtest\" or l == \"googletest\":\n return cls.GOOGLETEST\n elif l == \"gbench\" or l == \"googlebench\":\n return cls.GOOGLEBENCH\n elif l == \"pytest\":\n return cls.PYTEST\n else:\n print(\n f\"WARNING: Unrecognized command type '{type_str}'. Parsing as UNKNOWN.\",\n file=sys.stderr,\n )\n return cls.UNKNOWN\n\n\nclass LogParser:\n \"\"\"General parser for STDOUT of NVFuser commands\n\n This parser does not group into individual tests, but rather places all\n kernels into a single CompiledTest whose name is \"Ungrouped Kernels\".\n \"\"\"\n\n def __init__(self, log_file: str):\n self.compile_regex()\n\n self.kernel_map: dict[str, CompiledTest] = {}\n\n self.reset_test_state()\n\n self.parse(log_file)\n\n def compile_regex(self):\n # regex for stripping ANSI color codes","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.LogParser","uri":"program://Fuser/class/tools.codediff.codediff.LogParser#L256-L339","kind":"class","name":"LogParser","path":"tools/codediff/codediff.py","language":"python","start_line":256,"end_line":339,"context_start_line":236,"context_end_line":359,"code":" @classmethod\n def from_string(cls, type_str: str):\n l = type_str.lower()\n if l[:3] == \"unk\":\n # Specified unknown. Don't print warning\n return cls.UNKNOWN\n elif l == \"gtest\" or l == \"googletest\":\n return cls.GOOGLETEST\n elif l == \"gbench\" or l == \"googlebench\":\n return cls.GOOGLEBENCH\n elif l == \"pytest\":\n return cls.PYTEST\n else:\n print(\n f\"WARNING: Unrecognized command type '{type_str}'. Parsing as UNKNOWN.\",\n file=sys.stderr,\n )\n return cls.UNKNOWN\n\n\nclass LogParser:\n \"\"\"General parser for STDOUT of NVFuser commands\n\n This parser does not group into individual tests, but rather places all\n kernels into a single CompiledTest whose name is \"Ungrouped Kernels\".\n \"\"\"\n\n def __init__(self, log_file: str):\n self.compile_regex()\n\n self.kernel_map: dict[str, CompiledTest] = {}\n\n self.reset_test_state()\n\n self.parse(log_file)\n\n def compile_regex(self):\n # regex for stripping ANSI color codes\n self.ansi_re = re.compile(r\"(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]\")\n\n def reset_kernel_state(self):\n self.current_file = None\n self.ptxas_info = \"\"\n self.launch_params_str = \"\"\n\n def reset_test_state(self):\n \"\"\"Initialize temporary variables used during parsing pass\"\"\"\n self.reset_kernel_state()\n self.current_test = None\n self.kernels = []\n\n def parse(self, log_file: str):\n for line in open(log_file, \"r\").readlines():\n line = self.ansi_re.sub(\"\", line.rstrip())\n self.parse_line(line)\n self.finalize()\n\n def finalize_kernel(self):\n if self.current_file is not None:\n k = CompiledKernel(\n self.current_file,\n ptxas_info=self.ptxas_info,\n launch_params_str=self.launch_params_str,\n )\n self.kernels.append(k)\n self.reset_kernel_state()\n\n def finalize_test(self, passed: bool):\n assert self.current_test is not None\n self.finalize_kernel()\n new_test = CompiledTest(self.current_test, self.kernels, passed)\n self.kernel_map[self.current_test] = new_test\n self.reset_test_state()\n return new_test\n\n def finalize(self):\n if len(self.kernels) > 0:\n group_name = \"Ungrouped Kernels\"\n self.kernel_map[group_name] = CompiledTest(group_name, self.kernels)\n\n def parse_line(self, line):\n \"\"\"Parse a line of log. Return True if consumed\"\"\"\n if line[:10] == \"PRINTING: \":\n if line[-3:] == \".cu\":\n self.finalize_kernel()\n # This avoids comparing the .ptx files that are created then\n # removed by the MemoryTest.LoadCache tests\n self.current_file = line[10:]\n elif line[:6] == \"ptxas \":\n # NVFUSER_DUMP=ptxas_verbose corresponds to nvcc --ptxas-options=-v\n # or --resources-usage. This always prints after printing the cuda\n # filename\n if self.current_file is None:\n print(\"WARNING: Cannot associate ptxas info with CUDA kernel\")\n return False\n self.ptxas_info += line + \"\\n\"\n elif line[:19] == \"Launch Parameters: \":\n if self.current_file is None:\n print(\"WARNING: Cannot associate launch params with CUDA kernel\")\n return False\n self.launch_params_str += line + \"\\n\"\n else:\n return False\n return True\n\n\nclass LogParserGTest(LogParser):\n \"\"\"Parse output of googletest binaries like test_nvfuser\"\"\"\n\n def parse_line(self, line):\n if super().parse_line(line):\n return True\n\n if line[:13] == \"[ RUN ] \":\n self.current_test = line[13:]\n elif line[:13] == \"[ OK ] \":\n self.finalize_test(True)\n elif line[:13] == \"[ FAILED ] \":\n if self.current_test is not None and self.current_file is not None:\n # Avoid the summary of failed tests, such as\n # [ FAILED ] 1 test, listed below:\n # [ FAILED ] NVFuserTest.FusionTuringMatmulSplitK_CUDA\n self.finalize_test(False)\n else:","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.LogParserGTest","uri":"program://Fuser/class/tools.codediff.codediff.LogParserGTest#L342-L361","kind":"class","name":"LogParserGTest","path":"tools/codediff/codediff.py","language":"python","start_line":342,"end_line":361,"context_start_line":322,"context_end_line":381,"code":" # removed by the MemoryTest.LoadCache tests\n self.current_file = line[10:]\n elif line[:6] == \"ptxas \":\n # NVFUSER_DUMP=ptxas_verbose corresponds to nvcc --ptxas-options=-v\n # or --resources-usage. This always prints after printing the cuda\n # filename\n if self.current_file is None:\n print(\"WARNING: Cannot associate ptxas info with CUDA kernel\")\n return False\n self.ptxas_info += line + \"\\n\"\n elif line[:19] == \"Launch Parameters: \":\n if self.current_file is None:\n print(\"WARNING: Cannot associate launch params with CUDA kernel\")\n return False\n self.launch_params_str += line + \"\\n\"\n else:\n return False\n return True\n\n\nclass LogParserGTest(LogParser):\n \"\"\"Parse output of googletest binaries like test_nvfuser\"\"\"\n\n def parse_line(self, line):\n if super().parse_line(line):\n return True\n\n if line[:13] == \"[ RUN ] \":\n self.current_test = line[13:]\n elif line[:13] == \"[ OK ] \":\n self.finalize_test(True)\n elif line[:13] == \"[ FAILED ] \":\n if self.current_test is not None and self.current_file is not None:\n # Avoid the summary of failed tests, such as\n # [ FAILED ] 1 test, listed below:\n # [ FAILED ] NVFuserTest.FusionTuringMatmulSplitK_CUDA\n self.finalize_test(False)\n else:\n return False\n return True\n\n\nclass LogParserGBench(LogParser):\n \"\"\"Parse output of google benchmark binaries like nvfuser_bench\"\"\"\n\n def compile_regex(self):\n super().compile_regex()\n\n # Example line:\n # benchmark_name 34.0 us 1.53 ms 2007 /Launch_Parameters[block(2/2/32)/grid(32/2/2)/49664]\n # This is the only kind of line we match for benchmarks. Note that this is printed at the end of each benchmark\n self.result_re = re.compile(\n r\"^(?P\\S+)\\s+(?P[-+\\.\\d]+)\\s+(?P\\S+)\\s+(?P[-+\\.\\d]+)\\s+(?P\\S+)\\s+(?P\\d+).*$\"\n )\n\n def parse_line(self, line):\n if super().parse_line(line):\n return True\n\n m = re.match(self.result_re, line)","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.LogParserGBench","uri":"program://Fuser/class/tools.codediff.codediff.LogParserGBench#L364-L397","kind":"class","name":"LogParserGBench","path":"tools/codediff/codediff.py","language":"python","start_line":364,"end_line":397,"context_start_line":344,"context_end_line":417,"code":"\n def parse_line(self, line):\n if super().parse_line(line):\n return True\n\n if line[:13] == \"[ RUN ] \":\n self.current_test = line[13:]\n elif line[:13] == \"[ OK ] \":\n self.finalize_test(True)\n elif line[:13] == \"[ FAILED ] \":\n if self.current_test is not None and self.current_file is not None:\n # Avoid the summary of failed tests, such as\n # [ FAILED ] 1 test, listed below:\n # [ FAILED ] NVFuserTest.FusionTuringMatmulSplitK_CUDA\n self.finalize_test(False)\n else:\n return False\n return True\n\n\nclass LogParserGBench(LogParser):\n \"\"\"Parse output of google benchmark binaries like nvfuser_bench\"\"\"\n\n def compile_regex(self):\n super().compile_regex()\n\n # Example line:\n # benchmark_name 34.0 us 1.53 ms 2007 /Launch_Parameters[block(2/2/32)/grid(32/2/2)/49664]\n # This is the only kind of line we match for benchmarks. Note that this is printed at the end of each benchmark\n self.result_re = re.compile(\n r\"^(?P\\S+)\\s+(?P[-+\\.\\d]+)\\s+(?P\\S+)\\s+(?P[-+\\.\\d]+)\\s+(?P\\S+)\\s+(?P\\d+).*$\"\n )\n\n def parse_line(self, line):\n if super().parse_line(line):\n return True\n\n m = re.match(self.result_re, line)\n if m is not None:\n d = m.groupdict()\n self.current_test = d[\"testname\"]\n time = d[\"gputime\"]\n time_unit = d[\"gputimeunit\"]\n cpu = d[\"cputime\"]\n cpu_unit = d[\"cputimeunit\"]\n iterations = d[\"iterations\"]\n # Skip metadata which for nvfuser_bench sometimes includes LaunchParams\n # meta = m.groups()[6]\n new_test = self.finalize_test(True)\n new_test.benchmark_result = BenchmarkResult(\n time, time_unit, cpu, cpu_unit, iterations\n )\n return True\n return False\n\n\nclass LogParserPyTest(LogParser):\n \"\"\"Parse output of pytest tests.\n\n Note that the tests must be run with both the -v and -s options\n \"\"\"\n\n def compile_regex(self):\n super().compile_regex()\n\n self.itemlist_re = re.compile(r\"Running \\d+ items in this shard: (.*)$\")\n\n # match lines like these:\n # [2024-10-23 02:00:20] tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears PASSED\n\n self.wildcard_testname_re = re.compile(\n r\"^((?P\\[[\\d\\-: ]+\\]) )?(?P\\S+\\.py::\\S+)\\s?(?P.*)$\"","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.LogParserPyTest","uri":"program://Fuser/class/tools.codediff.codediff.LogParserPyTest#L400-L448","kind":"class","name":"LogParserPyTest","path":"tools/codediff/codediff.py","language":"python","start_line":400,"end_line":448,"context_start_line":380,"context_end_line":468,"code":"\n m = re.match(self.result_re, line)\n if m is not None:\n d = m.groupdict()\n self.current_test = d[\"testname\"]\n time = d[\"gputime\"]\n time_unit = d[\"gputimeunit\"]\n cpu = d[\"cputime\"]\n cpu_unit = d[\"cputimeunit\"]\n iterations = d[\"iterations\"]\n # Skip metadata which for nvfuser_bench sometimes includes LaunchParams\n # meta = m.groups()[6]\n new_test = self.finalize_test(True)\n new_test.benchmark_result = BenchmarkResult(\n time, time_unit, cpu, cpu_unit, iterations\n )\n return True\n return False\n\n\nclass LogParserPyTest(LogParser):\n \"\"\"Parse output of pytest tests.\n\n Note that the tests must be run with both the -v and -s options\n \"\"\"\n\n def compile_regex(self):\n super().compile_regex()\n\n self.itemlist_re = re.compile(r\"Running \\d+ items in this shard: (.*)$\")\n\n # match lines like these:\n # [2024-10-23 02:00:20] tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears PASSED\n\n self.wildcard_testname_re = re.compile(\n r\"^((?P\\[[\\d\\-: ]+\\]) )?(?P\\S+\\.py::\\S+)\\s?(?P.*)$\"\n )\n\n self.extra_wildcard_testname_re = re.compile(\n r\".*?(?P\\S+::\\S+) (?P.*)$\"\n )\n\n self.all_test_names: list[str] | None = None\n\n def parse_line(self, line):\n if self.all_test_names is None:\n m = re.match(self.itemlist_re, line)\n if m is not None:\n # grab the test list\n self.all_test_names = m.groups()[0].split(\", \")\n return True\n\n m = re.match(self.wildcard_testname_re, line)\n if m is not None:\n d = m.groupdict()\n self.current_test = d[\"testname\"]\n line = d[\"line\"]\n\n if line == \"PASSED\":\n self.finalize_test(True)\n elif line == \"FAILED\" and self.current_test is not None:\n self.finalize_test(False)\n\n if super().parse_line(line):\n return True\n\n return False\n\n\n@dataclass_json\n@dataclass\nclass TestRun:\n \"\"\"A single process that might contain many kernels, grouped into tests\"\"\"\n\n directory: str\n git: GitRev | None = None\n name: str | None = None\n command: str | None = None\n command_type: CommandType | None = None\n exit_code: int | None = None\n env: str | None = None\n gpu_names: str | None = None\n nvcc_version: str | None = None\n # map from name of test to list of kernel base filenames\n kernel_map: dict[str, CompiledTest] | None = None\n # collecting the preamble lets us skip it when diffing, and lets us compare\n # only the preamble between runs","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.TestRun","uri":"program://Fuser/class/tools.codediff.codediff.TestRun#L453-L679","kind":"class","name":"TestRun","path":"tools/codediff/codediff.py","language":"python","start_line":453,"end_line":679,"context_start_line":433,"context_end_line":699,"code":"\n m = re.match(self.wildcard_testname_re, line)\n if m is not None:\n d = m.groupdict()\n self.current_test = d[\"testname\"]\n line = d[\"line\"]\n\n if line == \"PASSED\":\n self.finalize_test(True)\n elif line == \"FAILED\" and self.current_test is not None:\n self.finalize_test(False)\n\n if super().parse_line(line):\n return True\n\n return False\n\n\n@dataclass_json\n@dataclass\nclass TestRun:\n \"\"\"A single process that might contain many kernels, grouped into tests\"\"\"\n\n directory: str\n git: GitRev | None = None\n name: str | None = None\n command: str | None = None\n command_type: CommandType | None = None\n exit_code: int | None = None\n env: str | None = None\n gpu_names: str | None = None\n nvcc_version: str | None = None\n # map from name of test to list of kernel base filenames\n kernel_map: dict[str, CompiledTest] | None = None\n # collecting the preamble lets us skip it when diffing, and lets us compare\n # only the preamble between runs\n preamble: str | None = None\n # The following lets us skip preamble when loading kernels. Note that the\n # preamble can change length due to differing index types, so we can't rely\n # on f.seek()\n preamble_size_lines: int | None = None\n\n def __post_init__(self):\n if self.git is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n if not os.path.isdir(self.directory):\n print(f\"ERROR: {self.directory} does not name a directory\")\n sys.exit(1)\n\n try:\n self.name = (\n open(os.path.join(self.directory, \"run_name\"), \"r\").read().rstrip()\n )\n except FileNotFoundError:\n self.name = os.path.basename(self.directory)\n\n # get description of this git rev\n gitdiff = None\n try:\n gitdiff = open(os.path.join(self.directory, \"git_diff\"), \"r\").read()\n except FileNotFoundError:\n pass\n git_hash = open(os.path.join(self.directory, \"git_hash\"), \"r\").read().rstrip()\n self.git = GitRev(git_hash, diff=gitdiff)\n\n self.command = open(os.path.join(self.directory, \"command\"), \"r\").read()\n\n try:\n self.command_type = CommandType.from_string(\n open(os.path.join(self.directory, \"command_type\"), \"r\").read().rstrip()\n )\n except FileNotFoundError:\n print(\n f\"WARNING: Could not find {os.path.join(self.directory, 'command_type')}. \"\n \"Parsing as UNKNOWN command type means kernels will be ungrouped.\",\n file=sys.stderr,\n )\n self.command_type = CommandType.UNKNOWN\n\n try:\n self.env = \"\"\n for line in open(os.path.join(self.directory, \"env\"), \"r\").readlines():\n # remove $testdir which is set by compare_codegen.sh\n # NOTE: compare_codegen.sh should have already removed these lines\n if re.search(r\"^testdir=\", line) is None:\n self.env += line\n except FileNotFoundError:\n self.env = None\n\n try:\n self.nvcc_version = open(\n os.path.join(self.directory, \"nvcc_version\"), \"r\"\n ).read()\n except FileNotFoundError:\n self.nvcc_version = None\n\n try:\n self.gpu_names = list(\n open(os.path.join(self.directory, \"gpu_names\"), \"r\").readlines()\n )\n except FileNotFoundError:\n self.gpu_names = None\n\n self.exit_code = int(open(os.path.join(self.directory, \"exitcode\"), \"r\").read())\n\n self.compute_kernel_map()\n\n self.find_preamble()\n\n def compute_kernel_map(self):\n \"\"\"\n Compute a map from test name to list of cuda filenames\n \"\"\"\n logfile = os.path.join(self.directory, \"stdout\")\n if not os.path.isfile(logfile):\n raise RuntimeError(\n f\"Input directory {self.directory} contains no file named 'stdout'\"\n )\n\n if self.command_type == CommandType.GOOGLETEST:\n parser = LogParserGTest(logfile)\n elif self.command_type == CommandType.GOOGLEBENCH:\n parser = LogParserGBench(logfile)\n elif self.command_type == CommandType.PYTEST:\n parser = LogParserPyTest(logfile)\n else:\n # The base class provides a parser that groups everything into a\n # single \"test\" called \"Ungrouped Kernels\"\n parser = LogParser(logfile)\n\n self.kernel_map = parser.kernel_map\n\n def find_preamble(self):\n \"\"\"Look for common preamble in collected kernels\"\"\"\n preamble_lines = []\n first = True\n files_processed = 0 # limit how many files to check\n for cufile in os.listdir(os.path.join(self.directory, \"cuda\")):\n cufile_full = os.path.join(self.directory, \"cuda\", cufile)\n with open(cufile_full, \"r\") as f:\n for i, line in enumerate(f.readlines()):\n line = line.rstrip()\n # we set nvfuser_index_t in the preamble. We ignore that change for the purposes of this diff\n if line[:8] == \"typedef \" and line[-17:] == \" nvfuser_index_t;\":\n line = \"typedef int nvfuser_index_t; // NOTE: index type hard-coded as int for display only\"\n if re.search(r\"void (nvfuser|kernel)_?\\d+\\b\", line) is not None:\n # we arrived at the kernel definition\n break\n if first:\n preamble_lines.append(line)\n elif i >= len(preamble_lines) or preamble_lines[i] != line:\n break\n preamble_lines = preamble_lines[:i]\n if len(preamble_lines) == 0:\n # early return if preamble is determined to be empty\n break\n first = False\n files_processed += 1\n if files_processed >= 50:\n break\n self.preamble_size_lines = len(preamble_lines)\n self.preamble = \"\\n\".join(preamble_lines)\n\n def get_kernel(\n self, test_name, kernel_number, strip_preamble=True\n ) -> CompiledKernel:\n \"\"\"Get a string of the kernel, optionally stripping the preamble\"\"\"\n kern = self.kernel_map[test_name].kernels[kernel_number]\n basename = kern.filename\n if kern.code is not None:\n return kern\n fullname = os.path.join(self.directory, \"cuda\", basename)\n kern.code = \"\"\n with open(fullname, \"r\") as f:\n for i, line in enumerate(f.readlines()):\n if kern.index_type is None:\n m = re.search(r\"typedef\\s+(\\S*)\\s+nvfuser_index_t;\", line)\n if m is not None:\n kern.index_type = m.groups()[0]\n if not strip_preamble or i >= self.preamble_size_lines:\n # replace kernel934 with kernel1 to facilitate diffing\n # also match kernel_43 to handle new-style naming with static fusion count\n kern.code += re.sub(r\"\\bnvfuser_\\d+\\b\", \"nvfuser_N\", line)\n kern.code = kern.code.rstrip()\n if strip_preamble and kern.code[-1] == \"}\":\n # trailing curly brace is close of namespace. This will clean it up so that we have just the kernel\n kern.code = kern.code[:-1].rstrip()\n # find ptx file if it exists\n ptx_basename = os.path.splitext(basename)[0] + \".ptx\"\n ptx_fullname = os.path.join(self.directory, \"ptx\", ptx_basename)\n try:\n kern.ptx = open(ptx_fullname, \"r\").read().rstrip()\n except FileNotFoundError:\n pass\n return kern\n\n def join(self, other: \"TestRun\"):\n \"\"\"Concatenate other with self\"\"\"\n # Stuff that has to match\n assert self.git == other.git\n assert self.preamble_size_lines == other.preamble_size_lines\n assert self.preamble == other.preamble\n assert self.command_type == other.command_type\n\n # don't update name of this command\n\n # Append differing nvcc versions as new rows, otherwise keep equal\n if other.nvcc_version != self.nvcc_version:\n self.nvcc_version += other.nvcc_version\n\n # We expect the env to differ since we are probably joining after\n # running multiple shards on different nodes in parallel. So just\n # concatenate the envs, with a blank line between\n if other.env != self.env:\n self.env += f\"\\n{other.env}\"\n\n # keep a list of all GPUs involved\n self.gpu_names += other.gpu_names\n\n # concatenate command as if we ran the commands in sequence\n self.command += f\" && {other.command}\"\n\n # if one of the inputs is an error (non-zero), preserve it\n self.exit_code += other.exit_code\n\n # now merge the kernel maps with one another\n for test_name, test_obj in other.kernel_map.items():\n assert test_obj.name == test_name\n if test_name == \"Ungrouped Kernels\":\n if test_name in self.kernel_map:\n self.kernel_map[test_name].kernels += test_obj.kernels\n if not test_obj.passed:\n self.kernel_map[test_name].passed = False\n # Don't merge benchmark results. We should not have\n # ungrouped kernels with these fields anyway, since we\n # expect all kernels to fall under some benchmark if the\n # command_type is known to be a benchmark\n assert self.kernel_map[test_name].benchmark_result is None\n assert test_obj.benchmark_result is None\n continue\n else:\n assert (\n test_name not in self.kernel_map\n ), f\"Cannot join test runs containing the same test {test_name}\"\n self.kernel_map[test_name] = test_obj\n\n\n@dataclass_json\n@dataclass\nclass KernelDiff:\n testname: str\n kernel_num: int\n kernel1: CompiledKernel\n kernel2: CompiledKernel\n diff_lines: InitVar[list[str]] = []\n ptx_diff_lines: InitVar[list[str] | None] = []\n new_lines: int = 0\n removed_lines: int = 0\n ptx_diff: str | None = None\n new_ptx_lines: int = 0\n removed_ptx_lines: int = 0\n diff: str | None = None\n\n def __post_init__(self, diff_lines: list[str], ptx_diff_lines: list[str] | None):\n if self.diff is not None:","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.KernelDiff","uri":"program://Fuser/class/tools.codediff.codediff.KernelDiff#L684-L718","kind":"class","name":"KernelDiff","path":"tools/codediff/codediff.py","language":"python","start_line":684,"end_line":718,"context_start_line":664,"context_end_line":738,"code":" if test_name in self.kernel_map:\n self.kernel_map[test_name].kernels += test_obj.kernels\n if not test_obj.passed:\n self.kernel_map[test_name].passed = False\n # Don't merge benchmark results. We should not have\n # ungrouped kernels with these fields anyway, since we\n # expect all kernels to fall under some benchmark if the\n # command_type is known to be a benchmark\n assert self.kernel_map[test_name].benchmark_result is None\n assert test_obj.benchmark_result is None\n continue\n else:\n assert (\n test_name not in self.kernel_map\n ), f\"Cannot join test runs containing the same test {test_name}\"\n self.kernel_map[test_name] = test_obj\n\n\n@dataclass_json\n@dataclass\nclass KernelDiff:\n testname: str\n kernel_num: int\n kernel1: CompiledKernel\n kernel2: CompiledKernel\n diff_lines: InitVar[list[str]] = []\n ptx_diff_lines: InitVar[list[str] | None] = []\n new_lines: int = 0\n removed_lines: int = 0\n ptx_diff: str | None = None\n new_ptx_lines: int = 0\n removed_ptx_lines: int = 0\n diff: str | None = None\n\n def __post_init__(self, diff_lines: list[str], ptx_diff_lines: list[str] | None):\n if self.diff is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n self.diff = \"\\n\".join(diff_lines)\n\n for line in diff_lines:\n if line[:2] == \"+ \":\n self.new_lines += 1\n elif line[:2] == \"- \":\n self.removed_lines += 1\n\n if ptx_diff_lines is not None:\n self.ptx_diff = \"\\n\".join(ptx_diff_lines)\n\n for line in ptx_diff_lines:\n if line[:2] == \"+ \":\n self.new_ptx_lines += 1\n elif line[:2] == \"- \":\n self.removed_ptx_lines += 1\n\n\n@dataclass_json\n@dataclass\nclass TestDiff:\n testname: str\n test1: CompiledTest\n test2: CompiledTest\n kernel_diffs: list[KernelDiff] | None = None\n\n\nfilename_pattern = re.compile(r\"__tmp_\\w+\")\nkernel_pattern = re.compile(r\"(?Pkernel|nvfuser)_\\d+\")\n\n\ndef sanitize_symbol_name(symb: str) -> str:\n \"\"\"\n Replace mangled kernel names like\n _ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_\n or","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.TestDiff","uri":"program://Fuser/class/tools.codediff.codediff.TestDiff#L723-L727","kind":"class","name":"TestDiff","path":"tools/codediff/codediff.py","language":"python","start_line":723,"end_line":727,"context_start_line":703,"context_end_line":747,"code":" self.diff = \"\\n\".join(diff_lines)\n\n for line in diff_lines:\n if line[:2] == \"+ \":\n self.new_lines += 1\n elif line[:2] == \"- \":\n self.removed_lines += 1\n\n if ptx_diff_lines is not None:\n self.ptx_diff = \"\\n\".join(ptx_diff_lines)\n\n for line in ptx_diff_lines:\n if line[:2] == \"+ \":\n self.new_ptx_lines += 1\n elif line[:2] == \"- \":\n self.removed_ptx_lines += 1\n\n\n@dataclass_json\n@dataclass\nclass TestDiff:\n testname: str\n test1: CompiledTest\n test2: CompiledTest\n kernel_diffs: list[KernelDiff] | None = None\n\n\nfilename_pattern = re.compile(r\"__tmp_\\w+\")\nkernel_pattern = re.compile(r\"(?Pkernel|nvfuser)_\\d+\")\n\n\ndef sanitize_symbol_name(symb: str) -> str:\n \"\"\"\n Replace mangled kernel names like\n _ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_\n or\n _ZN76_GLOBAL__N__00000000_37___tmp_kernel_4_cu_8995cef2_3255329nvfuser_4ENS_6TensorIfLi2ELi2EEES1_S1_\n\n This function first demangles the name, then parses each piece to check\n for common patterns to replace. This lets us replace stuff like \"kernel_4\"\n with \"kernel_N\" or \"nvfuser_4\" with \"nvfuser_N\". Note that this does not\n \"mangle\" the name back since there does not seem to be a useful utility\n for doing so and cxxfilt only does demangling. As this is only for diff\n purposes, the report will only show the demangled names in the diff\n portions, but clicking on the original code will show the actual original","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.sanitize_symbol_name","uri":"program://Fuser/function/tools.codediff.codediff.sanitize_symbol_name#L734-L769","kind":"function","name":"sanitize_symbol_name","path":"tools/codediff/codediff.py","language":"python","start_line":734,"end_line":769,"context_start_line":714,"context_end_line":789,"code":" for line in ptx_diff_lines:\n if line[:2] == \"+ \":\n self.new_ptx_lines += 1\n elif line[:2] == \"- \":\n self.removed_ptx_lines += 1\n\n\n@dataclass_json\n@dataclass\nclass TestDiff:\n testname: str\n test1: CompiledTest\n test2: CompiledTest\n kernel_diffs: list[KernelDiff] | None = None\n\n\nfilename_pattern = re.compile(r\"__tmp_\\w+\")\nkernel_pattern = re.compile(r\"(?Pkernel|nvfuser)_\\d+\")\n\n\ndef sanitize_symbol_name(symb: str) -> str:\n \"\"\"\n Replace mangled kernel names like\n _ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_\n or\n _ZN76_GLOBAL__N__00000000_37___tmp_kernel_4_cu_8995cef2_3255329nvfuser_4ENS_6TensorIfLi2ELi2EEES1_S1_\n\n This function first demangles the name, then parses each piece to check\n for common patterns to replace. This lets us replace stuff like \"kernel_4\"\n with \"kernel_N\" or \"nvfuser_4\" with \"nvfuser_N\". Note that this does not\n \"mangle\" the name back since there does not seem to be a useful utility\n for doing so and cxxfilt only does demangling. As this is only for diff\n purposes, the report will only show the demangled names in the diff\n portions, but clicking on the original code will show the actual original\n mangled symbol names.\n \"\"\"\n suffix = \"\"\n while len(symb) > 0:\n # PTX sometimes refers to local variables as\n # _. For example,\n # ZN3nvf9nvfuser_8ENS_6TensorINS_6__halfELi3ELi3EEES2_NS_9TensorMapES3_NS0_IS1_Li2ELi2EEE_param_4\n # Represents\n # nvf::nvfuser_8(nvf::Tensor, nvf::Tensor, nvf::TensorMap, nvf::TensorMap, nvf::Tensor)_param_4\n # Here we loop, cutting off more and more suffix until we are able to\n # demangle in order to demangle to something like the above\n try:\n d = cxxfilt.demangle(symb)\n break\n except cxxfilt.InvalidName:\n suffix = symb[-1] + suffix\n symb = symb[:-1]\n # Replace \"__tmp_kernel_pointwise_f0_c1_r0_g0_cu\" or \"__tmp_kernel_4\" with \"__tmp_filename\"\n d = re.sub(filename_pattern, \"__tmp_filename\", d)\n # Replace \"kernel_4\" or \"nvfuser_8\" with \"kernel_N\"\n d = re.sub(kernel_pattern, lambda m: f\"{m.groupdict()['prefix']}_N\", d)\n return d + suffix\n\n\n# Mangled symbol names start with _Z in the Itanium ABI\n# https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling\nsymbol_pattern = re.compile(r\"\\b_Z\\w+\\b\")\ncomment_pattern = re.compile(r\"//.*$\")\n\n\ndef sanitize_ptx_lines(lines: list[str]) -> list[str]:\n \"\"\"Remove comments and remove kernel id\"\"\"\n sanitary_lines = []\n for l in lines:\n l = re.sub(symbol_pattern, lambda m: sanitize_symbol_name(m.group()), l)\n\n # Remove comments. This fixes mismatches in PTX \"callseq\" comments, which appear to be non-repeatable.\n l = re.sub(comment_pattern, \"\", l)\n sanitary_lines.append(l)\n return sanitary_lines\n\n","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.sanitize_ptx_lines","uri":"program://Fuser/function/tools.codediff.codediff.sanitize_ptx_lines#L778-L787","kind":"function","name":"sanitize_ptx_lines","path":"tools/codediff/codediff.py","language":"python","start_line":778,"end_line":787,"context_start_line":758,"context_end_line":807,"code":" # demangle in order to demangle to something like the above\n try:\n d = cxxfilt.demangle(symb)\n break\n except cxxfilt.InvalidName:\n suffix = symb[-1] + suffix\n symb = symb[:-1]\n # Replace \"__tmp_kernel_pointwise_f0_c1_r0_g0_cu\" or \"__tmp_kernel_4\" with \"__tmp_filename\"\n d = re.sub(filename_pattern, \"__tmp_filename\", d)\n # Replace \"kernel_4\" or \"nvfuser_8\" with \"kernel_N\"\n d = re.sub(kernel_pattern, lambda m: f\"{m.groupdict()['prefix']}_N\", d)\n return d + suffix\n\n\n# Mangled symbol names start with _Z in the Itanium ABI\n# https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling\nsymbol_pattern = re.compile(r\"\\b_Z\\w+\\b\")\ncomment_pattern = re.compile(r\"//.*$\")\n\n\ndef sanitize_ptx_lines(lines: list[str]) -> list[str]:\n \"\"\"Remove comments and remove kernel id\"\"\"\n sanitary_lines = []\n for l in lines:\n l = re.sub(symbol_pattern, lambda m: sanitize_symbol_name(m.group()), l)\n\n # Remove comments. This fixes mismatches in PTX \"callseq\" comments, which appear to be non-repeatable.\n l = re.sub(comment_pattern, \"\", l)\n sanitary_lines.append(l)\n return sanitary_lines\n\n\n@dataclass_json\n@dataclass\nclass TestDifferences:\n run1: TestRun\n run2: TestRun\n # either a list of diffs, or different numbers of kernels present\n test_diffs: list[TestDiff] = field(default_factory=list)\n new_tests: list[CompiledTest] = field(default_factory=list)\n removed_tests: list[CompiledTest] = field(default_factory=list)\n total_num_diffs: int = 0\n show_diffs: InitVar[bool] = False\n inclusion_criterion: InitVar[str] = \"mismatched_cuda_or_ptx\"\n preamble_diff: str | None = None\n env_diff: str | None = None\n\n def __post_init__(self, show_diffs: bool, kernel_inclusion_criterion: str):\n if self.preamble_diff is not None:\n # Avoid running __post_init__ during deserialization","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.TestDifferences","uri":"program://Fuser/class/tools.codediff.codediff.TestDifferences#L792-L985","kind":"class","name":"TestDifferences","path":"tools/codediff/codediff.py","language":"python","start_line":792,"end_line":985,"context_start_line":772,"context_end_line":1005,"code":"# Mangled symbol names start with _Z in the Itanium ABI\n# https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling\nsymbol_pattern = re.compile(r\"\\b_Z\\w+\\b\")\ncomment_pattern = re.compile(r\"//.*$\")\n\n\ndef sanitize_ptx_lines(lines: list[str]) -> list[str]:\n \"\"\"Remove comments and remove kernel id\"\"\"\n sanitary_lines = []\n for l in lines:\n l = re.sub(symbol_pattern, lambda m: sanitize_symbol_name(m.group()), l)\n\n # Remove comments. This fixes mismatches in PTX \"callseq\" comments, which appear to be non-repeatable.\n l = re.sub(comment_pattern, \"\", l)\n sanitary_lines.append(l)\n return sanitary_lines\n\n\n@dataclass_json\n@dataclass\nclass TestDifferences:\n run1: TestRun\n run2: TestRun\n # either a list of diffs, or different numbers of kernels present\n test_diffs: list[TestDiff] = field(default_factory=list)\n new_tests: list[CompiledTest] = field(default_factory=list)\n removed_tests: list[CompiledTest] = field(default_factory=list)\n total_num_diffs: int = 0\n show_diffs: InitVar[bool] = False\n inclusion_criterion: InitVar[str] = \"mismatched_cuda_or_ptx\"\n preamble_diff: str | None = None\n env_diff: str | None = None\n\n def __post_init__(self, show_diffs: bool, kernel_inclusion_criterion: str):\n if self.preamble_diff is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n if self.run1.command != self.run2.command:\n print(\"WARNING: commands differ between runs\", file=sys.stderr)\n print(f\" {self.run1.directory}: {self.run1.command}\", file=sys.stderr)\n print(f\" {self.run2.directory}: {self.run2.command}\", file=sys.stderr)\n\n if self.run1.exit_code != self.run1.exit_code:\n print(\n f\"WARNING: Exit codes {self.run1.exit_code} and {self.run2.exit_code} do not match.\",\n file=sys.stderr,\n )\n\n self.preamble_diff = \"\\n\".join(\n difflib.unified_diff(\n self.run1.preamble.splitlines(),\n self.run2.preamble.splitlines(),\n fromfile=self.run1.name,\n tofile=self.run2.name,\n n=5,\n )\n )\n if len(self.preamble_diff) > 0:\n print(\"Preambles differ between runs indicating changes to runtime files\")\n\n self.env_diff = \"\\n\".join(\n difflib.unified_diff(\n self.run1.env.splitlines(),\n self.run2.env.splitlines(),\n fromfile=self.run1.name,\n tofile=self.run2.name,\n n=5,\n )\n )\n\n for testname, compiled_test1 in self.run1.kernel_map.items():\n if testname not in self.run2.kernel_map:\n compiled_test1.kernels = [\n self.run1.get_kernel(testname, i)\n for i in range(len(compiled_test1.kernels))\n ]\n self.removed_tests.append(compiled_test1)\n continue\n\n compiled_test2 = self.run2.kernel_map[testname]\n\n test1_kernel_count = len(compiled_test1.kernels)\n test2_kernel_count = len(compiled_test2.kernels)\n minimum_kernel_count = min(test1_kernel_count, test2_kernel_count)\n if test1_kernel_count != test2_kernel_count:\n print(\n f\"WARNING: Test {testname} has {test1_kernel_count} kernels \"\n f\"in {self.run1.directory} and {test2_kernel_count} kernels in {self.run2.directory}. \"\n f\"Only showing diffs for the first {minimum_kernel_count} kernels in this test.\",\n file=sys.stderr,\n )\n self.test_diffs.append(\n TestDiff(\n testname,\n compiled_test1,\n compiled_test2,\n None,\n )\n )\n\n kernel_diffs = []\n for kernel_num in range(minimum_kernel_count):\n kern1 = self.run1.get_kernel(testname, kernel_num, strip_preamble=True)\n kern2 = self.run2.get_kernel(testname, kernel_num, strip_preamble=True)\n assert kern1.code is not None\n assert kern2.code is not None\n\n ptx_diff_lines = None\n if kern1.ptx is not None and kern2.ptx is not None:\n ptx_diff_lines = list(\n difflib.unified_diff(\n sanitize_ptx_lines(kern1.ptx.splitlines()),\n sanitize_ptx_lines(kern2.ptx.splitlines()),\n fromfile=self.run1.name,\n tofile=self.run2.name,\n n=5,\n )\n )\n\n diff_lines = list(\n difflib.unified_diff(\n kern1.code.splitlines(),\n kern2.code.splitlines(),\n fromfile=self.run1.name,\n tofile=self.run2.name,\n n=5,\n )\n )\n if (\n kernel_inclusion_criterion == \"all\"\n or (\n kernel_inclusion_criterion == \"mismatched_cuda_or_ptx\"\n and diff_lines is not None\n and len(diff_lines) > 0\n )\n or (\n kernel_inclusion_criterion\n in [\"mismatched_cuda_or_ptx\", \"mismatched_ptx\"]\n and ptx_diff_lines is not None\n and len(ptx_diff_lines) > 0\n )\n ):\n kd = KernelDiff(\n testname,\n kernel_num + 1,\n kern1,\n kern2,\n diff_lines,\n ptx_diff_lines=ptx_diff_lines,\n )\n if show_diffs:\n print(testname, kernel_num, kd.diff)\n self.total_num_diffs += 1\n kernel_diffs.append(kd)\n\n if len(kernel_diffs) > 0:\n self.test_diffs.append(\n TestDiff(\n testname,\n compiled_test1,\n compiled_test2,\n kernel_diffs,\n )\n )\n\n for testname, compiled_test2 in self.run2.kernel_map.items():\n if testname not in self.run1.kernel_map:\n compiled_test2.kernels = [\n self.run2.get_kernel(testname, i)\n for i in range(len(compiled_test2.kernels))\n ]\n self.new_tests.append(compiled_test2)\n\n def hide_env(self):\n \"\"\"Remove private information like env vars and lib versions\"\"\"\n self.run1.env = None\n self.run2.env = None\n self.run1.nvcc_version = None\n self.run2.nvcc_version = None\n\n def generate_html(self, omit_preamble: bool, max_diffs: bool) -> str:\n \"\"\"Return a self-contained HTML string summarizing the codegen comparison\"\"\"\n import jinja2\n\n tools_dir = os.path.dirname(__file__)\n template_dir = os.path.join(tools_dir, \"templates\")\n env = jinja2.Environment(\n loader=jinja2.FileSystemLoader(searchpath=template_dir)\n )\n template = env.get_template(\"codediff.html\")\n # dict_factory lets us provide custom serializations for classes like Enums\n # https://stackoverflow.com/questions/61338539/how-to-use-enum-value-in-asdict-function-from-dataclasses-module\n context = asdict(\n self,\n dict_factory=lambda data: {\n # Serialize CommandType as string so that jinja can recognize it\n field: value.name if isinstance(value, CommandType) else value\n for field, value in data\n },\n )\n context[\"omit_preamble\"] = omit_preamble\n context[\"max_diffs\"] = max_diffs\n head_hash = (\n subprocess.run([\"git\", \"rev-parse\", \"HEAD\"], capture_output=True)\n .stdout.strip()\n .decode(\"utf-8\")\n )\n context[\"tool_git\"] = GitRev(head_hash)\n context[\"explain_api_url\"] = os.environ.get(\n \"CODEDIFF_EXPLAIN_API_URL\", \"/api/explain-diff\"\n )\n\n return template.render(context)\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n subparsers = parser.add_subparsers(title=\"verb\")\n\n parse_parser = subparsers.add_parser(\n \"parse\", help=\"Parse an output directory of run_command.sh into a JSON file\"\n )\n parse_parser.add_argument(\n \"dir\",\n help=\"Directory containing 'stdout' and 'cuda/' resulting from run_command.sh\",\n )\n parse_parser.add_argument(\"output_json\", help=\"Location to write JSON file\")\n\n def parse_dir(args: dict):","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.__post_init__","uri":"program://Fuser/function/tools.codediff.codediff.__post_init__#L805-L944","kind":"function","name":"__post_init__","path":"tools/codediff/codediff.py","language":"python","start_line":805,"end_line":944,"context_start_line":785,"context_end_line":964,"code":" l = re.sub(comment_pattern, \"\", l)\n sanitary_lines.append(l)\n return sanitary_lines\n\n\n@dataclass_json\n@dataclass\nclass TestDifferences:\n run1: TestRun\n run2: TestRun\n # either a list of diffs, or different numbers of kernels present\n test_diffs: list[TestDiff] = field(default_factory=list)\n new_tests: list[CompiledTest] = field(default_factory=list)\n removed_tests: list[CompiledTest] = field(default_factory=list)\n total_num_diffs: int = 0\n show_diffs: InitVar[bool] = False\n inclusion_criterion: InitVar[str] = \"mismatched_cuda_or_ptx\"\n preamble_diff: str | None = None\n env_diff: str | None = None\n\n def __post_init__(self, show_diffs: bool, kernel_inclusion_criterion: str):\n if self.preamble_diff is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n if self.run1.command != self.run2.command:\n print(\"WARNING: commands differ between runs\", file=sys.stderr)\n print(f\" {self.run1.directory}: {self.run1.command}\", file=sys.stderr)\n print(f\" {self.run2.directory}: {self.run2.command}\", file=sys.stderr)\n\n if self.run1.exit_code != self.run1.exit_code:\n print(\n f\"WARNING: Exit codes {self.run1.exit_code} and {self.run2.exit_code} do not match.\",\n file=sys.stderr,\n )\n\n self.preamble_diff = \"\\n\".join(\n difflib.unified_diff(\n self.run1.preamble.splitlines(),\n self.run2.preamble.splitlines(),\n fromfile=self.run1.name,\n tofile=self.run2.name,\n n=5,\n )\n )\n if len(self.preamble_diff) > 0:\n print(\"Preambles differ between runs indicating changes to runtime files\")\n\n self.env_diff = \"\\n\".join(\n difflib.unified_diff(\n self.run1.env.splitlines(),\n self.run2.env.splitlines(),\n fromfile=self.run1.name,\n tofile=self.run2.name,\n n=5,\n )\n )\n\n for testname, compiled_test1 in self.run1.kernel_map.items():\n if testname not in self.run2.kernel_map:\n compiled_test1.kernels = [\n self.run1.get_kernel(testname, i)\n for i in range(len(compiled_test1.kernels))\n ]\n self.removed_tests.append(compiled_test1)\n continue\n\n compiled_test2 = self.run2.kernel_map[testname]\n\n test1_kernel_count = len(compiled_test1.kernels)\n test2_kernel_count = len(compiled_test2.kernels)\n minimum_kernel_count = min(test1_kernel_count, test2_kernel_count)\n if test1_kernel_count != test2_kernel_count:\n print(\n f\"WARNING: Test {testname} has {test1_kernel_count} kernels \"\n f\"in {self.run1.directory} and {test2_kernel_count} kernels in {self.run2.directory}. \"\n f\"Only showing diffs for the first {minimum_kernel_count} kernels in this test.\",\n file=sys.stderr,\n )\n self.test_diffs.append(\n TestDiff(\n testname,\n compiled_test1,\n compiled_test2,\n None,\n )\n )\n\n kernel_diffs = []\n for kernel_num in range(minimum_kernel_count):\n kern1 = self.run1.get_kernel(testname, kernel_num, strip_preamble=True)\n kern2 = self.run2.get_kernel(testname, kernel_num, strip_preamble=True)\n assert kern1.code is not None\n assert kern2.code is not None\n\n ptx_diff_lines = None\n if kern1.ptx is not None and kern2.ptx is not None:\n ptx_diff_lines = list(\n difflib.unified_diff(\n sanitize_ptx_lines(kern1.ptx.splitlines()),\n sanitize_ptx_lines(kern2.ptx.splitlines()),\n fromfile=self.run1.name,\n tofile=self.run2.name,\n n=5,\n )\n )\n\n diff_lines = list(\n difflib.unified_diff(\n kern1.code.splitlines(),\n kern2.code.splitlines(),\n fromfile=self.run1.name,\n tofile=self.run2.name,\n n=5,\n )\n )\n if (\n kernel_inclusion_criterion == \"all\"\n or (\n kernel_inclusion_criterion == \"mismatched_cuda_or_ptx\"\n and diff_lines is not None\n and len(diff_lines) > 0\n )\n or (\n kernel_inclusion_criterion\n in [\"mismatched_cuda_or_ptx\", \"mismatched_ptx\"]\n and ptx_diff_lines is not None\n and len(ptx_diff_lines) > 0\n )\n ):\n kd = KernelDiff(\n testname,\n kernel_num + 1,\n kern1,\n kern2,\n diff_lines,\n ptx_diff_lines=ptx_diff_lines,\n )\n if show_diffs:\n print(testname, kernel_num, kd.diff)\n self.total_num_diffs += 1\n kernel_diffs.append(kd)\n\n if len(kernel_diffs) > 0:\n self.test_diffs.append(\n TestDiff(\n testname,\n compiled_test1,\n compiled_test2,\n kernel_diffs,\n )\n )\n\n for testname, compiled_test2 in self.run2.kernel_map.items():\n if testname not in self.run1.kernel_map:\n compiled_test2.kernels = [\n self.run2.get_kernel(testname, i)\n for i in range(len(compiled_test2.kernels))\n ]\n self.new_tests.append(compiled_test2)\n\n def hide_env(self):\n \"\"\"Remove private information like env vars and lib versions\"\"\"\n self.run1.env = None\n self.run2.env = None\n self.run1.nvcc_version = None\n self.run2.nvcc_version = None\n\n def generate_html(self, omit_preamble: bool, max_diffs: bool) -> str:\n \"\"\"Return a self-contained HTML string summarizing the codegen comparison\"\"\"\n import jinja2\n\n tools_dir = os.path.dirname(__file__)\n template_dir = os.path.join(tools_dir, \"templates\")\n env = jinja2.Environment(\n loader=jinja2.FileSystemLoader(searchpath=template_dir)\n )\n template = env.get_template(\"codediff.html\")\n # dict_factory lets us provide custom serializations for classes like Enums\n # https://stackoverflow.com/questions/61338539/how-to-use-enum-value-in-asdict-function-from-dataclasses-module","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.parse_ptxas","uri":"program://Fuser/function/tools.codediff.codediff.parse_ptxas#L132-L175","kind":"function","name":"parse_ptxas","path":"tools/codediff/codediff.py","language":"python","start_line":132,"end_line":175,"context_start_line":112,"context_end_line":195,"code":" launch_params: LaunchParams | None = None\n gmem_bytes: int = 0\n smem_bytes: int = 0\n cmem_bank_bytes: list[int] | None = None\n registers: int | None = None\n stack_frame_bytes: int = 0\n spill_store_bytes: int = 0\n spill_load_bytes: int = 0\n mangled_name: str | None = None\n arch: str | None = None\n index_type: str | None = None\n\n def __post_init__(self):\n if self.launch_params is not None:\n # Avoid running __post_init__ during deserialization\n return\n\n self.parse_ptxas()\n self.parse_launch_params()\n\n def parse_ptxas(self):\n # Example input:\n #\n # ptxas info : 307 bytes gmem\n # ptxas info : Compiling entry function\n # '_ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_'\n # for 'sm_86'\n # ptxas info : Function properties for\n # _ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_\n # ptxas . 0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads\n # ptxas info : Used 203 registers, 16 bytes smem, 472 bytes cmem[0], 8 bytes cmem[2]\n #\n # Here we parse this into the fields presented, and we replace the\n # mangled kernel name since it includes the kernel number and is\n # useless for the purposes of diffing since the kernel signature is\n # already included.\n if self.ptxas_info is None:\n return\n\n m = re.search(r\"Compiling entry function '(.*)' for '(.*)'\", self.ptxas_info)\n if m is not None:\n self.mangled_name, self.arch = m.groups()\n\n def find_unique_int(pattern) -> int | None:\n assert self.ptxas_info is not None\n m = re.search(pattern, self.ptxas_info)\n return 0 if m is None else int(m.groups()[0])\n\n self.stack_frame_bytes = find_unique_int(r\"(\\d+) bytes stack frame\")\n self.spill_store_bytes = find_unique_int(r\"(\\d+) bytes spill stores\")\n self.spill_load_bytes = find_unique_int(r\"(\\d+) bytes spill loads\")\n self.registers = find_unique_int(r\"(\\d+) registers\")\n self.gmem_bytes = find_unique_int(r\"(\\d+) bytes gmem\")\n self.smem_bytes = find_unique_int(r\"(\\d+) bytes smem\")\n\n self.cmem_bank_bytes = []\n cmem_banks = 0\n for m in re.finditer(r\"(\\d+) bytes cmem\\[(\\d+)\\]\", self.ptxas_info):\n nbytes_str, bank_str = m.groups()\n bank = int(bank_str)\n if len(self.cmem_bank_bytes) <= bank:\n self.cmem_bank_bytes += [0] * (bank + 1 - len(self.cmem_bank_bytes))\n self.cmem_bank_bytes[bank] = int(nbytes_str)\n cmem_banks += 1\n\n def parse_launch_params(self):\n # If NVFUSER_DUMP=launch_param is given we will get a line like this for every launch:\n # Launch Parameters: BlockDim.x = 32, BlockDim.y = 2, BlockDim.z = 2, GridDim.x = 8, GridDim.y = 8, GridDim.z = -1, Smem Size = 49152\n # This is not done by default since we might have hundreds of thousands of these lines.\n # Still, if we recognize it, we will parse this info. If there are\n # multiple lines, we just check that they are all equal and if not then\n # we keep the first version and print a warning.\n if self.launch_params_str is None:\n return\n\n self.launch_params = None\n for line in self.launch_params_str.splitlines():\n m = re.search(\n r\"Launch Parameters: BlockDim.x = (.*), BlockDim.y = (.*), BlockDim.z = (.*), \"\n r\"GridDim.x = (.*), GridDim.y = (.*), GridDim.z = (.*), Smem Size = (.*)$\",\n line,\n )\n bx, by, bz, gx, gy, gz, s = m.groups()\n lp = LaunchParams((bx, by, bz), (gx, gy, gz), s)","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.parse_launch_params","uri":"program://Fuser/function/tools.codediff.codediff.parse_launch_params#L177-L201","kind":"function","name":"parse_launch_params","path":"tools/codediff/codediff.py","language":"python","start_line":177,"end_line":201,"context_start_line":157,"context_end_line":221,"code":" m = re.search(pattern, self.ptxas_info)\n return 0 if m is None else int(m.groups()[0])\n\n self.stack_frame_bytes = find_unique_int(r\"(\\d+) bytes stack frame\")\n self.spill_store_bytes = find_unique_int(r\"(\\d+) bytes spill stores\")\n self.spill_load_bytes = find_unique_int(r\"(\\d+) bytes spill loads\")\n self.registers = find_unique_int(r\"(\\d+) registers\")\n self.gmem_bytes = find_unique_int(r\"(\\d+) bytes gmem\")\n self.smem_bytes = find_unique_int(r\"(\\d+) bytes smem\")\n\n self.cmem_bank_bytes = []\n cmem_banks = 0\n for m in re.finditer(r\"(\\d+) bytes cmem\\[(\\d+)\\]\", self.ptxas_info):\n nbytes_str, bank_str = m.groups()\n bank = int(bank_str)\n if len(self.cmem_bank_bytes) <= bank:\n self.cmem_bank_bytes += [0] * (bank + 1 - len(self.cmem_bank_bytes))\n self.cmem_bank_bytes[bank] = int(nbytes_str)\n cmem_banks += 1\n\n def parse_launch_params(self):\n # If NVFUSER_DUMP=launch_param is given we will get a line like this for every launch:\n # Launch Parameters: BlockDim.x = 32, BlockDim.y = 2, BlockDim.z = 2, GridDim.x = 8, GridDim.y = 8, GridDim.z = -1, Smem Size = 49152\n # This is not done by default since we might have hundreds of thousands of these lines.\n # Still, if we recognize it, we will parse this info. If there are\n # multiple lines, we just check that they are all equal and if not then\n # we keep the first version and print a warning.\n if self.launch_params_str is None:\n return\n\n self.launch_params = None\n for line in self.launch_params_str.splitlines():\n m = re.search(\n r\"Launch Parameters: BlockDim.x = (.*), BlockDim.y = (.*), BlockDim.z = (.*), \"\n r\"GridDim.x = (.*), GridDim.y = (.*), GridDim.z = (.*), Smem Size = (.*)$\",\n line,\n )\n bx, by, bz, gx, gy, gz, s = m.groups()\n lp = LaunchParams((bx, by, bz), (gx, gy, gz), s)\n if self.launch_params is None:\n self.launch_params = lp\n else:\n if lp != self.launch_params:\n # Found multiple mismatched launch params for one kernel. Only using first\n return\n\n\n@dataclass_json\n@dataclass\nclass BenchmarkResult:\n gpu_time: float\n gpu_time_unit: str\n cpu_time: float\n cpu_time_unit: float\n iterations: int | None = None\n\n\n@dataclass_json\n@dataclass\nclass CompiledTest:\n \"\"\"One grouping of kernels. A run holds multiple of these\"\"\"\n\n name: str\n kernels: list[CompiledKernel]\n passed: bool = True","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.__str__","uri":"program://Fuser/function/tools.codediff.codediff.__str__#L233-L234","kind":"function","name":"__str__","path":"tools/codediff/codediff.py","language":"python","start_line":233,"end_line":234,"context_start_line":213,"context_end_line":254,"code":"\n@dataclass_json\n@dataclass\nclass CompiledTest:\n \"\"\"One grouping of kernels. A run holds multiple of these\"\"\"\n\n name: str\n kernels: list[CompiledKernel]\n passed: bool = True\n benchmark_result: BenchmarkResult | None = None\n\n\nclass CommandType(str, Enum):\n \"\"\"Denotes what type of command was run\"\"\"\n\n UNKNOWN = \"UNKNOWN\"\n GOOGLETEST = \"GOOGLETEST\"\n GOOGLEBENCH = \"GOOGLEBENCH\"\n PYTEST = \"PYTEST\"\n\n def __str__(self):\n return self.name\n\n @classmethod\n def from_string(cls, type_str: str):\n l = type_str.lower()\n if l[:3] == \"unk\":\n # Specified unknown. Don't print warning\n return cls.UNKNOWN\n elif l == \"gtest\" or l == \"googletest\":\n return cls.GOOGLETEST\n elif l == \"gbench\" or l == \"googlebench\":\n return cls.GOOGLEBENCH\n elif l == \"pytest\":\n return cls.PYTEST\n else:\n print(\n f\"WARNING: Unrecognized command type '{type_str}'. Parsing as UNKNOWN.\",\n file=sys.stderr,\n )\n return cls.UNKNOWN\n","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.from_string","uri":"program://Fuser/function/tools.codediff.codediff.from_string#L237-L253","kind":"function","name":"from_string","path":"tools/codediff/codediff.py","language":"python","start_line":237,"end_line":253,"context_start_line":217,"context_end_line":273,"code":" \"\"\"One grouping of kernels. A run holds multiple of these\"\"\"\n\n name: str\n kernels: list[CompiledKernel]\n passed: bool = True\n benchmark_result: BenchmarkResult | None = None\n\n\nclass CommandType(str, Enum):\n \"\"\"Denotes what type of command was run\"\"\"\n\n UNKNOWN = \"UNKNOWN\"\n GOOGLETEST = \"GOOGLETEST\"\n GOOGLEBENCH = \"GOOGLEBENCH\"\n PYTEST = \"PYTEST\"\n\n def __str__(self):\n return self.name\n\n @classmethod\n def from_string(cls, type_str: str):\n l = type_str.lower()\n if l[:3] == \"unk\":\n # Specified unknown. Don't print warning\n return cls.UNKNOWN\n elif l == \"gtest\" or l == \"googletest\":\n return cls.GOOGLETEST\n elif l == \"gbench\" or l == \"googlebench\":\n return cls.GOOGLEBENCH\n elif l == \"pytest\":\n return cls.PYTEST\n else:\n print(\n f\"WARNING: Unrecognized command type '{type_str}'. Parsing as UNKNOWN.\",\n file=sys.stderr,\n )\n return cls.UNKNOWN\n\n\nclass LogParser:\n \"\"\"General parser for STDOUT of NVFuser commands\n\n This parser does not group into individual tests, but rather places all\n kernels into a single CompiledTest whose name is \"Ungrouped Kernels\".\n \"\"\"\n\n def __init__(self, log_file: str):\n self.compile_regex()\n\n self.kernel_map: dict[str, CompiledTest] = {}\n\n self.reset_test_state()\n\n self.parse(log_file)\n\n def compile_regex(self):\n # regex for stripping ANSI color codes","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.__init__","uri":"program://Fuser/function/tools.codediff.codediff.__init__#L263-L270","kind":"function","name":"__init__","path":"tools/codediff/codediff.py","language":"python","start_line":263,"end_line":270,"context_start_line":243,"context_end_line":290,"code":" return cls.GOOGLETEST\n elif l == \"gbench\" or l == \"googlebench\":\n return cls.GOOGLEBENCH\n elif l == \"pytest\":\n return cls.PYTEST\n else:\n print(\n f\"WARNING: Unrecognized command type '{type_str}'. Parsing as UNKNOWN.\",\n file=sys.stderr,\n )\n return cls.UNKNOWN\n\n\nclass LogParser:\n \"\"\"General parser for STDOUT of NVFuser commands\n\n This parser does not group into individual tests, but rather places all\n kernels into a single CompiledTest whose name is \"Ungrouped Kernels\".\n \"\"\"\n\n def __init__(self, log_file: str):\n self.compile_regex()\n\n self.kernel_map: dict[str, CompiledTest] = {}\n\n self.reset_test_state()\n\n self.parse(log_file)\n\n def compile_regex(self):\n # regex for stripping ANSI color codes\n self.ansi_re = re.compile(r\"(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]\")\n\n def reset_kernel_state(self):\n self.current_file = None\n self.ptxas_info = \"\"\n self.launch_params_str = \"\"\n\n def reset_test_state(self):\n \"\"\"Initialize temporary variables used during parsing pass\"\"\"\n self.reset_kernel_state()\n self.current_test = None\n self.kernels = []\n\n def parse(self, log_file: str):\n for line in open(log_file, \"r\").readlines():\n line = self.ansi_re.sub(\"\", line.rstrip())\n self.parse_line(line)","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.compile_regex","uri":"program://Fuser/function/tools.codediff.codediff.compile_regex#L406-L424","kind":"function","name":"compile_regex","path":"tools/codediff/codediff.py","language":"python","start_line":406,"end_line":424,"context_start_line":386,"context_end_line":444,"code":" time_unit = d[\"gputimeunit\"]\n cpu = d[\"cputime\"]\n cpu_unit = d[\"cputimeunit\"]\n iterations = d[\"iterations\"]\n # Skip metadata which for nvfuser_bench sometimes includes LaunchParams\n # meta = m.groups()[6]\n new_test = self.finalize_test(True)\n new_test.benchmark_result = BenchmarkResult(\n time, time_unit, cpu, cpu_unit, iterations\n )\n return True\n return False\n\n\nclass LogParserPyTest(LogParser):\n \"\"\"Parse output of pytest tests.\n\n Note that the tests must be run with both the -v and -s options\n \"\"\"\n\n def compile_regex(self):\n super().compile_regex()\n\n self.itemlist_re = re.compile(r\"Running \\d+ items in this shard: (.*)$\")\n\n # match lines like these:\n # [2024-10-23 02:00:20] tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears PASSED\n\n self.wildcard_testname_re = re.compile(\n r\"^((?P\\[[\\d\\-: ]+\\]) )?(?P\\S+\\.py::\\S+)\\s?(?P.*)$\"\n )\n\n self.extra_wildcard_testname_re = re.compile(\n r\".*?(?P\\S+::\\S+) (?P.*)$\"\n )\n\n self.all_test_names: list[str] | None = None\n\n def parse_line(self, line):\n if self.all_test_names is None:\n m = re.match(self.itemlist_re, line)\n if m is not None:\n # grab the test list\n self.all_test_names = m.groups()[0].split(\", \")\n return True\n\n m = re.match(self.wildcard_testname_re, line)\n if m is not None:\n d = m.groupdict()\n self.current_test = d[\"testname\"]\n line = d[\"line\"]\n\n if line == \"PASSED\":\n self.finalize_test(True)\n elif line == \"FAILED\" and self.current_test is not None:\n self.finalize_test(False)\n","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.reset_kernel_state","uri":"program://Fuser/function/tools.codediff.codediff.reset_kernel_state#L276-L279","kind":"function","name":"reset_kernel_state","path":"tools/codediff/codediff.py","language":"python","start_line":276,"end_line":279,"context_start_line":256,"context_end_line":299,"code":"class LogParser:\n \"\"\"General parser for STDOUT of NVFuser commands\n\n This parser does not group into individual tests, but rather places all\n kernels into a single CompiledTest whose name is \"Ungrouped Kernels\".\n \"\"\"\n\n def __init__(self, log_file: str):\n self.compile_regex()\n\n self.kernel_map: dict[str, CompiledTest] = {}\n\n self.reset_test_state()\n\n self.parse(log_file)\n\n def compile_regex(self):\n # regex for stripping ANSI color codes\n self.ansi_re = re.compile(r\"(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]\")\n\n def reset_kernel_state(self):\n self.current_file = None\n self.ptxas_info = \"\"\n self.launch_params_str = \"\"\n\n def reset_test_state(self):\n \"\"\"Initialize temporary variables used during parsing pass\"\"\"\n self.reset_kernel_state()\n self.current_test = None\n self.kernels = []\n\n def parse(self, log_file: str):\n for line in open(log_file, \"r\").readlines():\n line = self.ansi_re.sub(\"\", line.rstrip())\n self.parse_line(line)\n self.finalize()\n\n def finalize_kernel(self):\n if self.current_file is not None:\n k = CompiledKernel(\n self.current_file,\n ptxas_info=self.ptxas_info,\n launch_params_str=self.launch_params_str,\n )","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.reset_test_state","uri":"program://Fuser/function/tools.codediff.codediff.reset_test_state#L281-L285","kind":"function","name":"reset_test_state","path":"tools/codediff/codediff.py","language":"python","start_line":281,"end_line":285,"context_start_line":261,"context_end_line":305,"code":" \"\"\"\n\n def __init__(self, log_file: str):\n self.compile_regex()\n\n self.kernel_map: dict[str, CompiledTest] = {}\n\n self.reset_test_state()\n\n self.parse(log_file)\n\n def compile_regex(self):\n # regex for stripping ANSI color codes\n self.ansi_re = re.compile(r\"(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]\")\n\n def reset_kernel_state(self):\n self.current_file = None\n self.ptxas_info = \"\"\n self.launch_params_str = \"\"\n\n def reset_test_state(self):\n \"\"\"Initialize temporary variables used during parsing pass\"\"\"\n self.reset_kernel_state()\n self.current_test = None\n self.kernels = []\n\n def parse(self, log_file: str):\n for line in open(log_file, \"r\").readlines():\n line = self.ansi_re.sub(\"\", line.rstrip())\n self.parse_line(line)\n self.finalize()\n\n def finalize_kernel(self):\n if self.current_file is not None:\n k = CompiledKernel(\n self.current_file,\n ptxas_info=self.ptxas_info,\n launch_params_str=self.launch_params_str,\n )\n self.kernels.append(k)\n self.reset_kernel_state()\n\n def finalize_test(self, passed: bool):\n assert self.current_test is not None\n self.finalize_kernel()","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.parse","uri":"program://Fuser/function/tools.codediff.codediff.parse#L287-L291","kind":"function","name":"parse","path":"tools/codediff/codediff.py","language":"python","start_line":287,"end_line":291,"context_start_line":267,"context_end_line":311,"code":"\n self.reset_test_state()\n\n self.parse(log_file)\n\n def compile_regex(self):\n # regex for stripping ANSI color codes\n self.ansi_re = re.compile(r\"(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]\")\n\n def reset_kernel_state(self):\n self.current_file = None\n self.ptxas_info = \"\"\n self.launch_params_str = \"\"\n\n def reset_test_state(self):\n \"\"\"Initialize temporary variables used during parsing pass\"\"\"\n self.reset_kernel_state()\n self.current_test = None\n self.kernels = []\n\n def parse(self, log_file: str):\n for line in open(log_file, \"r\").readlines():\n line = self.ansi_re.sub(\"\", line.rstrip())\n self.parse_line(line)\n self.finalize()\n\n def finalize_kernel(self):\n if self.current_file is not None:\n k = CompiledKernel(\n self.current_file,\n ptxas_info=self.ptxas_info,\n launch_params_str=self.launch_params_str,\n )\n self.kernels.append(k)\n self.reset_kernel_state()\n\n def finalize_test(self, passed: bool):\n assert self.current_test is not None\n self.finalize_kernel()\n new_test = CompiledTest(self.current_test, self.kernels, passed)\n self.kernel_map[self.current_test] = new_test\n self.reset_test_state()\n return new_test\n\n def finalize(self):","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.finalize_kernel","uri":"program://Fuser/function/tools.codediff.codediff.finalize_kernel#L293-L301","kind":"function","name":"finalize_kernel","path":"tools/codediff/codediff.py","language":"python","start_line":293,"end_line":301,"context_start_line":273,"context_end_line":321,"code":" # regex for stripping ANSI color codes\n self.ansi_re = re.compile(r\"(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]\")\n\n def reset_kernel_state(self):\n self.current_file = None\n self.ptxas_info = \"\"\n self.launch_params_str = \"\"\n\n def reset_test_state(self):\n \"\"\"Initialize temporary variables used during parsing pass\"\"\"\n self.reset_kernel_state()\n self.current_test = None\n self.kernels = []\n\n def parse(self, log_file: str):\n for line in open(log_file, \"r\").readlines():\n line = self.ansi_re.sub(\"\", line.rstrip())\n self.parse_line(line)\n self.finalize()\n\n def finalize_kernel(self):\n if self.current_file is not None:\n k = CompiledKernel(\n self.current_file,\n ptxas_info=self.ptxas_info,\n launch_params_str=self.launch_params_str,\n )\n self.kernels.append(k)\n self.reset_kernel_state()\n\n def finalize_test(self, passed: bool):\n assert self.current_test is not None\n self.finalize_kernel()\n new_test = CompiledTest(self.current_test, self.kernels, passed)\n self.kernel_map[self.current_test] = new_test\n self.reset_test_state()\n return new_test\n\n def finalize(self):\n if len(self.kernels) > 0:\n group_name = \"Ungrouped Kernels\"\n self.kernel_map[group_name] = CompiledTest(group_name, self.kernels)\n\n def parse_line(self, line):\n \"\"\"Parse a line of log. Return True if consumed\"\"\"\n if line[:10] == \"PRINTING: \":\n if line[-3:] == \".cu\":\n self.finalize_kernel()\n # This avoids comparing the .ptx files that are created then","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.finalize_test","uri":"program://Fuser/function/tools.codediff.codediff.finalize_test#L303-L309","kind":"function","name":"finalize_test","path":"tools/codediff/codediff.py","language":"python","start_line":303,"end_line":309,"context_start_line":283,"context_end_line":329,"code":" self.reset_kernel_state()\n self.current_test = None\n self.kernels = []\n\n def parse(self, log_file: str):\n for line in open(log_file, \"r\").readlines():\n line = self.ansi_re.sub(\"\", line.rstrip())\n self.parse_line(line)\n self.finalize()\n\n def finalize_kernel(self):\n if self.current_file is not None:\n k = CompiledKernel(\n self.current_file,\n ptxas_info=self.ptxas_info,\n launch_params_str=self.launch_params_str,\n )\n self.kernels.append(k)\n self.reset_kernel_state()\n\n def finalize_test(self, passed: bool):\n assert self.current_test is not None\n self.finalize_kernel()\n new_test = CompiledTest(self.current_test, self.kernels, passed)\n self.kernel_map[self.current_test] = new_test\n self.reset_test_state()\n return new_test\n\n def finalize(self):\n if len(self.kernels) > 0:\n group_name = \"Ungrouped Kernels\"\n self.kernel_map[group_name] = CompiledTest(group_name, self.kernels)\n\n def parse_line(self, line):\n \"\"\"Parse a line of log. Return True if consumed\"\"\"\n if line[:10] == \"PRINTING: \":\n if line[-3:] == \".cu\":\n self.finalize_kernel()\n # This avoids comparing the .ptx files that are created then\n # removed by the MemoryTest.LoadCache tests\n self.current_file = line[10:]\n elif line[:6] == \"ptxas \":\n # NVFUSER_DUMP=ptxas_verbose corresponds to nvcc --ptxas-options=-v\n # or --resources-usage. This always prints after printing the cuda\n # filename\n if self.current_file is None:\n print(\"WARNING: Cannot associate ptxas info with CUDA kernel\")","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.finalize","uri":"program://Fuser/function/tools.codediff.codediff.finalize#L311-L314","kind":"function","name":"finalize","path":"tools/codediff/codediff.py","language":"python","start_line":311,"end_line":314,"context_start_line":291,"context_end_line":334,"code":" self.finalize()\n\n def finalize_kernel(self):\n if self.current_file is not None:\n k = CompiledKernel(\n self.current_file,\n ptxas_info=self.ptxas_info,\n launch_params_str=self.launch_params_str,\n )\n self.kernels.append(k)\n self.reset_kernel_state()\n\n def finalize_test(self, passed: bool):\n assert self.current_test is not None\n self.finalize_kernel()\n new_test = CompiledTest(self.current_test, self.kernels, passed)\n self.kernel_map[self.current_test] = new_test\n self.reset_test_state()\n return new_test\n\n def finalize(self):\n if len(self.kernels) > 0:\n group_name = \"Ungrouped Kernels\"\n self.kernel_map[group_name] = CompiledTest(group_name, self.kernels)\n\n def parse_line(self, line):\n \"\"\"Parse a line of log. Return True if consumed\"\"\"\n if line[:10] == \"PRINTING: \":\n if line[-3:] == \".cu\":\n self.finalize_kernel()\n # This avoids comparing the .ptx files that are created then\n # removed by the MemoryTest.LoadCache tests\n self.current_file = line[10:]\n elif line[:6] == \"ptxas \":\n # NVFUSER_DUMP=ptxas_verbose corresponds to nvcc --ptxas-options=-v\n # or --resources-usage. This always prints after printing the cuda\n # filename\n if self.current_file is None:\n print(\"WARNING: Cannot associate ptxas info with CUDA kernel\")\n return False\n self.ptxas_info += line + \"\\n\"\n elif line[:19] == \"Launch Parameters: \":\n if self.current_file is None:\n print(\"WARNING: Cannot associate launch params with CUDA kernel\")","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.parse_line","uri":"program://Fuser/function/tools.codediff.codediff.parse_line#L426-L448","kind":"function","name":"parse_line","path":"tools/codediff/codediff.py","language":"python","start_line":426,"end_line":448,"context_start_line":406,"context_end_line":468,"code":" def compile_regex(self):\n super().compile_regex()\n\n self.itemlist_re = re.compile(r\"Running \\d+ items in this shard: (.*)$\")\n\n # match lines like these:\n # [2024-10-23 02:00:20] tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears\n # tests/python/test_python_frontend.py::TestNvFuserFrontend::test_nanogpt_split_mha_linears PASSED\n\n self.wildcard_testname_re = re.compile(\n r\"^((?P\\[[\\d\\-: ]+\\]) )?(?P\\S+\\.py::\\S+)\\s?(?P.*)$\"\n )\n\n self.extra_wildcard_testname_re = re.compile(\n r\".*?(?P\\S+::\\S+) (?P.*)$\"\n )\n\n self.all_test_names: list[str] | None = None\n\n def parse_line(self, line):\n if self.all_test_names is None:\n m = re.match(self.itemlist_re, line)\n if m is not None:\n # grab the test list\n self.all_test_names = m.groups()[0].split(\", \")\n return True\n\n m = re.match(self.wildcard_testname_re, line)\n if m is not None:\n d = m.groupdict()\n self.current_test = d[\"testname\"]\n line = d[\"line\"]\n\n if line == \"PASSED\":\n self.finalize_test(True)\n elif line == \"FAILED\" and self.current_test is not None:\n self.finalize_test(False)\n\n if super().parse_line(line):\n return True\n\n return False\n\n\n@dataclass_json\n@dataclass\nclass TestRun:\n \"\"\"A single process that might contain many kernels, grouped into tests\"\"\"\n\n directory: str\n git: GitRev | None = None\n name: str | None = None\n command: str | None = None\n command_type: CommandType | None = None\n exit_code: int | None = None\n env: str | None = None\n gpu_names: str | None = None\n nvcc_version: str | None = None\n # map from name of test to list of kernel base filenames\n kernel_map: dict[str, CompiledTest] | None = None\n # collecting the preamble lets us skip it when diffing, and lets us compare\n # only the preamble between runs","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.compute_kernel_map","uri":"program://Fuser/function/tools.codediff.codediff.compute_kernel_map#L544-L565","kind":"function","name":"compute_kernel_map","path":"tools/codediff/codediff.py","language":"python","start_line":544,"end_line":565,"context_start_line":524,"context_end_line":585,"code":" try:\n self.nvcc_version = open(\n os.path.join(self.directory, \"nvcc_version\"), \"r\"\n ).read()\n except FileNotFoundError:\n self.nvcc_version = None\n\n try:\n self.gpu_names = list(\n open(os.path.join(self.directory, \"gpu_names\"), \"r\").readlines()\n )\n except FileNotFoundError:\n self.gpu_names = None\n\n self.exit_code = int(open(os.path.join(self.directory, \"exitcode\"), \"r\").read())\n\n self.compute_kernel_map()\n\n self.find_preamble()\n\n def compute_kernel_map(self):\n \"\"\"\n Compute a map from test name to list of cuda filenames\n \"\"\"\n logfile = os.path.join(self.directory, \"stdout\")\n if not os.path.isfile(logfile):\n raise RuntimeError(\n f\"Input directory {self.directory} contains no file named 'stdout'\"\n )\n\n if self.command_type == CommandType.GOOGLETEST:\n parser = LogParserGTest(logfile)\n elif self.command_type == CommandType.GOOGLEBENCH:\n parser = LogParserGBench(logfile)\n elif self.command_type == CommandType.PYTEST:\n parser = LogParserPyTest(logfile)\n else:\n # The base class provides a parser that groups everything into a\n # single \"test\" called \"Ungrouped Kernels\"\n parser = LogParser(logfile)\n\n self.kernel_map = parser.kernel_map\n\n def find_preamble(self):\n \"\"\"Look for common preamble in collected kernels\"\"\"\n preamble_lines = []\n first = True\n files_processed = 0 # limit how many files to check\n for cufile in os.listdir(os.path.join(self.directory, \"cuda\")):\n cufile_full = os.path.join(self.directory, \"cuda\", cufile)\n with open(cufile_full, \"r\") as f:\n for i, line in enumerate(f.readlines()):\n line = line.rstrip()\n # we set nvfuser_index_t in the preamble. We ignore that change for the purposes of this diff\n if line[:8] == \"typedef \" and line[-17:] == \" nvfuser_index_t;\":\n line = \"typedef int nvfuser_index_t; // NOTE: index type hard-coded as int for display only\"\n if re.search(r\"void (nvfuser|kernel)_?\\d+\\b\", line) is not None:\n # we arrived at the kernel definition\n break\n if first:\n preamble_lines.append(line)\n elif i >= len(preamble_lines) or preamble_lines[i] != line:","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.find_preamble","uri":"program://Fuser/function/tools.codediff.codediff.find_preamble#L567-L596","kind":"function","name":"find_preamble","path":"tools/codediff/codediff.py","language":"python","start_line":567,"end_line":596,"context_start_line":547,"context_end_line":616,"code":" \"\"\"\n logfile = os.path.join(self.directory, \"stdout\")\n if not os.path.isfile(logfile):\n raise RuntimeError(\n f\"Input directory {self.directory} contains no file named 'stdout'\"\n )\n\n if self.command_type == CommandType.GOOGLETEST:\n parser = LogParserGTest(logfile)\n elif self.command_type == CommandType.GOOGLEBENCH:\n parser = LogParserGBench(logfile)\n elif self.command_type == CommandType.PYTEST:\n parser = LogParserPyTest(logfile)\n else:\n # The base class provides a parser that groups everything into a\n # single \"test\" called \"Ungrouped Kernels\"\n parser = LogParser(logfile)\n\n self.kernel_map = parser.kernel_map\n\n def find_preamble(self):\n \"\"\"Look for common preamble in collected kernels\"\"\"\n preamble_lines = []\n first = True\n files_processed = 0 # limit how many files to check\n for cufile in os.listdir(os.path.join(self.directory, \"cuda\")):\n cufile_full = os.path.join(self.directory, \"cuda\", cufile)\n with open(cufile_full, \"r\") as f:\n for i, line in enumerate(f.readlines()):\n line = line.rstrip()\n # we set nvfuser_index_t in the preamble. We ignore that change for the purposes of this diff\n if line[:8] == \"typedef \" and line[-17:] == \" nvfuser_index_t;\":\n line = \"typedef int nvfuser_index_t; // NOTE: index type hard-coded as int for display only\"\n if re.search(r\"void (nvfuser|kernel)_?\\d+\\b\", line) is not None:\n # we arrived at the kernel definition\n break\n if first:\n preamble_lines.append(line)\n elif i >= len(preamble_lines) or preamble_lines[i] != line:\n break\n preamble_lines = preamble_lines[:i]\n if len(preamble_lines) == 0:\n # early return if preamble is determined to be empty\n break\n first = False\n files_processed += 1\n if files_processed >= 50:\n break\n self.preamble_size_lines = len(preamble_lines)\n self.preamble = \"\\n\".join(preamble_lines)\n\n def get_kernel(\n self, test_name, kernel_number, strip_preamble=True\n ) -> CompiledKernel:\n \"\"\"Get a string of the kernel, optionally stripping the preamble\"\"\"\n kern = self.kernel_map[test_name].kernels[kernel_number]\n basename = kern.filename\n if kern.code is not None:\n return kern\n fullname = os.path.join(self.directory, \"cuda\", basename)\n kern.code = \"\"\n with open(fullname, \"r\") as f:\n for i, line in enumerate(f.readlines()):\n if kern.index_type is None:\n m = re.search(r\"typedef\\s+(\\S*)\\s+nvfuser_index_t;\", line)\n if m is not None:\n kern.index_type = m.groups()[0]\n if not strip_preamble or i >= self.preamble_size_lines:\n # replace kernel934 with kernel1 to facilitate diffing\n # also match kernel_43 to handle new-style naming with static fusion count","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.get_kernel","uri":"program://Fuser/function/tools.codediff.codediff.get_kernel#L598-L629","kind":"function","name":"get_kernel","path":"tools/codediff/codediff.py","language":"python","start_line":598,"end_line":629,"context_start_line":578,"context_end_line":649,"code":" if line[:8] == \"typedef \" and line[-17:] == \" nvfuser_index_t;\":\n line = \"typedef int nvfuser_index_t; // NOTE: index type hard-coded as int for display only\"\n if re.search(r\"void (nvfuser|kernel)_?\\d+\\b\", line) is not None:\n # we arrived at the kernel definition\n break\n if first:\n preamble_lines.append(line)\n elif i >= len(preamble_lines) or preamble_lines[i] != line:\n break\n preamble_lines = preamble_lines[:i]\n if len(preamble_lines) == 0:\n # early return if preamble is determined to be empty\n break\n first = False\n files_processed += 1\n if files_processed >= 50:\n break\n self.preamble_size_lines = len(preamble_lines)\n self.preamble = \"\\n\".join(preamble_lines)\n\n def get_kernel(\n self, test_name, kernel_number, strip_preamble=True\n ) -> CompiledKernel:\n \"\"\"Get a string of the kernel, optionally stripping the preamble\"\"\"\n kern = self.kernel_map[test_name].kernels[kernel_number]\n basename = kern.filename\n if kern.code is not None:\n return kern\n fullname = os.path.join(self.directory, \"cuda\", basename)\n kern.code = \"\"\n with open(fullname, \"r\") as f:\n for i, line in enumerate(f.readlines()):\n if kern.index_type is None:\n m = re.search(r\"typedef\\s+(\\S*)\\s+nvfuser_index_t;\", line)\n if m is not None:\n kern.index_type = m.groups()[0]\n if not strip_preamble or i >= self.preamble_size_lines:\n # replace kernel934 with kernel1 to facilitate diffing\n # also match kernel_43 to handle new-style naming with static fusion count\n kern.code += re.sub(r\"\\bnvfuser_\\d+\\b\", \"nvfuser_N\", line)\n kern.code = kern.code.rstrip()\n if strip_preamble and kern.code[-1] == \"}\":\n # trailing curly brace is close of namespace. This will clean it up so that we have just the kernel\n kern.code = kern.code[:-1].rstrip()\n # find ptx file if it exists\n ptx_basename = os.path.splitext(basename)[0] + \".ptx\"\n ptx_fullname = os.path.join(self.directory, \"ptx\", ptx_basename)\n try:\n kern.ptx = open(ptx_fullname, \"r\").read().rstrip()\n except FileNotFoundError:\n pass\n return kern\n\n def join(self, other: \"TestRun\"):\n \"\"\"Concatenate other with self\"\"\"\n # Stuff that has to match\n assert self.git == other.git\n assert self.preamble_size_lines == other.preamble_size_lines\n assert self.preamble == other.preamble\n assert self.command_type == other.command_type\n\n # don't update name of this command\n\n # Append differing nvcc versions as new rows, otherwise keep equal\n if other.nvcc_version != self.nvcc_version:\n self.nvcc_version += other.nvcc_version\n\n # We expect the env to differ since we are probably joining after\n # running multiple shards on different nodes in parallel. So just\n # concatenate the envs, with a blank line between\n if other.env != self.env:\n self.env += f\"\\n{other.env}\"","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.join","uri":"program://Fuser/function/tools.codediff.codediff.join#L631-L679","kind":"function","name":"join","path":"tools/codediff/codediff.py","language":"python","start_line":631,"end_line":679,"context_start_line":611,"context_end_line":699,"code":" m = re.search(r\"typedef\\s+(\\S*)\\s+nvfuser_index_t;\", line)\n if m is not None:\n kern.index_type = m.groups()[0]\n if not strip_preamble or i >= self.preamble_size_lines:\n # replace kernel934 with kernel1 to facilitate diffing\n # also match kernel_43 to handle new-style naming with static fusion count\n kern.code += re.sub(r\"\\bnvfuser_\\d+\\b\", \"nvfuser_N\", line)\n kern.code = kern.code.rstrip()\n if strip_preamble and kern.code[-1] == \"}\":\n # trailing curly brace is close of namespace. This will clean it up so that we have just the kernel\n kern.code = kern.code[:-1].rstrip()\n # find ptx file if it exists\n ptx_basename = os.path.splitext(basename)[0] + \".ptx\"\n ptx_fullname = os.path.join(self.directory, \"ptx\", ptx_basename)\n try:\n kern.ptx = open(ptx_fullname, \"r\").read().rstrip()\n except FileNotFoundError:\n pass\n return kern\n\n def join(self, other: \"TestRun\"):\n \"\"\"Concatenate other with self\"\"\"\n # Stuff that has to match\n assert self.git == other.git\n assert self.preamble_size_lines == other.preamble_size_lines\n assert self.preamble == other.preamble\n assert self.command_type == other.command_type\n\n # don't update name of this command\n\n # Append differing nvcc versions as new rows, otherwise keep equal\n if other.nvcc_version != self.nvcc_version:\n self.nvcc_version += other.nvcc_version\n\n # We expect the env to differ since we are probably joining after\n # running multiple shards on different nodes in parallel. So just\n # concatenate the envs, with a blank line between\n if other.env != self.env:\n self.env += f\"\\n{other.env}\"\n\n # keep a list of all GPUs involved\n self.gpu_names += other.gpu_names\n\n # concatenate command as if we ran the commands in sequence\n self.command += f\" && {other.command}\"\n\n # if one of the inputs is an error (non-zero), preserve it\n self.exit_code += other.exit_code\n\n # now merge the kernel maps with one another\n for test_name, test_obj in other.kernel_map.items():\n assert test_obj.name == test_name\n if test_name == \"Ungrouped Kernels\":\n if test_name in self.kernel_map:\n self.kernel_map[test_name].kernels += test_obj.kernels\n if not test_obj.passed:\n self.kernel_map[test_name].passed = False\n # Don't merge benchmark results. We should not have\n # ungrouped kernels with these fields anyway, since we\n # expect all kernels to fall under some benchmark if the\n # command_type is known to be a benchmark\n assert self.kernel_map[test_name].benchmark_result is None\n assert test_obj.benchmark_result is None\n continue\n else:\n assert (\n test_name not in self.kernel_map\n ), f\"Cannot join test runs containing the same test {test_name}\"\n self.kernel_map[test_name] = test_obj\n\n\n@dataclass_json\n@dataclass\nclass KernelDiff:\n testname: str\n kernel_num: int\n kernel1: CompiledKernel\n kernel2: CompiledKernel\n diff_lines: InitVar[list[str]] = []\n ptx_diff_lines: InitVar[list[str] | None] = []\n new_lines: int = 0\n removed_lines: int = 0\n ptx_diff: str | None = None\n new_ptx_lines: int = 0\n removed_ptx_lines: int = 0\n diff: str | None = None\n\n def __post_init__(self, diff_lines: list[str], ptx_diff_lines: list[str] | None):\n if self.diff is not None:","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.hide_env","uri":"program://Fuser/function/tools.codediff.codediff.hide_env#L946-L951","kind":"function","name":"hide_env","path":"tools/codediff/codediff.py","language":"python","start_line":946,"end_line":951,"context_start_line":926,"context_end_line":971,"code":" kernel_diffs.append(kd)\n\n if len(kernel_diffs) > 0:\n self.test_diffs.append(\n TestDiff(\n testname,\n compiled_test1,\n compiled_test2,\n kernel_diffs,\n )\n )\n\n for testname, compiled_test2 in self.run2.kernel_map.items():\n if testname not in self.run1.kernel_map:\n compiled_test2.kernels = [\n self.run2.get_kernel(testname, i)\n for i in range(len(compiled_test2.kernels))\n ]\n self.new_tests.append(compiled_test2)\n\n def hide_env(self):\n \"\"\"Remove private information like env vars and lib versions\"\"\"\n self.run1.env = None\n self.run2.env = None\n self.run1.nvcc_version = None\n self.run2.nvcc_version = None\n\n def generate_html(self, omit_preamble: bool, max_diffs: bool) -> str:\n \"\"\"Return a self-contained HTML string summarizing the codegen comparison\"\"\"\n import jinja2\n\n tools_dir = os.path.dirname(__file__)\n template_dir = os.path.join(tools_dir, \"templates\")\n env = jinja2.Environment(\n loader=jinja2.FileSystemLoader(searchpath=template_dir)\n )\n template = env.get_template(\"codediff.html\")\n # dict_factory lets us provide custom serializations for classes like Enums\n # https://stackoverflow.com/questions/61338539/how-to-use-enum-value-in-asdict-function-from-dataclasses-module\n context = asdict(\n self,\n dict_factory=lambda data: {\n # Serialize CommandType as string so that jinja can recognize it\n field: value.name if isinstance(value, CommandType) else value\n for field, value in data\n },","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.generate_html","uri":"program://Fuser/function/tools.codediff.codediff.generate_html#L953-L985","kind":"function","name":"generate_html","path":"tools/codediff/codediff.py","language":"python","start_line":953,"end_line":985,"context_start_line":933,"context_end_line":1005,"code":" compiled_test2,\n kernel_diffs,\n )\n )\n\n for testname, compiled_test2 in self.run2.kernel_map.items():\n if testname not in self.run1.kernel_map:\n compiled_test2.kernels = [\n self.run2.get_kernel(testname, i)\n for i in range(len(compiled_test2.kernels))\n ]\n self.new_tests.append(compiled_test2)\n\n def hide_env(self):\n \"\"\"Remove private information like env vars and lib versions\"\"\"\n self.run1.env = None\n self.run2.env = None\n self.run1.nvcc_version = None\n self.run2.nvcc_version = None\n\n def generate_html(self, omit_preamble: bool, max_diffs: bool) -> str:\n \"\"\"Return a self-contained HTML string summarizing the codegen comparison\"\"\"\n import jinja2\n\n tools_dir = os.path.dirname(__file__)\n template_dir = os.path.join(tools_dir, \"templates\")\n env = jinja2.Environment(\n loader=jinja2.FileSystemLoader(searchpath=template_dir)\n )\n template = env.get_template(\"codediff.html\")\n # dict_factory lets us provide custom serializations for classes like Enums\n # https://stackoverflow.com/questions/61338539/how-to-use-enum-value-in-asdict-function-from-dataclasses-module\n context = asdict(\n self,\n dict_factory=lambda data: {\n # Serialize CommandType as string so that jinja can recognize it\n field: value.name if isinstance(value, CommandType) else value\n for field, value in data\n },\n )\n context[\"omit_preamble\"] = omit_preamble\n context[\"max_diffs\"] = max_diffs\n head_hash = (\n subprocess.run([\"git\", \"rev-parse\", \"HEAD\"], capture_output=True)\n .stdout.strip()\n .decode(\"utf-8\")\n )\n context[\"tool_git\"] = GitRev(head_hash)\n context[\"explain_api_url\"] = os.environ.get(\n \"CODEDIFF_EXPLAIN_API_URL\", \"/api/explain-diff\"\n )\n\n return template.render(context)\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n subparsers = parser.add_subparsers(title=\"verb\")\n\n parse_parser = subparsers.add_parser(\n \"parse\", help=\"Parse an output directory of run_command.sh into a JSON file\"\n )\n parse_parser.add_argument(\n \"dir\",\n help=\"Directory containing 'stdout' and 'cuda/' resulting from run_command.sh\",\n )\n parse_parser.add_argument(\"output_json\", help=\"Location to write JSON file\")\n\n def parse_dir(args: dict):","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.parse_dir","uri":"program://Fuser/function/tools.codediff.codediff.parse_dir#L1005-L1014","kind":"function","name":"parse_dir","path":"tools/codediff/codediff.py","language":"python","start_line":1005,"end_line":1014,"context_start_line":985,"context_end_line":1034,"code":" return template.render(context)\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n subparsers = parser.add_subparsers(title=\"verb\")\n\n parse_parser = subparsers.add_parser(\n \"parse\", help=\"Parse an output directory of run_command.sh into a JSON file\"\n )\n parse_parser.add_argument(\n \"dir\",\n help=\"Directory containing 'stdout' and 'cuda/' resulting from run_command.sh\",\n )\n parse_parser.add_argument(\"output_json\", help=\"Location to write JSON file\")\n\n def parse_dir(args: dict):\n tr = TestRun(args.dir)\n\n # load the code for each kernel\n for test_name, compiled_kernel in tr.kernel_map.items():\n for kernel_number in range(len(compiled_kernel.kernels)):\n tr.get_kernel(test_name, kernel_number, strip_preamble=True)\n\n with open(args.output_json, \"w\") as f:\n f.write(tr.to_json())\n\n parse_parser.set_defaults(func=parse_dir)\n\n join_parser = subparsers.add_parser(\n \"join\",\n help='Concatenate multiple command JSONs as if they were from a single command. This is useful for \"unsharding\" jobs that are computed using run_command.sh on multiple shards',\n )\n join_parser.add_argument(\n \"-o\", \"--output\", help=\"Location to write concatenated JSON file\"\n )\n join_parser.add_argument(\n \"input_jsons\", nargs=\"+\", help=\"Location of incoming JSON files\"\n )\n\n def join_jsons(args: dict):\n assert len(args.input_jsons) > 0\n\n with open(args.input_jsons[0], \"r\") as f:\n td = TestRun.from_json(f.read())\n","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.join_jsons","uri":"program://Fuser/function/tools.codediff.codediff.join_jsons#L1029-L1041","kind":"function","name":"join_jsons","path":"tools/codediff/codediff.py","language":"python","start_line":1029,"end_line":1041,"context_start_line":1009,"context_end_line":1061,"code":" for test_name, compiled_kernel in tr.kernel_map.items():\n for kernel_number in range(len(compiled_kernel.kernels)):\n tr.get_kernel(test_name, kernel_number, strip_preamble=True)\n\n with open(args.output_json, \"w\") as f:\n f.write(tr.to_json())\n\n parse_parser.set_defaults(func=parse_dir)\n\n join_parser = subparsers.add_parser(\n \"join\",\n help='Concatenate multiple command JSONs as if they were from a single command. This is useful for \"unsharding\" jobs that are computed using run_command.sh on multiple shards',\n )\n join_parser.add_argument(\n \"-o\", \"--output\", help=\"Location to write concatenated JSON file\"\n )\n join_parser.add_argument(\n \"input_jsons\", nargs=\"+\", help=\"Location of incoming JSON files\"\n )\n\n def join_jsons(args: dict):\n assert len(args.input_jsons) > 0\n\n with open(args.input_jsons[0], \"r\") as f:\n td = TestRun.from_json(f.read())\n\n for filename in args.input_jsons[1:]:\n with open(filename, \"r\") as f:\n td_other = TestRun.from_json(f.read())\n td.join(td_other)\n\n with open(args.output, \"w\") as f:\n f.write(td.to_json())\n\n join_parser.set_defaults(func=join_jsons)\n\n diff_parser = subparsers.add_parser(\n \"diff\", help=\"Compute the difference between two parsed command outputs\"\n )\n diff_parser.add_argument(\n \"--kernel-inclusion-criterion\",\n \"-i\",\n choices=(\"mismatched_cuda_or_ptx\", \"mismatched_ptx\", \"all\"),\n default=\"mismatched_cuda_or_ptx\",\n help=\"Which kernels should we include?\",\n )\n diff_parser.add_argument(\n \"--hide-diffs\",\n \"--no-print-diff\",\n action=\"store_true\",\n help=\"Print diffs to STDOUT?\",\n )\n diff_parser.add_argument(\"input_json1\", help=\"Location of first JSON file\")","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.diff_jsons","uri":"program://Fuser/function/tools.codediff.codediff.diff_jsons#L1065-L1095","kind":"function","name":"diff_jsons","path":"tools/codediff/codediff.py","language":"python","start_line":1065,"end_line":1095,"context_start_line":1045,"context_end_line":1115,"code":" diff_parser = subparsers.add_parser(\n \"diff\", help=\"Compute the difference between two parsed command outputs\"\n )\n diff_parser.add_argument(\n \"--kernel-inclusion-criterion\",\n \"-i\",\n choices=(\"mismatched_cuda_or_ptx\", \"mismatched_ptx\", \"all\"),\n default=\"mismatched_cuda_or_ptx\",\n help=\"Which kernels should we include?\",\n )\n diff_parser.add_argument(\n \"--hide-diffs\",\n \"--no-print-diff\",\n action=\"store_true\",\n help=\"Print diffs to STDOUT?\",\n )\n diff_parser.add_argument(\"input_json1\", help=\"Location of first JSON file\")\n diff_parser.add_argument(\"input_json2\", help=\"Location of second JSON file\")\n diff_parser.add_argument(\"output_json\", help=\"Location to write output JSON file\")\n\n def diff_jsons(args: dict):\n with open(args.input_json1, \"r\") as f:\n tr1 = TestRun.from_json(f.read())\n with open(args.input_json2, \"r\") as f:\n tr2 = TestRun.from_json(f.read())\n td = TestDifferences(\n tr1,\n tr2,\n show_diffs=not args.hide_diffs,\n inclusion_criterion=args.kernel_inclusion_criterion,\n )\n\n if len(td.test_diffs) == 0:\n print(\"No differences found in overlapping tests!\")\n else:\n print(\n td.total_num_diffs,\n \"kernel differences from\",\n len(td.test_diffs),\n \"tests found\",\n )\n if len(td.new_tests) > 0:\n print(len(td.new_tests), \"new tests found\")\n if len(td.removed_tests) > 0:\n print(len(td.removed_tests), \"removed tests found\")\n\n with open(args.output_json, \"w\") as f:\n f.write(td.to_json())\n\n # Return 1 if preamble or any kernels are changed, else 0\n exit(1 if len(td.test_diffs) > 0 or len(td.preamble_diff) > 0 else 0)\n\n diff_parser.set_defaults(func=diff_jsons)\n\n report_parser = subparsers.add_parser(\n \"diff_report\", help=\"Compute an HTML report from a diff JSON\"\n )\n report_parser.add_argument(\n \"--hide-env\",\n action=\"store_true\",\n help=\"Hide environment variables and nvcc versions in output?\",\n )\n report_parser.add_argument(\n \"--max-diffs\",\n default=200,\n type=int,\n help=\"Limit number of included kernel diffs in HTML output to this many (does not affect exit code).\",\n )\n report_parser.add_argument(\n \"--omit-preamble\",\n action=\"store_true\",","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.diff_report","uri":"program://Fuser/function/tools.codediff.codediff.diff_report#L1121-L1133","kind":"function","name":"diff_report","path":"tools/codediff/codediff.py","language":"python","start_line":1121,"end_line":1133,"context_start_line":1101,"context_end_line":1139,"code":" )\n report_parser.add_argument(\n \"--hide-env\",\n action=\"store_true\",\n help=\"Hide environment variables and nvcc versions in output?\",\n )\n report_parser.add_argument(\n \"--max-diffs\",\n default=200,\n type=int,\n help=\"Limit number of included kernel diffs in HTML output to this many (does not affect exit code).\",\n )\n report_parser.add_argument(\n \"--omit-preamble\",\n action=\"store_true\",\n help=\"Omit the preamble in HTML output?\",\n )\n report_parser.add_argument(\"input_json\", help=\"Location of diff JSON file\")\n report_parser.add_argument(\"output_html\", help=\"Location to write output HTML file\")\n\n def diff_report(args: dict):\n with open(args.input_json, \"r\") as f:\n td = TestDifferences.from_json(f.read())\n\n if args.hide_env:\n td.hide_env()\n\n with open(args.output_html, \"w\") as f:\n f.write(\n td.generate_html(\n omit_preamble=args.omit_preamble, max_diffs=args.max_diffs\n )\n )\n\n report_parser.set_defaults(func=diff_report)\n\n args = parser.parse_args()\n\n args.func(args)","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.git_show","uri":"program://Fuser/function/tools.codediff.codediff.git_show#L73-L87","kind":"function","name":"git_show","path":"tools/codediff/codediff.py","language":"python","start_line":73,"end_line":87,"context_start_line":53,"context_end_line":107,"code":" for line in (\n subprocess.run(\n [\"git\", \"branch\", \"--quiet\", \"--color=never\", self.full_hash],\n capture_output=True,\n )\n .stdout.strip()\n .decode(\"utf-8\")\n .splitlines()\n ):\n # Possible output:\n #\n # main\n # * scalar_seg_edges\n #\n # In this case, we have checked out the HEAD of the\n # scalar_seg_edges branch. Here we just strip the *.\n if line[0] == \"*\":\n line = line[2:]\n in_branches.append(line)\n\n def git_show(fmt) -> str:\n return (\n subprocess.run(\n [\n \"git\",\n \"show\",\n \"--no-patch\",\n f\"--format={fmt}\",\n self.full_hash,\n ],\n capture_output=True,\n )\n .stdout.strip()\n .decode(\"utf-8\")\n )\n\n self.title = git_show(\"%s\")\n self.author_name = git_show(\"%an\")\n self.author_email = git_show(\"%ae\")\n self.author_time = git_show(\"%ad\")\n self.commit_time = git_show(\"%cd\")\n\n\n@dataclass_json\n@dataclass\nclass LaunchParams:\n blockDim: tuple[int]\n gridDim: tuple[int]\n dynamic_smem_bytes: int\n\n\n@dataclass_json\n@dataclass\nclass CompiledKernel:\n filename: str","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.codediff.find_unique_int","uri":"program://Fuser/function/tools.codediff.codediff.find_unique_int#L155-L158","kind":"function","name":"find_unique_int","path":"tools/codediff/codediff.py","language":"python","start_line":155,"end_line":158,"context_start_line":135,"context_end_line":178,"code":" # ptxas info : 307 bytes gmem\n # ptxas info : Compiling entry function\n # '_ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_'\n # for 'sm_86'\n # ptxas info : Function properties for\n # _ZN76_GLOBAL__N__00000000_37___tmp_kernel_pointwise_f0_c1_r0_g0_cu_8995cef2_3255329nvfuser_pointwise_f0_c1_r0_g0ENS_6TensorIfLi2ELi2EEES1_S1_\n # ptxas . 0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads\n # ptxas info : Used 203 registers, 16 bytes smem, 472 bytes cmem[0], 8 bytes cmem[2]\n #\n # Here we parse this into the fields presented, and we replace the\n # mangled kernel name since it includes the kernel number and is\n # useless for the purposes of diffing since the kernel signature is\n # already included.\n if self.ptxas_info is None:\n return\n\n m = re.search(r\"Compiling entry function '(.*)' for '(.*)'\", self.ptxas_info)\n if m is not None:\n self.mangled_name, self.arch = m.groups()\n\n def find_unique_int(pattern) -> int | None:\n assert self.ptxas_info is not None\n m = re.search(pattern, self.ptxas_info)\n return 0 if m is None else int(m.groups()[0])\n\n self.stack_frame_bytes = find_unique_int(r\"(\\d+) bytes stack frame\")\n self.spill_store_bytes = find_unique_int(r\"(\\d+) bytes spill stores\")\n self.spill_load_bytes = find_unique_int(r\"(\\d+) bytes spill loads\")\n self.registers = find_unique_int(r\"(\\d+) registers\")\n self.gmem_bytes = find_unique_int(r\"(\\d+) bytes gmem\")\n self.smem_bytes = find_unique_int(r\"(\\d+) bytes smem\")\n\n self.cmem_bank_bytes = []\n cmem_banks = 0\n for m in re.finditer(r\"(\\d+) bytes cmem\\[(\\d+)\\]\", self.ptxas_info):\n nbytes_str, bank_str = m.groups()\n bank = int(bank_str)\n if len(self.cmem_bank_bytes) <= bank:\n self.cmem_bank_bytes += [0] * (bank + 1 - len(self.cmem_bank_bytes))\n self.cmem_bank_bytes[bank] = int(nbytes_str)\n cmem_banks += 1\n\n def parse_launch_params(self):\n # If NVFUSER_DUMP=launch_param is given we will get a line like this for every launch:","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.diff_report","uri":"program://Fuser/module/tools.codediff.diff_report#L1-L121","kind":"module","name":"tools.codediff.diff_report","path":"tools/codediff/diff_report.py","language":"python","start_line":1,"end_line":121,"context_start_line":1,"context_end_line":121,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nFind corresponding .cu files for matching tests, even when new tests are\nintroduced between two commits. Diffs are displayed and the return value is the\nnumber of mismatched corresponding tests.\n\nTests are skipped if they produce different numbers of .cu files, or if they\nexist in only one of the given runs.\n\nExample usage:\n python tools/diff_codegen_nvfuser_tests.py \\\n codegen_comparison/{$commit1,$commit2}/binary_tests\n\"\"\"\n\nimport os\n\nfrom codediff import TestRun, TestDifferences\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(\n epilog=\"This command must be run from within a git checkout of the NVFuser repo.\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\"dir1\", help=\"Directory containing 'stdout' and 'cuda/'\")\n parser.add_argument(\"dir2\", help=\"Directory containing 'stdout' and 'cuda/'\")\n parser.add_argument(\n \"--hide-env\",\n action=\"store_true\",\n help=\"Hide environment variables and nvcc versions in output?\",\n )\n parser.add_argument(\"--html\", action=\"store_true\", help=\"Write HTML file?\")\n parser.add_argument(\n \"--hide-diffs\",\n \"--no-print-diff\",\n action=\"store_true\",\n help=\"Print diffs to STDOUT?\",\n )\n parser.add_argument(\n \"--kernel-inclusion-criterion\",\n \"-i\",\n choices=(\"mismatched_cuda_or_ptx\", \"mismatched_ptx\", \"all\"),\n default=\"mismatched_cuda_or_ptx\",\n help=\"Which kernels should we include?\",\n )\n parser.add_argument(\n \"--html-max-diffs\",\n default=200,\n type=int,\n help=\"Limit number of included kernel diffs in HTML output to this many (does not affect exit code).\",\n )\n parser.add_argument(\n \"--html-omit-preamble\",\n action=\"store_true\",\n help=\"Omit the preamble in HTML output?\",\n )\n parser.add_argument(\n \"-o\", \"--output-file\", help=\"Location of HTML file output if -h is given.\"\n )\n parser.add_argument(\n \"--json\",\n help=\"Location to write JSON output, if given\",\n )\n args = parser.parse_args()\n\n td = TestDifferences(\n TestRun(args.dir1),\n TestRun(args.dir2),\n show_diffs=not args.hide_diffs,\n inclusion_criterion=args.kernel_inclusion_criterion,\n )\n\n if args.hide_env:\n td.hide_env()\n\n if args.html:\n output_file = args.output_file\n if output_file is None:\n # determine default output file\n def get_abbrev(d):\n return os.path.basename(os.path.dirname(os.path.abspath(d)))\n\n abbrev1 = get_abbrev(args.dir1)\n abbrev2 = get_abbrev(args.dir2)\n run_name = os.path.basename(os.path.abspath(args.dir1))\n output_file = f\"codediff_{abbrev1}_{abbrev2}_{run_name}.html\"\n with open(output_file, \"w\") as f:\n f.write(\n td.generate_html(\n omit_preamble=args.html_omit_preamble, max_diffs=args.html_max_diffs\n )\n )\n\n if args.json is not None:\n import json\n\n d = asdict(td)\n # clean up the dict a bit by removing temporary data structures\n del d[\"run1\"][\"kernel_map\"]\n del d[\"run2\"][\"kernel_map\"]\n json.dump(d, open(args.json, \"w\"), indent=2)\n\n if len(td.test_diffs) == 0:\n print(\"No differences found in overlapping tests!\")\n else:\n print(\n td.total_num_diffs,\n \"kernel differences from\",\n len(td.test_diffs),\n \"tests found\",\n )\n if len(td.new_tests) > 0:\n print(len(td.new_tests), \"new tests found\")\n if len(td.removed_tests) > 0:\n print(len(td.removed_tests), \"removed tests found\")\n\n # Return 1 if preamble or any kernels are changed, else 0\n exit(1 if len(td.test_diffs) > 0 or len(td.preamble_diff) > 0 else 0)","source_hash":"19c985eb63ab33ec27d5c174ee2fd026718a04edd76beeed386c2465946602c0","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.codediff.diff_report.get_abbrev","uri":"program://Fuser/function/tools.codediff.diff_report.get_abbrev#L83-L84","kind":"function","name":"get_abbrev","path":"tools/codediff/diff_report.py","language":"python","start_line":83,"end_line":84,"context_start_line":63,"context_end_line":104,"code":" parser.add_argument(\n \"--json\",\n help=\"Location to write JSON output, if given\",\n )\n args = parser.parse_args()\n\n td = TestDifferences(\n TestRun(args.dir1),\n TestRun(args.dir2),\n show_diffs=not args.hide_diffs,\n inclusion_criterion=args.kernel_inclusion_criterion,\n )\n\n if args.hide_env:\n td.hide_env()\n\n if args.html:\n output_file = args.output_file\n if output_file is None:\n # determine default output file\n def get_abbrev(d):\n return os.path.basename(os.path.dirname(os.path.abspath(d)))\n\n abbrev1 = get_abbrev(args.dir1)\n abbrev2 = get_abbrev(args.dir2)\n run_name = os.path.basename(os.path.abspath(args.dir1))\n output_file = f\"codediff_{abbrev1}_{abbrev2}_{run_name}.html\"\n with open(output_file, \"w\") as f:\n f.write(\n td.generate_html(\n omit_preamble=args.html_omit_preamble, max_diffs=args.html_max_diffs\n )\n )\n\n if args.json is not None:\n import json\n\n d = asdict(td)\n # clean up the dict a bit by removing temporary data structures\n del d[\"run1\"][\"kernel_map\"]\n del d[\"run2\"][\"kernel_map\"]\n json.dump(d, open(args.json, \"w\"), indent=2)","source_hash":"19c985eb63ab33ec27d5c174ee2fd026718a04edd76beeed386c2465946602c0","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.examples.repro","uri":"program://Fuser/module/tools.examples.repro#L1-L40","kind":"module","name":"tools.examples.repro","path":"tools/examples/repro.py","language":"python","start_line":1,"end_line":40,"context_start_line":1,"context_end_line":40,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nT0 = fd.define_tensor(symbolic_sizes=[-1], contiguous=[True], dtype=DataType.Float)\nT1 = fd.define_tensor(symbolic_sizes=[-1], contiguous=[True], dtype=DataType.Float)\nT2 = fd.define_tensor(symbolic_sizes=[-1, -1], contiguous=[True, True], dtype=DataType.Half)\nT3 = fd.ops.broadcast_in_dim(T0, output_shape=[1, 1024, 768], broadcast_dims=[2])\nT4 = fd.ops.broadcast_in_dim(T1, output_shape=[1, 1024, 768], broadcast_dims=[2])\nT5 = fd.ops.view(T2, original_shape=[1024, 768], new_shape=[1, 1024, 768])\nT6 = fd.ops.cast(T5, dtype=DataType.Float)\nS7 = fd.define_scalar(0.500000)\nT8 = fd.ops.mul(T6, S7)\nS9 = fd.define_scalar(0.707107)\nT10 = fd.ops.mul(T6, S9)\nT11 = fd.ops.erf(T10)\nS12 = fd.define_scalar(1.00000)\nT13 = fd.ops.add(T11, S12)\nT14 = fd.ops.mul(T8, T13)\nT15 = fd.ops.cast(T14, dtype=DataType.Half)\nT16 = fd.ops.cast(T15, dtype=DataType.Float)\nT17, T18 = fd.ops.var_mean(T16, dims=[2], correction=0, keepdim=False)\nT19 = fd.ops.broadcast_in_dim(T17, output_shape=[1, 1024, 1], broadcast_dims=[0, 1])\nT20 = fd.ops.broadcast_in_dim(T18, output_shape=[1, 1024, 1], broadcast_dims=[0, 1])\nS21 = fd.define_scalar(1.00000e-05)\nT22 = fd.ops.add(T19, S21)\nT23 = fd.ops.broadcast_in_dim(T20, output_shape=[1, 1024, 768], broadcast_dims=[0, 1, 2])\nT24 = fd.ops.rsqrt(T22)\nT25 = fd.ops.sub(T16, T23)\nT26 = fd.ops.broadcast_in_dim(T24, output_shape=[1, 1024, 768], broadcast_dims=[0, 1, 2])\nT27 = fd.ops.mul(T25, T26)\nT28 = fd.ops.mul(T27, T3)\nT29 = fd.ops.add(T28, T4)\nT30 = fd.ops.cast(T29, dtype=DataType.Float)\nT31 = fd.ops.cast(T30, dtype=DataType.Half)\nT32 = fd.ops.view(T31, original_shape=[1, 1024, 768], new_shape=[1024, 768])\nfd.add_output(T5)\nfd.add_output(T16)\nfd.add_output(T20)\nfd.add_output(T24)\nfd.add_output(T32)","source_hash":"e009233f02e76811949c562c899650eea890682c90a6d39743ad629e546b8031","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.options_loader","uri":"program://Fuser/module/tools.env-config.options_loader#L1-L120","kind":"module","name":"tools.env-config.options_loader","path":"tools/env-config/options_loader.py","language":"python","start_line":1,"end_line":120,"context_start_line":1,"context_end_line":120,"code":"#!/usr/bin/env python3\n# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nLoad environment options from YAML configuration.\n\nThis module provides a loader for env_options.yaml that replaces the\nhardcoded Python definitions in configure_env.py.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport yaml\nfrom pathlib import Path\nfrom dataclasses import dataclass, field\nfrom typing import Literal\n\n\n@dataclass\nclass EnvVarOption:\n \"\"\"Represents a single environment variable option.\"\"\"\n\n name: str\n description: str\n var_type: Literal[\"bool\", \"string\", \"int\", \"multi\"]\n category: str\n env_var: str | None = None\n default: str = \"\"\n choices: list[str] = field(default_factory=list)\n current_value: str | None = None\n source: str = \"\" # Optional: tracks where in options.h this came from\n\n def get_display_name(self) -> str:\n \"\"\"Get the display name for this option.\"\"\"\n return self.name\n\n def get_env_var_name(self) -> str:\n \"\"\"Get the actual environment variable name.\"\"\"\n if self.env_var is not None:\n return self.env_var\n return self.name\n\n\ndef load_options_from_yaml(\n yaml_path: str | Path,\n) -> tuple[dict[str, str], list[EnvVarOption]]:\n \"\"\"Load environment options from YAML file.\n\n Returns:\n Tuple of (CATEGORY_NAMES dict, ENV_VAR_DEFINITIONS list)\n \"\"\"\n yaml_path = Path(yaml_path)\n\n if not yaml_path.exists():\n raise FileNotFoundError(f\"Options YAML file not found: {yaml_path}\")\n\n with open(yaml_path, \"r\") as f:\n config = yaml.safe_load(f)\n\n # Extract category names\n category_names = {}\n for cat_key, cat_info in config.get(\"categories\", {}).items():\n category_names[cat_key] = cat_info[\"display_name\"]\n\n # Extract options\n options = []\n for opt_data in config.get(\"options\", []):\n option = EnvVarOption(\n name=opt_data[\"name\"],\n description=opt_data[\"description\"],\n var_type=opt_data[\"type\"],\n category=opt_data[\"category\"],\n env_var=opt_data.get(\"env_var\"),\n default=opt_data.get(\"default\", \"\"),\n choices=opt_data.get(\"choices\", []),\n source=opt_data.get(\"source\", \"\"),\n )\n options.append(option)\n\n return category_names, options\n\n\n# For testing\nif __name__ == \"__main__\":\n import sys\n\n yaml_file = sys.argv[1] if len(sys.argv) > 1 else \"env_options.yaml\"\n\n try:\n category_names, options = load_options_from_yaml(yaml_file)\n\n print(f\"Loaded from {yaml_file}:\")\n print(f\" Categories: {len(category_names)}\")\n print(f\" Options: {len(options)}\")\n print()\n\n # Count by category\n cat_counts = {}\n for opt in options:\n cat = opt.category\n if cat not in cat_counts:\n cat_counts[cat] = 0\n cat_counts[cat] += 1\n\n print(\"Options by category:\")\n for cat, count in sorted(cat_counts.items()):\n cat_name = category_names.get(cat, cat)\n print(f\" {cat_name[:50]:50s}: {count:3d}\")\n\n except FileNotFoundError as e:\n print(f\"Error: {e}\")\n sys.exit(1)\n except Exception as e:\n print(f\"Error loading YAML: {e}\")\n import traceback\n\n traceback.print_exc()\n sys.exit(1)","source_hash":"03b87b953d9828c1cecf8f91d4058a0e9b4f9da9403eea83b5c484589c3cbd9c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.options_loader.EnvVarOption","uri":"program://Fuser/class/tools.env-config.options_loader.EnvVarOption#L22-L43","kind":"class","name":"EnvVarOption","path":"tools/env-config/options_loader.py","language":"python","start_line":22,"end_line":43,"context_start_line":2,"context_end_line":63,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nLoad environment options from YAML configuration.\n\nThis module provides a loader for env_options.yaml that replaces the\nhardcoded Python definitions in configure_env.py.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport yaml\nfrom pathlib import Path\nfrom dataclasses import dataclass, field\nfrom typing import Literal\n\n\n@dataclass\nclass EnvVarOption:\n \"\"\"Represents a single environment variable option.\"\"\"\n\n name: str\n description: str\n var_type: Literal[\"bool\", \"string\", \"int\", \"multi\"]\n category: str\n env_var: str | None = None\n default: str = \"\"\n choices: list[str] = field(default_factory=list)\n current_value: str | None = None\n source: str = \"\" # Optional: tracks where in options.h this came from\n\n def get_display_name(self) -> str:\n \"\"\"Get the display name for this option.\"\"\"\n return self.name\n\n def get_env_var_name(self) -> str:\n \"\"\"Get the actual environment variable name.\"\"\"\n if self.env_var is not None:\n return self.env_var\n return self.name\n\n\ndef load_options_from_yaml(\n yaml_path: str | Path,\n) -> tuple[dict[str, str], list[EnvVarOption]]:\n \"\"\"Load environment options from YAML file.\n\n Returns:\n Tuple of (CATEGORY_NAMES dict, ENV_VAR_DEFINITIONS list)\n \"\"\"\n yaml_path = Path(yaml_path)\n\n if not yaml_path.exists():\n raise FileNotFoundError(f\"Options YAML file not found: {yaml_path}\")\n\n with open(yaml_path, \"r\") as f:\n config = yaml.safe_load(f)\n\n # Extract category names\n category_names = {}","source_hash":"03b87b953d9828c1cecf8f91d4058a0e9b4f9da9403eea83b5c484589c3cbd9c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.options_loader.load_options_from_yaml","uri":"program://Fuser/function/tools.env-config.options_loader.load_options_from_yaml#L46-L82","kind":"function","name":"load_options_from_yaml","path":"tools/env-config/options_loader.py","language":"python","start_line":46,"end_line":82,"context_start_line":26,"context_end_line":102,"code":" description: str\n var_type: Literal[\"bool\", \"string\", \"int\", \"multi\"]\n category: str\n env_var: str | None = None\n default: str = \"\"\n choices: list[str] = field(default_factory=list)\n current_value: str | None = None\n source: str = \"\" # Optional: tracks where in options.h this came from\n\n def get_display_name(self) -> str:\n \"\"\"Get the display name for this option.\"\"\"\n return self.name\n\n def get_env_var_name(self) -> str:\n \"\"\"Get the actual environment variable name.\"\"\"\n if self.env_var is not None:\n return self.env_var\n return self.name\n\n\ndef load_options_from_yaml(\n yaml_path: str | Path,\n) -> tuple[dict[str, str], list[EnvVarOption]]:\n \"\"\"Load environment options from YAML file.\n\n Returns:\n Tuple of (CATEGORY_NAMES dict, ENV_VAR_DEFINITIONS list)\n \"\"\"\n yaml_path = Path(yaml_path)\n\n if not yaml_path.exists():\n raise FileNotFoundError(f\"Options YAML file not found: {yaml_path}\")\n\n with open(yaml_path, \"r\") as f:\n config = yaml.safe_load(f)\n\n # Extract category names\n category_names = {}\n for cat_key, cat_info in config.get(\"categories\", {}).items():\n category_names[cat_key] = cat_info[\"display_name\"]\n\n # Extract options\n options = []\n for opt_data in config.get(\"options\", []):\n option = EnvVarOption(\n name=opt_data[\"name\"],\n description=opt_data[\"description\"],\n var_type=opt_data[\"type\"],\n category=opt_data[\"category\"],\n env_var=opt_data.get(\"env_var\"),\n default=opt_data.get(\"default\", \"\"),\n choices=opt_data.get(\"choices\", []),\n source=opt_data.get(\"source\", \"\"),\n )\n options.append(option)\n\n return category_names, options\n\n\n# For testing\nif __name__ == \"__main__\":\n import sys\n\n yaml_file = sys.argv[1] if len(sys.argv) > 1 else \"env_options.yaml\"\n\n try:\n category_names, options = load_options_from_yaml(yaml_file)\n\n print(f\"Loaded from {yaml_file}:\")\n print(f\" Categories: {len(category_names)}\")\n print(f\" Options: {len(options)}\")\n print()\n\n # Count by category\n cat_counts = {}\n for opt in options:\n cat = opt.category","source_hash":"03b87b953d9828c1cecf8f91d4058a0e9b4f9da9403eea83b5c484589c3cbd9c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.options_loader.get_display_name","uri":"program://Fuser/function/tools.env-config.options_loader.get_display_name#L35-L37","kind":"function","name":"get_display_name","path":"tools/env-config/options_loader.py","language":"python","start_line":35,"end_line":37,"context_start_line":15,"context_end_line":57,"code":"import yaml\nfrom pathlib import Path\nfrom dataclasses import dataclass, field\nfrom typing import Literal\n\n\n@dataclass\nclass EnvVarOption:\n \"\"\"Represents a single environment variable option.\"\"\"\n\n name: str\n description: str\n var_type: Literal[\"bool\", \"string\", \"int\", \"multi\"]\n category: str\n env_var: str | None = None\n default: str = \"\"\n choices: list[str] = field(default_factory=list)\n current_value: str | None = None\n source: str = \"\" # Optional: tracks where in options.h this came from\n\n def get_display_name(self) -> str:\n \"\"\"Get the display name for this option.\"\"\"\n return self.name\n\n def get_env_var_name(self) -> str:\n \"\"\"Get the actual environment variable name.\"\"\"\n if self.env_var is not None:\n return self.env_var\n return self.name\n\n\ndef load_options_from_yaml(\n yaml_path: str | Path,\n) -> tuple[dict[str, str], list[EnvVarOption]]:\n \"\"\"Load environment options from YAML file.\n\n Returns:\n Tuple of (CATEGORY_NAMES dict, ENV_VAR_DEFINITIONS list)\n \"\"\"\n yaml_path = Path(yaml_path)\n\n if not yaml_path.exists():\n raise FileNotFoundError(f\"Options YAML file not found: {yaml_path}\")","source_hash":"03b87b953d9828c1cecf8f91d4058a0e9b4f9da9403eea83b5c484589c3cbd9c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.options_loader.get_env_var_name","uri":"program://Fuser/function/tools.env-config.options_loader.get_env_var_name#L39-L43","kind":"function","name":"get_env_var_name","path":"tools/env-config/options_loader.py","language":"python","start_line":39,"end_line":43,"context_start_line":19,"context_end_line":63,"code":"\n\n@dataclass\nclass EnvVarOption:\n \"\"\"Represents a single environment variable option.\"\"\"\n\n name: str\n description: str\n var_type: Literal[\"bool\", \"string\", \"int\", \"multi\"]\n category: str\n env_var: str | None = None\n default: str = \"\"\n choices: list[str] = field(default_factory=list)\n current_value: str | None = None\n source: str = \"\" # Optional: tracks where in options.h this came from\n\n def get_display_name(self) -> str:\n \"\"\"Get the display name for this option.\"\"\"\n return self.name\n\n def get_env_var_name(self) -> str:\n \"\"\"Get the actual environment variable name.\"\"\"\n if self.env_var is not None:\n return self.env_var\n return self.name\n\n\ndef load_options_from_yaml(\n yaml_path: str | Path,\n) -> tuple[dict[str, str], list[EnvVarOption]]:\n \"\"\"Load environment options from YAML file.\n\n Returns:\n Tuple of (CATEGORY_NAMES dict, ENV_VAR_DEFINITIONS list)\n \"\"\"\n yaml_path = Path(yaml_path)\n\n if not yaml_path.exists():\n raise FileNotFoundError(f\"Options YAML file not found: {yaml_path}\")\n\n with open(yaml_path, \"r\") as f:\n config = yaml.safe_load(f)\n\n # Extract category names\n category_names = {}","source_hash":"03b87b953d9828c1cecf8f91d4058a0e9b4f9da9403eea83b5c484589c3cbd9c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui","uri":"program://Fuser/module/tools.env-config.curses_ui#L1-L894","kind":"module","name":"tools.env-config.curses_ui","path":"tools/env-config/curses_ui.py","language":"python","start_line":1,"end_line":894,"context_start_line":1,"context_end_line":894,"code":"#!/usr/bin/env python3\n# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nCurses-based TUI for nvFuser environment configuration.\nProvides a ccmake-like interface for navigating and configuring options.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport curses\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from configure_env import EnvVarConfig\n\nfrom configure_env import CATEGORY_NAMES\n\n\nclass CursesUI:\n \"\"\"Curses-based UI for environment configuration.\"\"\"\n\n def __init__(self, stdscr, config: EnvVarConfig) -> None:\n self.stdscr = stdscr\n self.config = config\n self.current_row: int = 0\n self.top_row: int = 0\n self.modified: bool = False\n self.should_exit: bool = False\n self.search_mode: bool = False\n self.search_query: str = \"\"\n self.search_matches: list[int] = [] # Indices of matching items\n self.search_match_index: int = 0 # Current match we're at\n\n # Build flat list of all options with category headers\n self.display_items: list[dict[str, str | object]] = []\n\n # Display categories in the order defined in CATEGORY_NAMES\n for category in CATEGORY_NAMES.keys():\n if category not in config.categories:\n continue\n opts = config.categories[category]\n # Add category header\n self.display_items.append(\n {\n \"type\": \"header\",\n \"text\": CATEGORY_NAMES[category],\n }\n )\n # Add options\n for opt in opts:\n self.display_items.append(\n {\n \"type\": \"option\",\n \"option\": opt,\n }\n )\n\n # Initialize curses\n curses.curs_set(0) # Hide cursor\n curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) # Highlight\n curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) # Header\n curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) # Enabled/Set\n curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK) # Multi tag\n\n def draw_header(self) -> None:\n \"\"\"Draw the top header.\"\"\"\n height, width = self.stdscr.getmaxyx()\n self.stdscr.attron(curses.color_pair(2) | curses.A_BOLD)\n header = \"nvFuser Environment Configuration\"\n self.stdscr.addstr(0, (width - len(header)) // 2, header)\n self.stdscr.attroff(curses.color_pair(2) | curses.A_BOLD)\n\n def draw_footer(self) -> None:\n \"\"\"Draw the bottom help text.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n # Show search mode or normal help\n if self.search_mode:\n help_text = f\"/{self.search_query}\"\n if self.search_matches:\n help_text += (\n f\" [{self.search_match_index + 1}/{len(self.search_matches)}]\"\n )\n help_text = help_text.ljust(width - 1)\n else:\n # Show context-sensitive help based on current selection\n item = (\n self.display_items[self.current_row]\n if self.current_row < len(self.display_items)\n else None\n )\n\n if item and item[\"type\"] == \"option\":\n opt = item[\"option\"]\n match opt.var_type:\n case \"bool\":\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Toggle [r] Reload [a] Apply [g] Gen [q] Quit\"\n case \"multi\":\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Cycle [r] Reload [a] Apply [g] Gen [q] Quit\"\n case _:\n # String/Int - Enter to edit\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Edit [r] Reload [a] Apply [g] Gen [q] Quit\"\n else:\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Toggle [r] Reload [a] Apply [g] Gen [q] Quit\"\n\n if self.modified:\n help_text = \"[MODIFIED] \" + help_text\n\n self.stdscr.attron(curses.color_pair(2))\n self.stdscr.addstr(height - 1, 0, help_text.ljust(width - 1))\n self.stdscr.attroff(curses.color_pair(2))\n\n def draw_option(\n self, y: int, item: dict[str, str | object], is_selected: bool\n ) -> None:\n \"\"\"Draw a single option or header.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n if y < 2 or y >= height - 1:\n return # Skip if outside visible area\n\n if item[\"type\"] == \"header\":\n # Draw category header\n attr = curses.color_pair(2) | curses.A_BOLD\n if is_selected:\n attr |= curses.A_REVERSE\n self.stdscr.attron(attr)\n self.stdscr.addstr(y, 0, (\" \" + item[\"text\"]).ljust(width - 1))\n self.stdscr.attroff(attr)\n\n elif item[\"type\"] == \"option\":\n opt = item[\"option\"]\n base_attr = 0\n\n if is_selected:\n base_attr |= curses.A_REVERSE\n\n # Format the option display\n # All options get a checkbox at the beginning showing if they're set\n prefix = \" \" # 3 spaces for better visual separation\n\n if opt.var_type == \"bool\":\n # Boolean option - checkbox shows enabled/disabled status\n name_part = opt.get_display_name()\n\n if opt.current_value == \"1\":\n checkbox = \"[X] \"\n attr = base_attr | curses.color_pair(3) # Green for enabled\n else:\n checkbox = \"[ ] \"\n attr = base_attr\n\n line = f\"{prefix}{checkbox}{name_part}\"\n max_len = width - 1\n if len(line) > max_len:\n line = line[: max_len - 3] + \"...\"\n\n self.stdscr.attron(attr)\n self.stdscr.addstr(y, 0, line.ljust(width - 1))\n self.stdscr.attroff(attr)\n\n else:\n # String/int/multi option with value display and checkbox\n display_name = opt.get_display_name()\n\n # Determine if this option has a value (affects checkbox and color)\n has_value = opt.current_value is not None\n line_attr = base_attr | curses.color_pair(3) if has_value else base_attr\n\n # Add checkbox at the beginning - checked if value is set\n if has_value:\n checkbox = \"[X] \"\n else:\n checkbox = \"[ ] \"\n\n name_part = f\"{prefix}{checkbox}{display_name}\"\n\n # Draw name part with checkbox (green if value is set)\n self.stdscr.attron(line_attr)\n self.stdscr.addstr(y, 0, name_part)\n self.stdscr.attroff(line_attr)\n\n # Add [multi] tag in yellow for multi-choice options\n multi_tag_len = 0\n if opt.var_type == \"multi\":\n multi_tag = \" [multi]\"\n multi_tag_len = len(multi_tag)\n multi_attr = base_attr | curses.color_pair(4) # Yellow\n self.stdscr.attron(multi_attr)\n self.stdscr.addstr(y, len(name_part), multi_tag)\n self.stdscr.attroff(multi_attr)\n\n # Draw value part (green if set)\n if opt.current_value:\n value_part = f\" = {opt.current_value}\"\n else:\n # Show = \"\" for empty string/int/multi to indicate they expect values\n value_part = ' = \"\"'\n\n # Calculate remaining space\n total_prefix = len(name_part) + multi_tag_len\n remaining_space = width - 1 - total_prefix\n if len(value_part) > remaining_space:\n value_part = value_part[: remaining_space - 3] + \"...\"\n\n self.stdscr.attron(line_attr)\n self.stdscr.addstr(y, total_prefix, value_part)\n\n # Pad the rest of the line\n total_len = total_prefix + len(value_part)\n if total_len < width - 1:\n self.stdscr.addstr(y, total_len, \" \" * (width - 1 - total_len))\n self.stdscr.attroff(line_attr)\n\n def draw_description(self) -> None:\n \"\"\"Draw description of currently selected item.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n # Draw description area separator\n desc_start = height - 5\n self.stdscr.hline(desc_start, 0, curses.ACS_HLINE, width)\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n desc_y = desc_start + 1\n\n # Wrap description text\n desc_text = f\"Description: {opt.description}\"\n\n # Add choices for multi options\n if opt.var_type == \"multi\" and opt.choices:\n desc_text += f\" | Choices: {', '.join(repr(c) for c in opt.choices)}\"\n\n words = desc_text.split()\n lines = []\n current_line = \"\"\n\n for word in words:\n if len(current_line) + len(word) + 1 <= width - 2:\n current_line += word + \" \"\n else:\n lines.append(current_line.strip())\n current_line = word + \" \"\n if current_line:\n lines.append(current_line.strip())\n\n # Draw description lines\n for i, line in enumerate(lines[:3]): # Max 3 lines\n if desc_y + i < height - 1:\n self.stdscr.addstr(desc_y + i, 1, line)\n\n def draw(self) -> None:\n \"\"\"Draw the entire UI.\"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n self.draw_header()\n\n # Draw options list\n visible_rows = height - 7 # Leave space for header, description, footer\n for i, item in enumerate(\n self.display_items[self.top_row : self.top_row + visible_rows]\n ):\n self.draw_option(i + 2, item, i + self.top_row == self.current_row)\n\n self.draw_description()\n self.draw_footer()\n\n self.stdscr.refresh()\n\n def handle_toggle(self) -> None:\n \"\"\"Handle toggling/editing current item.\"\"\"\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n\n match opt.var_type:\n case \"bool\":\n # Toggle boolean\n opt.current_value = \"1\" if opt.current_value != \"1\" else None\n self.modified = True\n\n case \"multi\":\n # Cycle through choices, including unset at the end\n # Note: Some choices may include \"\" (empty string) as a valid choice\n if opt.current_value is None:\n # Currently unset, go to first choice\n opt.current_value = opt.choices[0] if opt.choices else \"\"\n elif opt.current_value not in opt.choices:\n # Invalid value, go to first choice\n opt.current_value = opt.choices[0] if opt.choices else \"\"\n else:\n # Valid value, cycle to next (or back to None after last)\n idx = opt.choices.index(opt.current_value)\n if idx == len(opt.choices) - 1:\n # Last choice, cycle back to unset (None)\n opt.current_value = None\n else:\n # Go to next choice\n opt.current_value = opt.choices[idx + 1]\n self.modified = True\n\n case \"int\" | \"string\":\n # For string/int, Enter opens the editor\n self.handle_edit()\n\n def handle_edit(self) -> None:\n \"\"\"Handle editing current item value.\"\"\"\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n\n if opt.var_type in [\"int\", \"string\", \"multi\"]:\n height, width = self.stdscr.getmaxyx()\n\n # Calculate the Y position of the current row on screen\n # Rows start at y=2 (after header), and we need to account for scroll\n screen_y = 2 + (self.current_row - self.top_row)\n\n # Make sure we're within visible area\n if screen_y < 2 or screen_y >= height - 5:\n # Fall back to center if somehow out of range\n screen_y = height // 2\n\n # Build the display name with [multi] tag if applicable\n display_name = opt.get_display_name()\n if opt.var_type == \"multi\":\n display_name += \" [multi]\"\n\n # Get current value to pre-fill\n current_val = opt.current_value if opt.current_value else \"\"\n\n # Create prompt: \"name = |cursor here|\"\n prefix = \" \"\n prompt_text = f\"{prefix}{display_name} = \"\n\n # Clear the line and show the prompt\n self.stdscr.move(screen_y, 0)\n self.stdscr.clrtoeol()\n self.stdscr.addstr(screen_y, 0, prompt_text, curses.A_BOLD)\n\n # Pre-fill with current value\n if current_val:\n self.stdscr.addstr(screen_y, len(prompt_text), current_val)\n\n self.stdscr.refresh()\n\n # Position cursor at the end of the current value\n cursor_pos = len(prompt_text) + len(current_val)\n self.stdscr.move(screen_y, cursor_pos)\n\n # Enable cursor and echo\n curses.curs_set(1)\n curses.echo()\n\n try:\n # Manual text editing with basic line editing support\n buffer = list(current_val) # Start with current value\n cursor_offset = len(buffer) # Cursor at end\n max_len = width - len(prompt_text) - 2\n\n while True:\n # Display current buffer\n self.stdscr.move(screen_y, len(prompt_text))\n self.stdscr.clrtoeol()\n display_text = \"\".join(buffer)\n if len(display_text) > max_len:\n display_text = display_text[:max_len]\n self.stdscr.addstr(screen_y, len(prompt_text), display_text)\n self.stdscr.move(screen_y, len(prompt_text) + cursor_offset)\n self.stdscr.refresh()\n\n # Get key\n key = self.stdscr.getch()\n\n if key == ord(\"\\n\") or key == curses.KEY_ENTER:\n # Accept input\n value = \"\".join(buffer).strip()\n if value or opt.current_value: # Allow clearing\n opt.current_value = value if value else None\n self.modified = True\n break\n elif key == 27: # Escape\n # Cancel editing\n break\n elif key == curses.KEY_BACKSPACE or key == 127 or key == 8:\n # Backspace\n if cursor_offset > 0:\n buffer.pop(cursor_offset - 1)\n cursor_offset -= 1\n elif key == curses.KEY_DC:\n # Delete key\n if cursor_offset < len(buffer):\n buffer.pop(cursor_offset)\n elif key == curses.KEY_LEFT:\n # Move cursor left\n if cursor_offset > 0:\n cursor_offset -= 1\n elif key == curses.KEY_RIGHT:\n # Move cursor right\n if cursor_offset < len(buffer):\n cursor_offset += 1\n elif key == curses.KEY_HOME or key == 1: # Ctrl-A\n # Move to start\n cursor_offset = 0\n elif key == curses.KEY_END or key == 5: # Ctrl-E\n # Move to end\n cursor_offset = len(buffer)\n elif key == 21: # Ctrl-U\n # Clear line\n buffer = []\n cursor_offset = 0\n elif 32 <= key <= 126:\n # Printable character\n if len(buffer) < max_len:\n buffer.insert(cursor_offset, chr(key))\n cursor_offset += 1\n\n except Exception:\n pass\n finally:\n curses.noecho()\n curses.curs_set(0)\n\n def show_confirmation(self, message: str, prompt: str) -> str:\n \"\"\"Show a simple y/n confirmation dialog.\n\n Returns the character pressed by the user (y/n/etc).\n \"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Center the message\n y = height // 2\n x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show prompt below\n y += 2\n x = max(0, (width - len(prompt)) // 2)\n self.stdscr.addstr(y, x, prompt)\n\n self.stdscr.refresh()\n\n # Get single character response\n response = self.stdscr.getch()\n if response == 27: # Escape\n return \"n\"\n return chr(response) if response < 256 else \"n\"\n\n def show_message(\n self, message: str, submessage: str = \"\", wait_for_key: bool = True\n ) -> None:\n \"\"\"Show a simple message dialog\"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Center the message\n y = height // 2\n x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show submessage below\n if submessage:\n y += 2\n x = max(0, (width - len(submessage)) // 2)\n self.stdscr.addstr(y, x, submessage)\n\n if wait_for_key:\n y += 2\n prompt = \"Press any key to continue...\"\n x = max(0, (width - len(prompt)) // 2)\n self.stdscr.addstr(y, x, prompt)\n\n self.stdscr.refresh()\n\n if wait_for_key:\n self.stdscr.getch()\n\n def handle_apply_now(self) -> None:\n \"\"\"Show confirmation, generate apply script, and signal to exit\"\"\"\n # Import save_config here to avoid circular import\n from configure_env import save_config\n import os\n import sys\n import tempfile\n\n # Show confirmation dialog\n response = self.show_confirmation(\"Apply configuration and exit?\", \"[y/N]\")\n\n if response not in [\"y\", \"Y\"]:\n return # User cancel\n# ... truncated ...","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":true} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.CursesUI","uri":"program://Fuser/class/tools.env-config.curses_ui.CursesUI#L22-L888","kind":"class","name":"CursesUI","path":"tools/env-config/curses_ui.py","language":"python","start_line":22,"end_line":888,"context_start_line":2,"context_end_line":894,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nCurses-based TUI for nvFuser environment configuration.\nProvides a ccmake-like interface for navigating and configuring options.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport curses\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from configure_env import EnvVarConfig\n\nfrom configure_env import CATEGORY_NAMES\n\n\nclass CursesUI:\n \"\"\"Curses-based UI for environment configuration.\"\"\"\n\n def __init__(self, stdscr, config: EnvVarConfig) -> None:\n self.stdscr = stdscr\n self.config = config\n self.current_row: int = 0\n self.top_row: int = 0\n self.modified: bool = False\n self.should_exit: bool = False\n self.search_mode: bool = False\n self.search_query: str = \"\"\n self.search_matches: list[int] = [] # Indices of matching items\n self.search_match_index: int = 0 # Current match we're at\n\n # Build flat list of all options with category headers\n self.display_items: list[dict[str, str | object]] = []\n\n # Display categories in the order defined in CATEGORY_NAMES\n for category in CATEGORY_NAMES.keys():\n if category not in config.categories:\n continue\n opts = config.categories[category]\n # Add category header\n self.display_items.append(\n {\n \"type\": \"header\",\n \"text\": CATEGORY_NAMES[category],\n }\n )\n # Add options\n for opt in opts:\n self.display_items.append(\n {\n \"type\": \"option\",\n \"option\": opt,\n }\n )\n\n # Initialize curses\n curses.curs_set(0) # Hide cursor\n curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) # Highlight\n curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) # Header\n curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) # Enabled/Set\n curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK) # Multi tag\n\n def draw_header(self) -> None:\n \"\"\"Draw the top header.\"\"\"\n height, width = self.stdscr.getmaxyx()\n self.stdscr.attron(curses.color_pair(2) | curses.A_BOLD)\n header = \"nvFuser Environment Configuration\"\n self.stdscr.addstr(0, (width - len(header)) // 2, header)\n self.stdscr.attroff(curses.color_pair(2) | curses.A_BOLD)\n\n def draw_footer(self) -> None:\n \"\"\"Draw the bottom help text.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n # Show search mode or normal help\n if self.search_mode:\n help_text = f\"/{self.search_query}\"\n if self.search_matches:\n help_text += (\n f\" [{self.search_match_index + 1}/{len(self.search_matches)}]\"\n )\n help_text = help_text.ljust(width - 1)\n else:\n # Show context-sensitive help based on current selection\n item = (\n self.display_items[self.current_row]\n if self.current_row < len(self.display_items)\n else None\n )\n\n if item and item[\"type\"] == \"option\":\n opt = item[\"option\"]\n match opt.var_type:\n case \"bool\":\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Toggle [r] Reload [a] Apply [g] Gen [q] Quit\"\n case \"multi\":\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Cycle [r] Reload [a] Apply [g] Gen [q] Quit\"\n case _:\n # String/Int - Enter to edit\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Edit [r] Reload [a] Apply [g] Gen [q] Quit\"\n else:\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Toggle [r] Reload [a] Apply [g] Gen [q] Quit\"\n\n if self.modified:\n help_text = \"[MODIFIED] \" + help_text\n\n self.stdscr.attron(curses.color_pair(2))\n self.stdscr.addstr(height - 1, 0, help_text.ljust(width - 1))\n self.stdscr.attroff(curses.color_pair(2))\n\n def draw_option(\n self, y: int, item: dict[str, str | object], is_selected: bool\n ) -> None:\n \"\"\"Draw a single option or header.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n if y < 2 or y >= height - 1:\n return # Skip if outside visible area\n\n if item[\"type\"] == \"header\":\n # Draw category header\n attr = curses.color_pair(2) | curses.A_BOLD\n if is_selected:\n attr |= curses.A_REVERSE\n self.stdscr.attron(attr)\n self.stdscr.addstr(y, 0, (\" \" + item[\"text\"]).ljust(width - 1))\n self.stdscr.attroff(attr)\n\n elif item[\"type\"] == \"option\":\n opt = item[\"option\"]\n base_attr = 0\n\n if is_selected:\n base_attr |= curses.A_REVERSE\n\n # Format the option display\n # All options get a checkbox at the beginning showing if they're set\n prefix = \" \" # 3 spaces for better visual separation\n\n if opt.var_type == \"bool\":\n # Boolean option - checkbox shows enabled/disabled status\n name_part = opt.get_display_name()\n\n if opt.current_value == \"1\":\n checkbox = \"[X] \"\n attr = base_attr | curses.color_pair(3) # Green for enabled\n else:\n checkbox = \"[ ] \"\n attr = base_attr\n\n line = f\"{prefix}{checkbox}{name_part}\"\n max_len = width - 1\n if len(line) > max_len:\n line = line[: max_len - 3] + \"...\"\n\n self.stdscr.attron(attr)\n self.stdscr.addstr(y, 0, line.ljust(width - 1))\n self.stdscr.attroff(attr)\n\n else:\n # String/int/multi option with value display and checkbox\n display_name = opt.get_display_name()\n\n # Determine if this option has a value (affects checkbox and color)\n has_value = opt.current_value is not None\n line_attr = base_attr | curses.color_pair(3) if has_value else base_attr\n\n # Add checkbox at the beginning - checked if value is set\n if has_value:\n checkbox = \"[X] \"\n else:\n checkbox = \"[ ] \"\n\n name_part = f\"{prefix}{checkbox}{display_name}\"\n\n # Draw name part with checkbox (green if value is set)\n self.stdscr.attron(line_attr)\n self.stdscr.addstr(y, 0, name_part)\n self.stdscr.attroff(line_attr)\n\n # Add [multi] tag in yellow for multi-choice options\n multi_tag_len = 0\n if opt.var_type == \"multi\":\n multi_tag = \" [multi]\"\n multi_tag_len = len(multi_tag)\n multi_attr = base_attr | curses.color_pair(4) # Yellow\n self.stdscr.attron(multi_attr)\n self.stdscr.addstr(y, len(name_part), multi_tag)\n self.stdscr.attroff(multi_attr)\n\n # Draw value part (green if set)\n if opt.current_value:\n value_part = f\" = {opt.current_value}\"\n else:\n # Show = \"\" for empty string/int/multi to indicate they expect values\n value_part = ' = \"\"'\n\n # Calculate remaining space\n total_prefix = len(name_part) + multi_tag_len\n remaining_space = width - 1 - total_prefix\n if len(value_part) > remaining_space:\n value_part = value_part[: remaining_space - 3] + \"...\"\n\n self.stdscr.attron(line_attr)\n self.stdscr.addstr(y, total_prefix, value_part)\n\n # Pad the rest of the line\n total_len = total_prefix + len(value_part)\n if total_len < width - 1:\n self.stdscr.addstr(y, total_len, \" \" * (width - 1 - total_len))\n self.stdscr.attroff(line_attr)\n\n def draw_description(self) -> None:\n \"\"\"Draw description of currently selected item.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n # Draw description area separator\n desc_start = height - 5\n self.stdscr.hline(desc_start, 0, curses.ACS_HLINE, width)\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n desc_y = desc_start + 1\n\n # Wrap description text\n desc_text = f\"Description: {opt.description}\"\n\n # Add choices for multi options\n if opt.var_type == \"multi\" and opt.choices:\n desc_text += f\" | Choices: {', '.join(repr(c) for c in opt.choices)}\"\n\n words = desc_text.split()\n lines = []\n current_line = \"\"\n\n for word in words:\n if len(current_line) + len(word) + 1 <= width - 2:\n current_line += word + \" \"\n else:\n lines.append(current_line.strip())\n current_line = word + \" \"\n if current_line:\n lines.append(current_line.strip())\n\n # Draw description lines\n for i, line in enumerate(lines[:3]): # Max 3 lines\n if desc_y + i < height - 1:\n self.stdscr.addstr(desc_y + i, 1, line)\n\n def draw(self) -> None:\n \"\"\"Draw the entire UI.\"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n self.draw_header()\n\n # Draw options list\n visible_rows = height - 7 # Leave space for header, description, footer\n for i, item in enumerate(\n self.display_items[self.top_row : self.top_row + visible_rows]\n ):\n self.draw_option(i + 2, item, i + self.top_row == self.current_row)\n\n self.draw_description()\n self.draw_footer()\n\n self.stdscr.refresh()\n\n def handle_toggle(self) -> None:\n \"\"\"Handle toggling/editing current item.\"\"\"\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n\n match opt.var_type:\n case \"bool\":\n # Toggle boolean\n opt.current_value = \"1\" if opt.current_value != \"1\" else None\n self.modified = True\n\n case \"multi\":\n # Cycle through choices, including unset at the end\n # Note: Some choices may include \"\" (empty string) as a valid choice\n if opt.current_value is None:\n # Currently unset, go to first choice\n opt.current_value = opt.choices[0] if opt.choices else \"\"\n elif opt.current_value not in opt.choices:\n # Invalid value, go to first choice\n opt.current_value = opt.choices[0] if opt.choices else \"\"\n else:\n # Valid value, cycle to next (or back to None after last)\n idx = opt.choices.index(opt.current_value)\n if idx == len(opt.choices) - 1:\n # Last choice, cycle back to unset (None)\n opt.current_value = None\n else:\n # Go to next choice\n opt.current_value = opt.choices[idx + 1]\n self.modified = True\n\n case \"int\" | \"string\":\n # For string/int, Enter opens the editor\n self.handle_edit()\n\n def handle_edit(self) -> None:\n \"\"\"Handle editing current item value.\"\"\"\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n\n if opt.var_type in [\"int\", \"string\", \"multi\"]:\n height, width = self.stdscr.getmaxyx()\n\n # Calculate the Y position of the current row on screen\n # Rows start at y=2 (after header), and we need to account for scroll\n screen_y = 2 + (self.current_row - self.top_row)\n\n # Make sure we're within visible area\n if screen_y < 2 or screen_y >= height - 5:\n # Fall back to center if somehow out of range\n screen_y = height // 2\n\n # Build the display name with [multi] tag if applicable\n display_name = opt.get_display_name()\n if opt.var_type == \"multi\":\n display_name += \" [multi]\"\n\n # Get current value to pre-fill\n current_val = opt.current_value if opt.current_value else \"\"\n\n # Create prompt: \"name = |cursor here|\"\n prefix = \" \"\n prompt_text = f\"{prefix}{display_name} = \"\n\n # Clear the line and show the prompt\n self.stdscr.move(screen_y, 0)\n self.stdscr.clrtoeol()\n self.stdscr.addstr(screen_y, 0, prompt_text, curses.A_BOLD)\n\n # Pre-fill with current value\n if current_val:\n self.stdscr.addstr(screen_y, len(prompt_text), current_val)\n\n self.stdscr.refresh()\n\n # Position cursor at the end of the current value\n cursor_pos = len(prompt_text) + len(current_val)\n self.stdscr.move(screen_y, cursor_pos)\n\n # Enable cursor and echo\n curses.curs_set(1)\n curses.echo()\n\n try:\n # Manual text editing with basic line editing support\n buffer = list(current_val) # Start with current value\n cursor_offset = len(buffer) # Cursor at end\n max_len = width - len(prompt_text) - 2\n\n while True:\n # Display current buffer\n self.stdscr.move(screen_y, len(prompt_text))\n self.stdscr.clrtoeol()\n display_text = \"\".join(buffer)\n if len(display_text) > max_len:\n display_text = display_text[:max_len]\n self.stdscr.addstr(screen_y, len(prompt_text), display_text)\n self.stdscr.move(screen_y, len(prompt_text) + cursor_offset)\n self.stdscr.refresh()\n\n # Get key\n key = self.stdscr.getch()\n\n if key == ord(\"\\n\") or key == curses.KEY_ENTER:\n # Accept input\n value = \"\".join(buffer).strip()\n if value or opt.current_value: # Allow clearing\n opt.current_value = value if value else None\n self.modified = True\n break\n elif key == 27: # Escape\n # Cancel editing\n break\n elif key == curses.KEY_BACKSPACE or key == 127 or key == 8:\n # Backspace\n if cursor_offset > 0:\n buffer.pop(cursor_offset - 1)\n cursor_offset -= 1\n elif key == curses.KEY_DC:\n # Delete key\n if cursor_offset < len(buffer):\n buffer.pop(cursor_offset)\n elif key == curses.KEY_LEFT:\n # Move cursor left\n if cursor_offset > 0:\n cursor_offset -= 1\n elif key == curses.KEY_RIGHT:\n # Move cursor right\n if cursor_offset < len(buffer):\n cursor_offset += 1\n elif key == curses.KEY_HOME or key == 1: # Ctrl-A\n # Move to start\n cursor_offset = 0\n elif key == curses.KEY_END or key == 5: # Ctrl-E\n # Move to end\n cursor_offset = len(buffer)\n elif key == 21: # Ctrl-U\n # Clear line\n buffer = []\n cursor_offset = 0\n elif 32 <= key <= 126:\n # Printable character\n if len(buffer) < max_len:\n buffer.insert(cursor_offset, chr(key))\n cursor_offset += 1\n\n except Exception:\n pass\n finally:\n curses.noecho()\n curses.curs_set(0)\n\n def show_confirmation(self, message: str, prompt: str) -> str:\n \"\"\"Show a simple y/n confirmation dialog.\n\n Returns the character pressed by the user (y/n/etc).\n \"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Center the message\n y = height // 2\n x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show prompt below\n y += 2\n x = max(0, (width - len(prompt)) // 2)\n self.stdscr.addstr(y, x, prompt)\n\n self.stdscr.refresh()\n\n # Get single character response\n response = self.stdscr.getch()\n if response == 27: # Escape\n return \"n\"\n return chr(response) if response < 256 else \"n\"\n\n def show_message(\n self, message: str, submessage: str = \"\", wait_for_key: bool = True\n ) -> None:\n \"\"\"Show a simple message dialog\"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Center the message\n y = height // 2\n x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show submessage below\n if submessage:\n y += 2\n x = max(0, (width - len(submessage)) // 2)\n self.stdscr.addstr(y, x, submessage)\n\n if wait_for_key:\n y += 2\n prompt = \"Press any key to continue...\"\n x = max(0, (width - len(prompt)) // 2)\n self.stdscr.addstr(y, x, prompt)\n\n self.stdscr.refresh()\n\n if wait_for_key:\n self.stdscr.getch()\n\n def handle_apply_now(self) -> None:\n \"\"\"Show confirmation, generate apply script, and signal to exit\"\"\"\n # Import save_config here to avoid circular import\n from configure_env import save_config\n import os\n import sys\n import tempfile\n\n # Show confirmation dialog\n response = self.show_confirmation(\"Apply configuration and exit?\", \"[y/N]\")\n\n if response not in [\"y\", \"Y\"]:\n return # User cancelled\n\n # Get expo\n# ... truncated ...","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":true} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.run_curses_ui","uri":"program://Fuser/function/tools.env-config.curses_ui.run_curses_ui#L891-L894","kind":"function","name":"run_curses_ui","path":"tools/env-config/curses_ui.py","language":"python","start_line":891,"end_line":894,"context_start_line":871,"context_end_line":894,"code":" break # Exit immediately after apply\n\n elif key == ord(\"g\") or key == ord(\"G\"):\n self.handle_generate()\n if self.should_exit:\n break # Exit immediately after generate\n\n elif key == ord(\"/\"):\n # Enter search mode\n self.handle_search()\n\n elif key == ord(\"n\"):\n # Jump to next search match\n self.jump_to_next_match()\n\n elif key == ord(\"N\"):\n # Jump to previous search match\n self.jump_to_prev_match()\n\n\ndef run_curses_ui(stdscr, config: EnvVarConfig) -> None:\n \"\"\"Entry point for curses UI.\"\"\"\n ui = CursesUI(stdscr, config)\n ui.run()","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.__init__","uri":"program://Fuser/function/tools.env-config.curses_ui.__init__#L25-L66","kind":"function","name":"__init__","path":"tools/env-config/curses_ui.py","language":"python","start_line":25,"end_line":66,"context_start_line":5,"context_end_line":86,"code":"\n\"\"\"\nCurses-based TUI for nvFuser environment configuration.\nProvides a ccmake-like interface for navigating and configuring options.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport curses\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from configure_env import EnvVarConfig\n\nfrom configure_env import CATEGORY_NAMES\n\n\nclass CursesUI:\n \"\"\"Curses-based UI for environment configuration.\"\"\"\n\n def __init__(self, stdscr, config: EnvVarConfig) -> None:\n self.stdscr = stdscr\n self.config = config\n self.current_row: int = 0\n self.top_row: int = 0\n self.modified: bool = False\n self.should_exit: bool = False\n self.search_mode: bool = False\n self.search_query: str = \"\"\n self.search_matches: list[int] = [] # Indices of matching items\n self.search_match_index: int = 0 # Current match we're at\n\n # Build flat list of all options with category headers\n self.display_items: list[dict[str, str | object]] = []\n\n # Display categories in the order defined in CATEGORY_NAMES\n for category in CATEGORY_NAMES.keys():\n if category not in config.categories:\n continue\n opts = config.categories[category]\n # Add category header\n self.display_items.append(\n {\n \"type\": \"header\",\n \"text\": CATEGORY_NAMES[category],\n }\n )\n # Add options\n for opt in opts:\n self.display_items.append(\n {\n \"type\": \"option\",\n \"option\": opt,\n }\n )\n\n # Initialize curses\n curses.curs_set(0) # Hide cursor\n curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) # Highlight\n curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) # Header\n curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) # Enabled/Set\n curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK) # Multi tag\n\n def draw_header(self) -> None:\n \"\"\"Draw the top header.\"\"\"\n height, width = self.stdscr.getmaxyx()\n self.stdscr.attron(curses.color_pair(2) | curses.A_BOLD)\n header = \"nvFuser Environment Configuration\"\n self.stdscr.addstr(0, (width - len(header)) // 2, header)\n self.stdscr.attroff(curses.color_pair(2) | curses.A_BOLD)\n\n def draw_footer(self) -> None:\n \"\"\"Draw the bottom help text.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n # Show search mode or normal help\n if self.search_mode:\n help_text = f\"/{self.search_query}\"\n if self.search_matches:\n help_text += (\n f\" [{self.search_match_index + 1}/{len(self.search_matches)}]\"\n )","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.draw_header","uri":"program://Fuser/function/tools.env-config.curses_ui.draw_header#L68-L74","kind":"function","name":"draw_header","path":"tools/env-config/curses_ui.py","language":"python","start_line":68,"end_line":74,"context_start_line":48,"context_end_line":94,"code":" \"type\": \"header\",\n \"text\": CATEGORY_NAMES[category],\n }\n )\n # Add options\n for opt in opts:\n self.display_items.append(\n {\n \"type\": \"option\",\n \"option\": opt,\n }\n )\n\n # Initialize curses\n curses.curs_set(0) # Hide cursor\n curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) # Highlight\n curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) # Header\n curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) # Enabled/Set\n curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK) # Multi tag\n\n def draw_header(self) -> None:\n \"\"\"Draw the top header.\"\"\"\n height, width = self.stdscr.getmaxyx()\n self.stdscr.attron(curses.color_pair(2) | curses.A_BOLD)\n header = \"nvFuser Environment Configuration\"\n self.stdscr.addstr(0, (width - len(header)) // 2, header)\n self.stdscr.attroff(curses.color_pair(2) | curses.A_BOLD)\n\n def draw_footer(self) -> None:\n \"\"\"Draw the bottom help text.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n # Show search mode or normal help\n if self.search_mode:\n help_text = f\"/{self.search_query}\"\n if self.search_matches:\n help_text += (\n f\" [{self.search_match_index + 1}/{len(self.search_matches)}]\"\n )\n help_text = help_text.ljust(width - 1)\n else:\n # Show context-sensitive help based on current selection\n item = (\n self.display_items[self.current_row]\n if self.current_row < len(self.display_items)\n else None\n )","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.draw_footer","uri":"program://Fuser/function/tools.env-config.curses_ui.draw_footer#L76-L114","kind":"function","name":"draw_footer","path":"tools/env-config/curses_ui.py","language":"python","start_line":76,"end_line":114,"context_start_line":56,"context_end_line":134,"code":" \"type\": \"option\",\n \"option\": opt,\n }\n )\n\n # Initialize curses\n curses.curs_set(0) # Hide cursor\n curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) # Highlight\n curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) # Header\n curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) # Enabled/Set\n curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK) # Multi tag\n\n def draw_header(self) -> None:\n \"\"\"Draw the top header.\"\"\"\n height, width = self.stdscr.getmaxyx()\n self.stdscr.attron(curses.color_pair(2) | curses.A_BOLD)\n header = \"nvFuser Environment Configuration\"\n self.stdscr.addstr(0, (width - len(header)) // 2, header)\n self.stdscr.attroff(curses.color_pair(2) | curses.A_BOLD)\n\n def draw_footer(self) -> None:\n \"\"\"Draw the bottom help text.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n # Show search mode or normal help\n if self.search_mode:\n help_text = f\"/{self.search_query}\"\n if self.search_matches:\n help_text += (\n f\" [{self.search_match_index + 1}/{len(self.search_matches)}]\"\n )\n help_text = help_text.ljust(width - 1)\n else:\n # Show context-sensitive help based on current selection\n item = (\n self.display_items[self.current_row]\n if self.current_row < len(self.display_items)\n else None\n )\n\n if item and item[\"type\"] == \"option\":\n opt = item[\"option\"]\n match opt.var_type:\n case \"bool\":\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Toggle [r] Reload [a] Apply [g] Gen [q] Quit\"\n case \"multi\":\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Cycle [r] Reload [a] Apply [g] Gen [q] Quit\"\n case _:\n # String/Int - Enter to edit\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Edit [r] Reload [a] Apply [g] Gen [q] Quit\"\n else:\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Toggle [r] Reload [a] Apply [g] Gen [q] Quit\"\n\n if self.modified:\n help_text = \"[MODIFIED] \" + help_text\n\n self.stdscr.attron(curses.color_pair(2))\n self.stdscr.addstr(height - 1, 0, help_text.ljust(width - 1))\n self.stdscr.attroff(curses.color_pair(2))\n\n def draw_option(\n self, y: int, item: dict[str, str | object], is_selected: bool\n ) -> None:\n \"\"\"Draw a single option or header.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n if y < 2 or y >= height - 1:\n return # Skip if outside visible area\n\n if item[\"type\"] == \"header\":\n # Draw category header\n attr = curses.color_pair(2) | curses.A_BOLD\n if is_selected:\n attr |= curses.A_REVERSE\n self.stdscr.attron(attr)\n self.stdscr.addstr(y, 0, (\" \" + item[\"text\"]).ljust(width - 1))\n self.stdscr.attroff(attr)\n\n elif item[\"type\"] == \"option\":","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.draw_option","uri":"program://Fuser/function/tools.env-config.curses_ui.draw_option#L116-L216","kind":"function","name":"draw_option","path":"tools/env-config/curses_ui.py","language":"python","start_line":116,"end_line":216,"context_start_line":96,"context_end_line":236,"code":" if item and item[\"type\"] == \"option\":\n opt = item[\"option\"]\n match opt.var_type:\n case \"bool\":\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Toggle [r] Reload [a] Apply [g] Gen [q] Quit\"\n case \"multi\":\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Cycle [r] Reload [a] Apply [g] Gen [q] Quit\"\n case _:\n # String/Int - Enter to edit\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Edit [r] Reload [a] Apply [g] Gen [q] Quit\"\n else:\n help_text = \"[↑↓/jk] Nav [/] Search [n/N] Next/Prev [{}] Sect [PgUp/PgDn] Top/Bot [Enter] Toggle [r] Reload [a] Apply [g] Gen [q] Quit\"\n\n if self.modified:\n help_text = \"[MODIFIED] \" + help_text\n\n self.stdscr.attron(curses.color_pair(2))\n self.stdscr.addstr(height - 1, 0, help_text.ljust(width - 1))\n self.stdscr.attroff(curses.color_pair(2))\n\n def draw_option(\n self, y: int, item: dict[str, str | object], is_selected: bool\n ) -> None:\n \"\"\"Draw a single option or header.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n if y < 2 or y >= height - 1:\n return # Skip if outside visible area\n\n if item[\"type\"] == \"header\":\n # Draw category header\n attr = curses.color_pair(2) | curses.A_BOLD\n if is_selected:\n attr |= curses.A_REVERSE\n self.stdscr.attron(attr)\n self.stdscr.addstr(y, 0, (\" \" + item[\"text\"]).ljust(width - 1))\n self.stdscr.attroff(attr)\n\n elif item[\"type\"] == \"option\":\n opt = item[\"option\"]\n base_attr = 0\n\n if is_selected:\n base_attr |= curses.A_REVERSE\n\n # Format the option display\n # All options get a checkbox at the beginning showing if they're set\n prefix = \" \" # 3 spaces for better visual separation\n\n if opt.var_type == \"bool\":\n # Boolean option - checkbox shows enabled/disabled status\n name_part = opt.get_display_name()\n\n if opt.current_value == \"1\":\n checkbox = \"[X] \"\n attr = base_attr | curses.color_pair(3) # Green for enabled\n else:\n checkbox = \"[ ] \"\n attr = base_attr\n\n line = f\"{prefix}{checkbox}{name_part}\"\n max_len = width - 1\n if len(line) > max_len:\n line = line[: max_len - 3] + \"...\"\n\n self.stdscr.attron(attr)\n self.stdscr.addstr(y, 0, line.ljust(width - 1))\n self.stdscr.attroff(attr)\n\n else:\n # String/int/multi option with value display and checkbox\n display_name = opt.get_display_name()\n\n # Determine if this option has a value (affects checkbox and color)\n has_value = opt.current_value is not None\n line_attr = base_attr | curses.color_pair(3) if has_value else base_attr\n\n # Add checkbox at the beginning - checked if value is set\n if has_value:\n checkbox = \"[X] \"\n else:\n checkbox = \"[ ] \"\n\n name_part = f\"{prefix}{checkbox}{display_name}\"\n\n # Draw name part with checkbox (green if value is set)\n self.stdscr.attron(line_attr)\n self.stdscr.addstr(y, 0, name_part)\n self.stdscr.attroff(line_attr)\n\n # Add [multi] tag in yellow for multi-choice options\n multi_tag_len = 0\n if opt.var_type == \"multi\":\n multi_tag = \" [multi]\"\n multi_tag_len = len(multi_tag)\n multi_attr = base_attr | curses.color_pair(4) # Yellow\n self.stdscr.attron(multi_attr)\n self.stdscr.addstr(y, len(name_part), multi_tag)\n self.stdscr.attroff(multi_attr)\n\n # Draw value part (green if set)\n if opt.current_value:\n value_part = f\" = {opt.current_value}\"\n else:\n # Show = \"\" for empty string/int/multi to indicate they expect values\n value_part = ' = \"\"'\n\n # Calculate remaining space\n total_prefix = len(name_part) + multi_tag_len\n remaining_space = width - 1 - total_prefix\n if len(value_part) > remaining_space:\n value_part = value_part[: remaining_space - 3] + \"...\"\n\n self.stdscr.attron(line_attr)\n self.stdscr.addstr(y, total_prefix, value_part)\n\n # Pad the rest of the line\n total_len = total_prefix + len(value_part)\n if total_len < width - 1:\n self.stdscr.addstr(y, total_len, \" \" * (width - 1 - total_len))\n self.stdscr.attroff(line_attr)\n\n def draw_description(self) -> None:\n \"\"\"Draw description of currently selected item.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n # Draw description area separator\n desc_start = height - 5\n self.stdscr.hline(desc_start, 0, curses.ACS_HLINE, width)\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n desc_y = desc_start + 1\n\n # Wrap description text\n desc_text = f\"Description: {opt.description}\"","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.draw_description","uri":"program://Fuser/function/tools.env-config.curses_ui.draw_description#L218-L258","kind":"function","name":"draw_description","path":"tools/env-config/curses_ui.py","language":"python","start_line":218,"end_line":258,"context_start_line":198,"context_end_line":278,"code":" value_part = f\" = {opt.current_value}\"\n else:\n # Show = \"\" for empty string/int/multi to indicate they expect values\n value_part = ' = \"\"'\n\n # Calculate remaining space\n total_prefix = len(name_part) + multi_tag_len\n remaining_space = width - 1 - total_prefix\n if len(value_part) > remaining_space:\n value_part = value_part[: remaining_space - 3] + \"...\"\n\n self.stdscr.attron(line_attr)\n self.stdscr.addstr(y, total_prefix, value_part)\n\n # Pad the rest of the line\n total_len = total_prefix + len(value_part)\n if total_len < width - 1:\n self.stdscr.addstr(y, total_len, \" \" * (width - 1 - total_len))\n self.stdscr.attroff(line_attr)\n\n def draw_description(self) -> None:\n \"\"\"Draw description of currently selected item.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n # Draw description area separator\n desc_start = height - 5\n self.stdscr.hline(desc_start, 0, curses.ACS_HLINE, width)\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n desc_y = desc_start + 1\n\n # Wrap description text\n desc_text = f\"Description: {opt.description}\"\n\n # Add choices for multi options\n if opt.var_type == \"multi\" and opt.choices:\n desc_text += f\" | Choices: {', '.join(repr(c) for c in opt.choices)}\"\n\n words = desc_text.split()\n lines = []\n current_line = \"\"\n\n for word in words:\n if len(current_line) + len(word) + 1 <= width - 2:\n current_line += word + \" \"\n else:\n lines.append(current_line.strip())\n current_line = word + \" \"\n if current_line:\n lines.append(current_line.strip())\n\n # Draw description lines\n for i, line in enumerate(lines[:3]): # Max 3 lines\n if desc_y + i < height - 1:\n self.stdscr.addstr(desc_y + i, 1, line)\n\n def draw(self) -> None:\n \"\"\"Draw the entire UI.\"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n self.draw_header()\n\n # Draw options list\n visible_rows = height - 7 # Leave space for header, description, footer\n for i, item in enumerate(\n self.display_items[self.top_row : self.top_row + visible_rows]\n ):\n self.draw_option(i + 2, item, i + self.top_row == self.current_row)\n\n self.draw_description()\n self.draw_footer()\n\n self.stdscr.refresh()\n","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.draw","uri":"program://Fuser/function/tools.env-config.curses_ui.draw#L260-L277","kind":"function","name":"draw","path":"tools/env-config/curses_ui.py","language":"python","start_line":260,"end_line":277,"context_start_line":240,"context_end_line":297,"code":" desc_text += f\" | Choices: {', '.join(repr(c) for c in opt.choices)}\"\n\n words = desc_text.split()\n lines = []\n current_line = \"\"\n\n for word in words:\n if len(current_line) + len(word) + 1 <= width - 2:\n current_line += word + \" \"\n else:\n lines.append(current_line.strip())\n current_line = word + \" \"\n if current_line:\n lines.append(current_line.strip())\n\n # Draw description lines\n for i, line in enumerate(lines[:3]): # Max 3 lines\n if desc_y + i < height - 1:\n self.stdscr.addstr(desc_y + i, 1, line)\n\n def draw(self) -> None:\n \"\"\"Draw the entire UI.\"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n self.draw_header()\n\n # Draw options list\n visible_rows = height - 7 # Leave space for header, description, footer\n for i, item in enumerate(\n self.display_items[self.top_row : self.top_row + visible_rows]\n ):\n self.draw_option(i + 2, item, i + self.top_row == self.current_row)\n\n self.draw_description()\n self.draw_footer()\n\n self.stdscr.refresh()\n\n def handle_toggle(self) -> None:\n \"\"\"Handle toggling/editing current item.\"\"\"\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n\n match opt.var_type:\n case \"bool\":\n # Toggle boolean\n opt.current_value = \"1\" if opt.current_value != \"1\" else None\n self.modified = True\n\n case \"multi\":\n # Cycle through choices, including unset at the end\n # Note: Some choices may include \"\" (empty string) as a valid choice","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.handle_toggle","uri":"program://Fuser/function/tools.env-config.curses_ui.handle_toggle#L279-L317","kind":"function","name":"handle_toggle","path":"tools/env-config/curses_ui.py","language":"python","start_line":279,"end_line":317,"context_start_line":259,"context_end_line":337,"code":"\n def draw(self) -> None:\n \"\"\"Draw the entire UI.\"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n self.draw_header()\n\n # Draw options list\n visible_rows = height - 7 # Leave space for header, description, footer\n for i, item in enumerate(\n self.display_items[self.top_row : self.top_row + visible_rows]\n ):\n self.draw_option(i + 2, item, i + self.top_row == self.current_row)\n\n self.draw_description()\n self.draw_footer()\n\n self.stdscr.refresh()\n\n def handle_toggle(self) -> None:\n \"\"\"Handle toggling/editing current item.\"\"\"\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n\n match opt.var_type:\n case \"bool\":\n # Toggle boolean\n opt.current_value = \"1\" if opt.current_value != \"1\" else None\n self.modified = True\n\n case \"multi\":\n # Cycle through choices, including unset at the end\n # Note: Some choices may include \"\" (empty string) as a valid choice\n if opt.current_value is None:\n # Currently unset, go to first choice\n opt.current_value = opt.choices[0] if opt.choices else \"\"\n elif opt.current_value not in opt.choices:\n # Invalid value, go to first choice\n opt.current_value = opt.choices[0] if opt.choices else \"\"\n else:\n # Valid value, cycle to next (or back to None after last)\n idx = opt.choices.index(opt.current_value)\n if idx == len(opt.choices) - 1:\n # Last choice, cycle back to unset (None)\n opt.current_value = None\n else:\n # Go to next choice\n opt.current_value = opt.choices[idx + 1]\n self.modified = True\n\n case \"int\" | \"string\":\n # For string/int, Enter opens the editor\n self.handle_edit()\n\n def handle_edit(self) -> None:\n \"\"\"Handle editing current item value.\"\"\"\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n\n if opt.var_type in [\"int\", \"string\", \"multi\"]:\n height, width = self.stdscr.getmaxyx()\n\n # Calculate the Y position of the current row on screen\n # Rows start at y=2 (after header), and we need to account for scroll\n screen_y = 2 + (self.current_row - self.top_row)\n\n # Make sure we're within visible area\n if screen_y < 2 or screen_y >= height - 5:","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.handle_edit","uri":"program://Fuser/function/tools.env-config.curses_ui.handle_edit#L319-L439","kind":"function","name":"handle_edit","path":"tools/env-config/curses_ui.py","language":"python","start_line":319,"end_line":439,"context_start_line":299,"context_end_line":459,"code":" # Currently unset, go to first choice\n opt.current_value = opt.choices[0] if opt.choices else \"\"\n elif opt.current_value not in opt.choices:\n # Invalid value, go to first choice\n opt.current_value = opt.choices[0] if opt.choices else \"\"\n else:\n # Valid value, cycle to next (or back to None after last)\n idx = opt.choices.index(opt.current_value)\n if idx == len(opt.choices) - 1:\n # Last choice, cycle back to unset (None)\n opt.current_value = None\n else:\n # Go to next choice\n opt.current_value = opt.choices[idx + 1]\n self.modified = True\n\n case \"int\" | \"string\":\n # For string/int, Enter opens the editor\n self.handle_edit()\n\n def handle_edit(self) -> None:\n \"\"\"Handle editing current item value.\"\"\"\n if self.current_row >= len(self.display_items):\n return\n\n item = self.display_items[self.current_row]\n\n if item[\"type\"] == \"option\":\n opt = item[\"option\"]\n\n if opt.var_type in [\"int\", \"string\", \"multi\"]:\n height, width = self.stdscr.getmaxyx()\n\n # Calculate the Y position of the current row on screen\n # Rows start at y=2 (after header), and we need to account for scroll\n screen_y = 2 + (self.current_row - self.top_row)\n\n # Make sure we're within visible area\n if screen_y < 2 or screen_y >= height - 5:\n # Fall back to center if somehow out of range\n screen_y = height // 2\n\n # Build the display name with [multi] tag if applicable\n display_name = opt.get_display_name()\n if opt.var_type == \"multi\":\n display_name += \" [multi]\"\n\n # Get current value to pre-fill\n current_val = opt.current_value if opt.current_value else \"\"\n\n # Create prompt: \"name = |cursor here|\"\n prefix = \" \"\n prompt_text = f\"{prefix}{display_name} = \"\n\n # Clear the line and show the prompt\n self.stdscr.move(screen_y, 0)\n self.stdscr.clrtoeol()\n self.stdscr.addstr(screen_y, 0, prompt_text, curses.A_BOLD)\n\n # Pre-fill with current value\n if current_val:\n self.stdscr.addstr(screen_y, len(prompt_text), current_val)\n\n self.stdscr.refresh()\n\n # Position cursor at the end of the current value\n cursor_pos = len(prompt_text) + len(current_val)\n self.stdscr.move(screen_y, cursor_pos)\n\n # Enable cursor and echo\n curses.curs_set(1)\n curses.echo()\n\n try:\n # Manual text editing with basic line editing support\n buffer = list(current_val) # Start with current value\n cursor_offset = len(buffer) # Cursor at end\n max_len = width - len(prompt_text) - 2\n\n while True:\n # Display current buffer\n self.stdscr.move(screen_y, len(prompt_text))\n self.stdscr.clrtoeol()\n display_text = \"\".join(buffer)\n if len(display_text) > max_len:\n display_text = display_text[:max_len]\n self.stdscr.addstr(screen_y, len(prompt_text), display_text)\n self.stdscr.move(screen_y, len(prompt_text) + cursor_offset)\n self.stdscr.refresh()\n\n # Get key\n key = self.stdscr.getch()\n\n if key == ord(\"\\n\") or key == curses.KEY_ENTER:\n # Accept input\n value = \"\".join(buffer).strip()\n if value or opt.current_value: # Allow clearing\n opt.current_value = value if value else None\n self.modified = True\n break\n elif key == 27: # Escape\n # Cancel editing\n break\n elif key == curses.KEY_BACKSPACE or key == 127 or key == 8:\n # Backspace\n if cursor_offset > 0:\n buffer.pop(cursor_offset - 1)\n cursor_offset -= 1\n elif key == curses.KEY_DC:\n # Delete key\n if cursor_offset < len(buffer):\n buffer.pop(cursor_offset)\n elif key == curses.KEY_LEFT:\n # Move cursor left\n if cursor_offset > 0:\n cursor_offset -= 1\n elif key == curses.KEY_RIGHT:\n # Move cursor right\n if cursor_offset < len(buffer):\n cursor_offset += 1\n elif key == curses.KEY_HOME or key == 1: # Ctrl-A\n # Move to start\n cursor_offset = 0\n elif key == curses.KEY_END or key == 5: # Ctrl-E\n # Move to end\n cursor_offset = len(buffer)\n elif key == 21: # Ctrl-U\n # Clear line\n buffer = []\n cursor_offset = 0\n elif 32 <= key <= 126:\n # Printable character\n if len(buffer) < max_len:\n buffer.insert(cursor_offset, chr(key))\n cursor_offset += 1\n\n except Exception:\n pass\n finally:\n curses.noecho()\n curses.curs_set(0)\n\n def show_confirmation(self, message: str, prompt: str) -> str:\n \"\"\"Show a simple y/n confirmation dialog.\n\n Returns the character pressed by the user (y/n/etc).\n \"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Center the message\n y = height // 2\n x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show prompt below\n y += 2\n x = max(0, (width - len(prompt)) // 2)\n self.stdscr.addstr(y, x, prompt)\n\n self.stdscr.refresh()","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.show_confirmation","uri":"program://Fuser/function/tools.env-config.curses_ui.show_confirmation#L441-L465","kind":"function","name":"show_confirmation","path":"tools/env-config/curses_ui.py","language":"python","start_line":441,"end_line":465,"context_start_line":421,"context_end_line":485,"code":" cursor_offset = 0\n elif key == curses.KEY_END or key == 5: # Ctrl-E\n # Move to end\n cursor_offset = len(buffer)\n elif key == 21: # Ctrl-U\n # Clear line\n buffer = []\n cursor_offset = 0\n elif 32 <= key <= 126:\n # Printable character\n if len(buffer) < max_len:\n buffer.insert(cursor_offset, chr(key))\n cursor_offset += 1\n\n except Exception:\n pass\n finally:\n curses.noecho()\n curses.curs_set(0)\n\n def show_confirmation(self, message: str, prompt: str) -> str:\n \"\"\"Show a simple y/n confirmation dialog.\n\n Returns the character pressed by the user (y/n/etc).\n \"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Center the message\n y = height // 2\n x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show prompt below\n y += 2\n x = max(0, (width - len(prompt)) // 2)\n self.stdscr.addstr(y, x, prompt)\n\n self.stdscr.refresh()\n\n # Get single character response\n response = self.stdscr.getch()\n if response == 27: # Escape\n return \"n\"\n return chr(response) if response < 256 else \"n\"\n\n def show_message(\n self, message: str, submessage: str = \"\", wait_for_key: bool = True\n ) -> None:\n \"\"\"Show a simple message dialog\"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Center the message\n y = height // 2\n x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show submessage below\n if submessage:\n y += 2\n x = max(0, (width - len(submessage)) // 2)\n self.stdscr.addstr(y, x, submessage)\n\n if wait_for_key:","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.show_message","uri":"program://Fuser/function/tools.env-config.curses_ui.show_message#L467-L494","kind":"function","name":"show_message","path":"tools/env-config/curses_ui.py","language":"python","start_line":467,"end_line":494,"context_start_line":447,"context_end_line":514,"code":" height, width = self.stdscr.getmaxyx()\n\n # Center the message\n y = height // 2\n x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show prompt below\n y += 2\n x = max(0, (width - len(prompt)) // 2)\n self.stdscr.addstr(y, x, prompt)\n\n self.stdscr.refresh()\n\n # Get single character response\n response = self.stdscr.getch()\n if response == 27: # Escape\n return \"n\"\n return chr(response) if response < 256 else \"n\"\n\n def show_message(\n self, message: str, submessage: str = \"\", wait_for_key: bool = True\n ) -> None:\n \"\"\"Show a simple message dialog\"\"\"\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Center the message\n y = height // 2\n x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show submessage below\n if submessage:\n y += 2\n x = max(0, (width - len(submessage)) // 2)\n self.stdscr.addstr(y, x, submessage)\n\n if wait_for_key:\n y += 2\n prompt = \"Press any key to continue...\"\n x = max(0, (width - len(prompt)) // 2)\n self.stdscr.addstr(y, x, prompt)\n\n self.stdscr.refresh()\n\n if wait_for_key:\n self.stdscr.getch()\n\n def handle_apply_now(self) -> None:\n \"\"\"Show confirmation, generate apply script, and signal to exit\"\"\"\n # Import save_config here to avoid circular import\n from configure_env import save_config\n import os\n import sys\n import tempfile\n\n # Show confirmation dialog\n response = self.show_confirmation(\"Apply configuration and exit?\", \"[y/N]\")\n\n if response not in [\"y\", \"Y\"]:\n return # User cancelled\n\n # Get exports and unsets\n exports = self.config.get_env_exports()\n unsets = self.config.get_unset_vars()\n\n # Generate apply script with unpredictable name in current directory","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.handle_apply_now","uri":"program://Fuser/function/tools.env-config.curses_ui.handle_apply_now#L496-L537","kind":"function","name":"handle_apply_now","path":"tools/env-config/curses_ui.py","language":"python","start_line":496,"end_line":537,"context_start_line":476,"context_end_line":557,"code":" x = max(0, (width - len(message)) // 2)\n self.stdscr.addstr(y, x, message, curses.A_BOLD)\n\n # Show submessage below\n if submessage:\n y += 2\n x = max(0, (width - len(submessage)) // 2)\n self.stdscr.addstr(y, x, submessage)\n\n if wait_for_key:\n y += 2\n prompt = \"Press any key to continue...\"\n x = max(0, (width - len(prompt)) // 2)\n self.stdscr.addstr(y, x, prompt)\n\n self.stdscr.refresh()\n\n if wait_for_key:\n self.stdscr.getch()\n\n def handle_apply_now(self) -> None:\n \"\"\"Show confirmation, generate apply script, and signal to exit\"\"\"\n # Import save_config here to avoid circular import\n from configure_env import save_config\n import os\n import sys\n import tempfile\n\n # Show confirmation dialog\n response = self.show_confirmation(\"Apply configuration and exit?\", \"[y/N]\")\n\n if response not in [\"y\", \"Y\"]:\n return # User cancelled\n\n # Get exports and unsets\n exports = self.config.get_env_exports()\n unsets = self.config.get_unset_vars()\n\n # Generate apply script with unpredictable name in current directory\n # Using mktemp pattern for security (prevents race conditions)\n fd, apply_script = tempfile.mkstemp(\n suffix=\".sh\", prefix=\".nvfuser-apply.\", dir=os.getcwd(), text=True\n )\n os.close(fd) # Close the file descriptor, we'll write via save_config\n\n # Debug output\n if os.environ.get(\"NVFUSER_CONFIG_DEBUG\") == \"1\":\n sys.stderr.write(f\"[DEBUG] Creating apply script at: {apply_script}\\n\")\n sys.stderr.write(f\"[DEBUG] Exports: {len(exports)} variables\\n\")\n sys.stderr.write(f\"[DEBUG] Unsets: {len(unsets)} variables\\n\")\n\n save_config(exports, unsets, apply_script)\n\n if os.environ.get(\"NVFUSER_CONFIG_DEBUG\") == \"1\":\n if os.path.exists(apply_script):\n sys.stderr.write(\"[DEBUG] Apply script created successfully\\n\")\n else:\n sys.stderr.write(\"[DEBUG] ERROR: Apply script was NOT created!\\n\")\n\n # Set flag to exit\n self.should_exit = True\n self.modified = False # Prevent quit prompt\n\n def handle_generate(self) -> None:\n \"\"\"Prompt for filename and generate script\"\"\"\n # Import save_config here to avoid circular import\n from configure_env import save_config\n\n # Simple text input prompt\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Show prompt\n prompt = \"Enter filename [nvfuser_env.sh]: \"\n self.stdscr.addstr(height // 2, 2, prompt, curses.A_BOLD)\n self.stdscr.refresh()\n\n # Enable echo for input\n curses.echo()\n curses.curs_set(1)\n\n # Get input (basic - no arrow key editing, but backspace works naturally)","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.handle_generate","uri":"program://Fuser/function/tools.env-config.curses_ui.handle_generate#L539-L590","kind":"function","name":"handle_generate","path":"tools/env-config/curses_ui.py","language":"python","start_line":539,"end_line":590,"context_start_line":519,"context_end_line":610,"code":" os.close(fd) # Close the file descriptor, we'll write via save_config\n\n # Debug output\n if os.environ.get(\"NVFUSER_CONFIG_DEBUG\") == \"1\":\n sys.stderr.write(f\"[DEBUG] Creating apply script at: {apply_script}\\n\")\n sys.stderr.write(f\"[DEBUG] Exports: {len(exports)} variables\\n\")\n sys.stderr.write(f\"[DEBUG] Unsets: {len(unsets)} variables\\n\")\n\n save_config(exports, unsets, apply_script)\n\n if os.environ.get(\"NVFUSER_CONFIG_DEBUG\") == \"1\":\n if os.path.exists(apply_script):\n sys.stderr.write(\"[DEBUG] Apply script created successfully\\n\")\n else:\n sys.stderr.write(\"[DEBUG] ERROR: Apply script was NOT created!\\n\")\n\n # Set flag to exit\n self.should_exit = True\n self.modified = False # Prevent quit prompt\n\n def handle_generate(self) -> None:\n \"\"\"Prompt for filename and generate script\"\"\"\n # Import save_config here to avoid circular import\n from configure_env import save_config\n\n # Simple text input prompt\n self.stdscr.clear()\n height, width = self.stdscr.getmaxyx()\n\n # Show prompt\n prompt = \"Enter filename [nvfuser_env.sh]: \"\n self.stdscr.addstr(height // 2, 2, prompt, curses.A_BOLD)\n self.stdscr.refresh()\n\n # Enable echo for input\n curses.echo()\n curses.curs_set(1)\n\n # Get input (basic - no arrow key editing, but backspace works naturally)\n try:\n filename_input = (\n self.stdscr.getstr(height // 2, 2 + len(prompt), 50)\n .decode(\"utf-8\")\n .strip()\n )\n finally:\n curses.noecho()\n curses.curs_set(0)\n\n # Use default if empty\n if not filename_input:\n filename = \"nvfuser_env.sh\"\n else:\n filename = filename_input\n\n # Get exports and unsets\n exports = self.config.get_env_exports()\n unsets = self.config.get_unset_vars()\n\n # Generate script\n save_config(exports, unsets, filename)\n\n # Show confirmation dialog\n self.show_message(\n f\"Configuration saved to {filename}\",\n f\"To apply: source {filename}\",\n wait_for_key=True,\n )\n\n # Exit\n self.should_exit = True\n self.modified = False\n\n def reload_from_environment(self) -> None:\n \"\"\"Reload configuration values from current environment.\"\"\"\n self.config._load_current_values()\n self.modified = False\n\n def jump_to_next_section(self) -> None:\n \"\"\"Jump to the next section header.\"\"\"\n for i in range(self.current_row + 1, len(self.display_items)):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n if self.current_row >= self.top_row + visible_rows:\n self.top_row = self.current_row - visible_rows + 1\n break\n\n def jump_to_prev_section(self) -> None:\n \"\"\"Jump to the previous section header.\"\"\"","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.reload_from_environment","uri":"program://Fuser/function/tools.env-config.curses_ui.reload_from_environment#L592-L595","kind":"function","name":"reload_from_environment","path":"tools/env-config/curses_ui.py","language":"python","start_line":592,"end_line":595,"context_start_line":572,"context_end_line":615,"code":" filename = filename_input\n\n # Get exports and unsets\n exports = self.config.get_env_exports()\n unsets = self.config.get_unset_vars()\n\n # Generate script\n save_config(exports, unsets, filename)\n\n # Show confirmation dialog\n self.show_message(\n f\"Configuration saved to {filename}\",\n f\"To apply: source {filename}\",\n wait_for_key=True,\n )\n\n # Exit\n self.should_exit = True\n self.modified = False\n\n def reload_from_environment(self) -> None:\n \"\"\"Reload configuration values from current environment.\"\"\"\n self.config._load_current_values()\n self.modified = False\n\n def jump_to_next_section(self) -> None:\n \"\"\"Jump to the next section header.\"\"\"\n for i in range(self.current_row + 1, len(self.display_items)):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n if self.current_row >= self.top_row + visible_rows:\n self.top_row = self.current_row - visible_rows + 1\n break\n\n def jump_to_prev_section(self) -> None:\n \"\"\"Jump to the previous section header.\"\"\"\n for i in range(self.current_row - 1, -1, -1):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n if self.current_row < self.top_row:","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.jump_to_next_section","uri":"program://Fuser/function/tools.env-config.curses_ui.jump_to_next_section#L597-L607","kind":"function","name":"jump_to_next_section","path":"tools/env-config/curses_ui.py","language":"python","start_line":597,"end_line":607,"context_start_line":577,"context_end_line":627,"code":"\n # Generate script\n save_config(exports, unsets, filename)\n\n # Show confirmation dialog\n self.show_message(\n f\"Configuration saved to {filename}\",\n f\"To apply: source {filename}\",\n wait_for_key=True,\n )\n\n # Exit\n self.should_exit = True\n self.modified = False\n\n def reload_from_environment(self) -> None:\n \"\"\"Reload configuration values from current environment.\"\"\"\n self.config._load_current_values()\n self.modified = False\n\n def jump_to_next_section(self) -> None:\n \"\"\"Jump to the next section header.\"\"\"\n for i in range(self.current_row + 1, len(self.display_items)):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n if self.current_row >= self.top_row + visible_rows:\n self.top_row = self.current_row - visible_rows + 1\n break\n\n def jump_to_prev_section(self) -> None:\n \"\"\"Jump to the previous section header.\"\"\"\n for i in range(self.current_row - 1, -1, -1):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n if self.current_row < self.top_row:\n self.top_row = self.current_row\n break\n\n def jump_to_top(self) -> None:\n \"\"\"Jump to the first item.\"\"\"\n self.current_row = 0\n self.top_row = 0\n\n def jump_to_bottom(self) -> None:\n \"\"\"Jump to the last item.\"\"\"\n self.current_row = len(self.display_items) - 1\n # Adjust scroll to show bottom","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.jump_to_prev_section","uri":"program://Fuser/function/tools.env-config.curses_ui.jump_to_prev_section#L609-L617","kind":"function","name":"jump_to_prev_section","path":"tools/env-config/curses_ui.py","language":"python","start_line":609,"end_line":617,"context_start_line":589,"context_end_line":637,"code":" self.should_exit = True\n self.modified = False\n\n def reload_from_environment(self) -> None:\n \"\"\"Reload configuration values from current environment.\"\"\"\n self.config._load_current_values()\n self.modified = False\n\n def jump_to_next_section(self) -> None:\n \"\"\"Jump to the next section header.\"\"\"\n for i in range(self.current_row + 1, len(self.display_items)):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n if self.current_row >= self.top_row + visible_rows:\n self.top_row = self.current_row - visible_rows + 1\n break\n\n def jump_to_prev_section(self) -> None:\n \"\"\"Jump to the previous section header.\"\"\"\n for i in range(self.current_row - 1, -1, -1):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n if self.current_row < self.top_row:\n self.top_row = self.current_row\n break\n\n def jump_to_top(self) -> None:\n \"\"\"Jump to the first item.\"\"\"\n self.current_row = 0\n self.top_row = 0\n\n def jump_to_bottom(self) -> None:\n \"\"\"Jump to the last item.\"\"\"\n self.current_row = len(self.display_items) - 1\n # Adjust scroll to show bottom\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n self.top_row = max(0, self.current_row - visible_rows + 1)\n\n def search_items(self, query: str) -> list[int]:\n \"\"\"Search for items matching the query.\n\n Returns list of indices of matching items (both headers and options).\n Searches in option names and category headers only.\n Case-insensitive search.","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.jump_to_top","uri":"program://Fuser/function/tools.env-config.curses_ui.jump_to_top#L619-L622","kind":"function","name":"jump_to_top","path":"tools/env-config/curses_ui.py","language":"python","start_line":619,"end_line":622,"context_start_line":599,"context_end_line":642,"code":" for i in range(self.current_row + 1, len(self.display_items)):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n if self.current_row >= self.top_row + visible_rows:\n self.top_row = self.current_row - visible_rows + 1\n break\n\n def jump_to_prev_section(self) -> None:\n \"\"\"Jump to the previous section header.\"\"\"\n for i in range(self.current_row - 1, -1, -1):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n if self.current_row < self.top_row:\n self.top_row = self.current_row\n break\n\n def jump_to_top(self) -> None:\n \"\"\"Jump to the first item.\"\"\"\n self.current_row = 0\n self.top_row = 0\n\n def jump_to_bottom(self) -> None:\n \"\"\"Jump to the last item.\"\"\"\n self.current_row = len(self.display_items) - 1\n # Adjust scroll to show bottom\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n self.top_row = max(0, self.current_row - visible_rows + 1)\n\n def search_items(self, query: str) -> list[int]:\n \"\"\"Search for items matching the query.\n\n Returns list of indices of matching items (both headers and options).\n Searches in option names and category headers only.\n Case-insensitive search.\n \"\"\"\n if not query:\n return []\n\n matches = []","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.jump_to_bottom","uri":"program://Fuser/function/tools.env-config.curses_ui.jump_to_bottom#L624-L630","kind":"function","name":"jump_to_bottom","path":"tools/env-config/curses_ui.py","language":"python","start_line":624,"end_line":630,"context_start_line":604,"context_end_line":650,"code":" visible_rows = height - 7\n if self.current_row >= self.top_row + visible_rows:\n self.top_row = self.current_row - visible_rows + 1\n break\n\n def jump_to_prev_section(self) -> None:\n \"\"\"Jump to the previous section header.\"\"\"\n for i in range(self.current_row - 1, -1, -1):\n if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n if self.current_row < self.top_row:\n self.top_row = self.current_row\n break\n\n def jump_to_top(self) -> None:\n \"\"\"Jump to the first item.\"\"\"\n self.current_row = 0\n self.top_row = 0\n\n def jump_to_bottom(self) -> None:\n \"\"\"Jump to the last item.\"\"\"\n self.current_row = len(self.display_items) - 1\n # Adjust scroll to show bottom\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n self.top_row = max(0, self.current_row - visible_rows + 1)\n\n def search_items(self, query: str) -> list[int]:\n \"\"\"Search for items matching the query.\n\n Returns list of indices of matching items (both headers and options).\n Searches in option names and category headers only.\n Case-insensitive search.\n \"\"\"\n if not query:\n return []\n\n matches = []\n query_lower = query.lower()\n\n for i, item in enumerate(self.display_items):\n if item[\"type\"] == \"header\":\n # Search in category header text\n if query_lower in item[\"text\"].lower():\n matches.append(i)\n elif item[\"type\"] == \"option\":","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.search_items","uri":"program://Fuser/function/tools.env-config.curses_ui.search_items#L632-L656","kind":"function","name":"search_items","path":"tools/env-config/curses_ui.py","language":"python","start_line":632,"end_line":656,"context_start_line":612,"context_end_line":676,"code":" if self.display_items[i][\"type\"] == \"header\":\n self.current_row = i\n # Adjust scroll if needed\n if self.current_row < self.top_row:\n self.top_row = self.current_row\n break\n\n def jump_to_top(self) -> None:\n \"\"\"Jump to the first item.\"\"\"\n self.current_row = 0\n self.top_row = 0\n\n def jump_to_bottom(self) -> None:\n \"\"\"Jump to the last item.\"\"\"\n self.current_row = len(self.display_items) - 1\n # Adjust scroll to show bottom\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n self.top_row = max(0, self.current_row - visible_rows + 1)\n\n def search_items(self, query: str) -> list[int]:\n \"\"\"Search for items matching the query.\n\n Returns list of indices of matching items (both headers and options).\n Searches in option names and category headers only.\n Case-insensitive search.\n \"\"\"\n if not query:\n return []\n\n matches = []\n query_lower = query.lower()\n\n for i, item in enumerate(self.display_items):\n if item[\"type\"] == \"header\":\n # Search in category header text\n if query_lower in item[\"text\"].lower():\n matches.append(i)\n elif item[\"type\"] == \"option\":\n opt = item[\"option\"]\n # Search in option name only\n if query_lower in opt.name.lower():\n matches.append(i)\n\n return matches\n\n def handle_search(self) -> None:\n \"\"\"Enter search mode and handle search input.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n # Enable cursor for search input\n curses.curs_set(1)\n curses.echo()\n\n search_query = \"\"\n\n try:\n while True:\n # Draw the search prompt\n self.stdscr.move(height - 1, 0)\n self.stdscr.clrtoeol()\n self.stdscr.attron(curses.color_pair(2))\n prompt = f\"/{search_query}\"\n self.stdscr.addstr(height - 1, 0, prompt.ljust(width - 1))\n self.stdscr.attroff(curses.color_pair(2))","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.handle_search","uri":"program://Fuser/function/tools.env-config.curses_ui.handle_search#L658-L704","kind":"function","name":"handle_search","path":"tools/env-config/curses_ui.py","language":"python","start_line":658,"end_line":704,"context_start_line":638,"context_end_line":724,"code":" \"\"\"\n if not query:\n return []\n\n matches = []\n query_lower = query.lower()\n\n for i, item in enumerate(self.display_items):\n if item[\"type\"] == \"header\":\n # Search in category header text\n if query_lower in item[\"text\"].lower():\n matches.append(i)\n elif item[\"type\"] == \"option\":\n opt = item[\"option\"]\n # Search in option name only\n if query_lower in opt.name.lower():\n matches.append(i)\n\n return matches\n\n def handle_search(self) -> None:\n \"\"\"Enter search mode and handle search input.\"\"\"\n height, width = self.stdscr.getmaxyx()\n\n # Enable cursor for search input\n curses.curs_set(1)\n curses.echo()\n\n search_query = \"\"\n\n try:\n while True:\n # Draw the search prompt\n self.stdscr.move(height - 1, 0)\n self.stdscr.clrtoeol()\n self.stdscr.attron(curses.color_pair(2))\n prompt = f\"/{search_query}\"\n self.stdscr.addstr(height - 1, 0, prompt.ljust(width - 1))\n self.stdscr.attroff(curses.color_pair(2))\n self.stdscr.move(height - 1, len(prompt))\n self.stdscr.refresh()\n\n # Get key\n key = self.stdscr.getch()\n\n if key == ord(\"\\n\") or key == curses.KEY_ENTER:\n # Accept search and jump to first match\n if search_query:\n self.search_query = search_query\n self.search_matches = self.search_items(search_query)\n if self.search_matches:\n self.search_match_index = 0\n self.jump_to_search_match(self.search_matches[0])\n break\n elif key == 27: # Escape\n # Cancel search\n break\n elif key == curses.KEY_BACKSPACE or key == 127 or key == 8:\n # Backspace\n if search_query:\n search_query = search_query[:-1]\n elif 32 <= key <= 126:\n # Printable character\n search_query += chr(key)\n finally:\n curses.noecho()\n curses.curs_set(0)\n\n def jump_to_search_match(self, match_index: int) -> None:\n \"\"\"Jump to a specific item by index.\"\"\"\n if 0 <= match_index < len(self.display_items):\n self.current_row = match_index\n # Adjust scroll to center the match if possible\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n # Try to center the match\n target_top = max(0, self.current_row - visible_rows // 2)\n # But make sure we don't scroll past the end\n max_top = max(0, len(self.display_items) - visible_rows)\n self.top_row = min(target_top, max_top)\n\n def jump_to_next_match(self) -> None:\n \"\"\"Jump to next search match (n in vim).\"\"\"\n if not self.search_matches:\n return\n\n self.search_match_index = (self.search_match_index + 1) % len(","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.jump_to_search_match","uri":"program://Fuser/function/tools.env-config.curses_ui.jump_to_search_match#L706-L717","kind":"function","name":"jump_to_search_match","path":"tools/env-config/curses_ui.py","language":"python","start_line":706,"end_line":717,"context_start_line":686,"context_end_line":737,"code":" self.search_query = search_query\n self.search_matches = self.search_items(search_query)\n if self.search_matches:\n self.search_match_index = 0\n self.jump_to_search_match(self.search_matches[0])\n break\n elif key == 27: # Escape\n # Cancel search\n break\n elif key == curses.KEY_BACKSPACE or key == 127 or key == 8:\n # Backspace\n if search_query:\n search_query = search_query[:-1]\n elif 32 <= key <= 126:\n # Printable character\n search_query += chr(key)\n finally:\n curses.noecho()\n curses.curs_set(0)\n\n def jump_to_search_match(self, match_index: int) -> None:\n \"\"\"Jump to a specific item by index.\"\"\"\n if 0 <= match_index < len(self.display_items):\n self.current_row = match_index\n # Adjust scroll to center the match if possible\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n # Try to center the match\n target_top = max(0, self.current_row - visible_rows // 2)\n # But make sure we don't scroll past the end\n max_top = max(0, len(self.display_items) - visible_rows)\n self.top_row = min(target_top, max_top)\n\n def jump_to_next_match(self) -> None:\n \"\"\"Jump to next search match (n in vim).\"\"\"\n if not self.search_matches:\n return\n\n self.search_match_index = (self.search_match_index + 1) % len(\n self.search_matches\n )\n self.jump_to_search_match(self.search_matches[self.search_match_index])\n\n def jump_to_prev_match(self) -> None:\n \"\"\"Jump to previous search match (N in vim).\"\"\"\n if not self.search_matches:\n return\n\n self.search_match_index = (self.search_match_index - 1) % len(\n self.search_matches\n )\n self.jump_to_search_match(self.search_matches[self.search_match_index])","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.jump_to_next_match","uri":"program://Fuser/function/tools.env-config.curses_ui.jump_to_next_match#L719-L727","kind":"function","name":"jump_to_next_match","path":"tools/env-config/curses_ui.py","language":"python","start_line":719,"end_line":727,"context_start_line":699,"context_end_line":747,"code":" elif 32 <= key <= 126:\n # Printable character\n search_query += chr(key)\n finally:\n curses.noecho()\n curses.curs_set(0)\n\n def jump_to_search_match(self, match_index: int) -> None:\n \"\"\"Jump to a specific item by index.\"\"\"\n if 0 <= match_index < len(self.display_items):\n self.current_row = match_index\n # Adjust scroll to center the match if possible\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n # Try to center the match\n target_top = max(0, self.current_row - visible_rows // 2)\n # But make sure we don't scroll past the end\n max_top = max(0, len(self.display_items) - visible_rows)\n self.top_row = min(target_top, max_top)\n\n def jump_to_next_match(self) -> None:\n \"\"\"Jump to next search match (n in vim).\"\"\"\n if not self.search_matches:\n return\n\n self.search_match_index = (self.search_match_index + 1) % len(\n self.search_matches\n )\n self.jump_to_search_match(self.search_matches[self.search_match_index])\n\n def jump_to_prev_match(self) -> None:\n \"\"\"Jump to previous search match (N in vim).\"\"\"\n if not self.search_matches:\n return\n\n self.search_match_index = (self.search_match_index - 1) % len(\n self.search_matches\n )\n self.jump_to_search_match(self.search_matches[self.search_match_index])\n\n def run(self) -> None:\n \"\"\"Main event loop.\"\"\"\n while True:\n self.draw()\n\n key = self.stdscr.getch()\n\n if key == ord(\"q\") or key == ord(\"Q\"):\n # Quit","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.jump_to_prev_match","uri":"program://Fuser/function/tools.env-config.curses_ui.jump_to_prev_match#L729-L737","kind":"function","name":"jump_to_prev_match","path":"tools/env-config/curses_ui.py","language":"python","start_line":729,"end_line":737,"context_start_line":709,"context_end_line":757,"code":" self.current_row = match_index\n # Adjust scroll to center the match if possible\n height, _ = self.stdscr.getmaxyx()\n visible_rows = height - 7\n # Try to center the match\n target_top = max(0, self.current_row - visible_rows // 2)\n # But make sure we don't scroll past the end\n max_top = max(0, len(self.display_items) - visible_rows)\n self.top_row = min(target_top, max_top)\n\n def jump_to_next_match(self) -> None:\n \"\"\"Jump to next search match (n in vim).\"\"\"\n if not self.search_matches:\n return\n\n self.search_match_index = (self.search_match_index + 1) % len(\n self.search_matches\n )\n self.jump_to_search_match(self.search_matches[self.search_match_index])\n\n def jump_to_prev_match(self) -> None:\n \"\"\"Jump to previous search match (N in vim).\"\"\"\n if not self.search_matches:\n return\n\n self.search_match_index = (self.search_match_index - 1) % len(\n self.search_matches\n )\n self.jump_to_search_match(self.search_matches[self.search_match_index])\n\n def run(self) -> None:\n \"\"\"Main event loop.\"\"\"\n while True:\n self.draw()\n\n key = self.stdscr.getch()\n\n if key == ord(\"q\") or key == ord(\"Q\"):\n # Quit\n if self.modified:\n # Ask what to do with changes\n height, width = self.stdscr.getmaxyx()\n msg_y = height // 2 - 3\n\n self.stdscr.clear()\n self.stdscr.attron(curses.color_pair(1))\n\n title = \"You have unsaved changes!\"\n self.stdscr.addstr(msg_y, (width - len(title)) // 2, title)","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.curses_ui.run","uri":"program://Fuser/function/tools.env-config.curses_ui.run#L739-L888","kind":"function","name":"run","path":"tools/env-config/curses_ui.py","language":"python","start_line":739,"end_line":888,"context_start_line":719,"context_end_line":894,"code":" def jump_to_next_match(self) -> None:\n \"\"\"Jump to next search match (n in vim).\"\"\"\n if not self.search_matches:\n return\n\n self.search_match_index = (self.search_match_index + 1) % len(\n self.search_matches\n )\n self.jump_to_search_match(self.search_matches[self.search_match_index])\n\n def jump_to_prev_match(self) -> None:\n \"\"\"Jump to previous search match (N in vim).\"\"\"\n if not self.search_matches:\n return\n\n self.search_match_index = (self.search_match_index - 1) % len(\n self.search_matches\n )\n self.jump_to_search_match(self.search_matches[self.search_match_index])\n\n def run(self) -> None:\n \"\"\"Main event loop.\"\"\"\n while True:\n self.draw()\n\n key = self.stdscr.getch()\n\n if key == ord(\"q\") or key == ord(\"Q\"):\n # Quit\n if self.modified:\n # Ask what to do with changes\n height, width = self.stdscr.getmaxyx()\n msg_y = height // 2 - 3\n\n self.stdscr.clear()\n self.stdscr.attron(curses.color_pair(1))\n\n title = \"You have unsaved changes!\"\n self.stdscr.addstr(msg_y, (width - len(title)) // 2, title)\n\n self.stdscr.attroff(curses.color_pair(1))\n\n # Show options\n options = [\n \"\",\n \"What would you like to do?\",\n \"\",\n \" [a] Apply Now - Generate .nvfuser_apply.*.sh in current dir\",\n \" (sourced automatically after exit)\",\n \"\",\n \" [g] Generate - Create nvfuser_env.sh\",\n \" (then source it after exit)\",\n \"\",\n \" [q] Quit - Exit without saving\",\n \"\",\n \" [Esc] Cancel - Return to configuration\",\n ]\n\n for i, line in enumerate(options):\n if line.startswith(\" [\"):\n # Highlight the option keys\n self.stdscr.attron(curses.A_BOLD)\n self.stdscr.addstr(\n msg_y + 2 + i, (width - len(line)) // 2, line\n )\n if line.startswith(\" [\"):\n self.stdscr.attroff(curses.A_BOLD)\n\n self.stdscr.refresh()\n\n # Get response\n response = self.stdscr.getch()\n\n if response == ord(\"a\") or response == ord(\"A\"):\n self.handle_apply_now()\n break\n elif response == ord(\"g\") or response == ord(\"G\"):\n self.handle_generate()\n break\n elif response == ord(\"q\") or response == ord(\"Q\"):\n break\n elif response == 27: # Escape\n continue # Return to main loop\n else:\n # Invalid key, show again\n continue\n else:\n # No changes, just quit\n break\n\n elif key == curses.KEY_UP:\n if self.current_row > 0:\n self.current_row -= 1\n # Adjust scroll if needed\n if self.current_row < self.top_row:\n self.top_row = self.current_row\n\n elif key == curses.KEY_DOWN:\n if self.current_row < len(self.display_items) - 1:\n self.current_row += 1\n # Adjust scroll if needed\n height, width = self.stdscr.getmaxyx()\n visible_rows = height - 7\n if self.current_row >= self.top_row + visible_rows:\n self.top_row = self.current_row - visible_rows + 1\n\n # Vim-style navigation\n elif key == ord(\"k\") or key == ord(\"K\"):\n # Up (same as arrow up)\n if self.current_row > 0:\n self.current_row -= 1\n if self.current_row < self.top_row:\n self.top_row = self.current_row\n\n elif key == ord(\"j\") or key == ord(\"J\"):\n # Down (same as arrow down)\n if self.current_row < len(self.display_items) - 1:\n self.current_row += 1\n height, width = self.stdscr.getmaxyx()\n visible_rows = height - 7\n if self.current_row >= self.top_row + visible_rows:\n self.top_row = self.current_row - visible_rows + 1\n\n elif key == ord(\"}\"):\n # Jump to next section\n self.jump_to_next_section()\n\n elif key == ord(\"{\"):\n # Jump to previous section\n self.jump_to_prev_section()\n\n elif key == curses.KEY_PPAGE:\n # Page Up - jump to top\n self.jump_to_top()\n\n elif key == curses.KEY_NPAGE:\n # Page Down - jump to bottom\n self.jump_to_bottom()\n\n elif key == ord(\" \") or key == ord(\"\\n\") or key == curses.KEY_ENTER:\n self.handle_toggle()\n\n elif key == ord(\"e\") or key == ord(\"E\"):\n self.handle_edit()\n\n elif key == ord(\"r\") or key == ord(\"R\"):\n # Reload from environment\n self.reload_from_environment()\n\n elif key == ord(\"a\") or key == ord(\"A\"):\n self.handle_apply_now()\n if self.should_exit:\n break # Exit immediately after apply\n\n elif key == ord(\"g\") or key == ord(\"G\"):\n self.handle_generate()\n if self.should_exit:\n break # Exit immediately after generate\n\n elif key == ord(\"/\"):\n # Enter search mode\n self.handle_search()\n\n elif key == ord(\"n\"):\n # Jump to next search match\n self.jump_to_next_match()\n\n elif key == ord(\"N\"):\n # Jump to previous search match\n self.jump_to_prev_match()\n\n\ndef run_curses_ui(stdscr, config: EnvVarConfig) -> None:\n \"\"\"Entry point for curses UI.\"\"\"\n ui = CursesUI(stdscr, config)\n ui.run()","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env","uri":"program://Fuser/module/tools.env-config.configure_env#L1-L314","kind":"module","name":"tools.env-config.configure_env","path":"tools/env-config/configure_env.py","language":"python","start_line":1,"end_line":314,"context_start_line":1,"context_end_line":314,"code":"#!/usr/bin/env python3\n# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nInteractive nvFuser Environment Configuration Tool\n\nThis tool provides an interactive interface (similar to ccmake) for configuring\nnvFuser environment variables. It helps users set up debug flags, feature toggles,\nand runtime options without needing to remember complex NVFUSER_* variable names.\n\nUsage:\n python tools/configure_env.py # Interactive TUI mode\n python tools/configure_env.py --simple # Simple prompt mode\n python tools/configure_env.py --generate-script # Generate shell script\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport os\nfrom pathlib import Path\n\n# Load environment options from YAML\nfrom options_loader import load_options_from_yaml, EnvVarOption\n\n# Load configuration from YAML file\n_yaml_path = Path(__file__).parent / \"env_options.yaml\"\nCATEGORY_NAMES, ENV_VAR_DEFINITIONS = load_options_from_yaml(_yaml_path)\n\n\nclass EnvVarConfig:\n \"\"\"Manages the current configuration state.\"\"\"\n\n def __init__(self) -> None:\n # Use (name, env_var) tuple as key to handle options with same name\n # but different env vars (e.g., expr_simplify in DUMP vs DISABLE)\n self.options: dict[tuple[str, str | None], EnvVarOption] = {\n (opt.name, opt.env_var): opt for opt in ENV_VAR_DEFINITIONS\n }\n # Also maintain a list of all options for iteration\n self.all_options: list[EnvVarOption] = ENV_VAR_DEFINITIONS.copy()\n self.categories: dict[str, list[EnvVarOption]] = self._organize_by_category()\n self._load_current_values()\n\n def _organize_by_category(self) -> dict[str, list[EnvVarOption]]:\n \"\"\"Organize options by category.\"\"\"\n categories: dict[str, list[EnvVarOption]] = {}\n for opt in self.all_options:\n if opt.category not in categories:\n categories[opt.category] = []\n categories[opt.category].append(opt)\n return categories\n\n def _load_current_values(self) -> None:\n \"\"\"Load current values from environment.\"\"\"\n for opt in self.all_options:\n env_var_name = opt.get_env_var_name()\n\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # These are comma-separated list values\n list_val = os.environ.get(env_var_name, \"\")\n if list_val:\n list_items = [item.strip() for item in list_val.split(\",\")]\n if opt.name in list_items:\n opt.current_value = \"1\"\n else:\n # Regular environment variables\n if env_var_name in os.environ:\n val = os.environ[env_var_name]\n if opt.var_type == \"bool\":\n if val.upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]:\n opt.current_value = \"1\"\n else:\n opt.current_value = val\n\n def get_env_exports(self) -> dict[str, str]:\n \"\"\"Generate environment variable exports based on current configuration.\"\"\"\n exports: dict[str, str] = {}\n\n # Collect values for list-based env vars (DUMP, ENABLE, DISABLE)\n list_vars: dict[str, list[str]] = {} # Maps env_var_name -> list of values\n\n for opt in self.all_options:\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # List items\n if opt.current_value == \"1\":\n env_var = opt.get_env_var_name()\n if env_var not in list_vars:\n list_vars[env_var] = []\n list_vars[env_var].append(opt.name)\n else:\n # Regular env vars\n if opt.current_value is not None:\n env_var = opt.get_env_var_name()\n if opt.var_type == \"bool\":\n if opt.current_value == \"1\":\n exports[env_var] = \"1\"\n else:\n exports[env_var] = opt.current_value\n\n # Add list-based env vars as comma-separated strings\n for env_var, values in list_vars.items():\n exports[env_var] = \",\".join(values)\n\n return exports\n\n def get_unset_vars(self) -> list[str]:\n \"\"\"Get list of ALL variable names that should be unset (empty or unconfigured)\n\n This unsets all known nvFuser variables that aren't configured, ensuring a\n clean slate when the script is sourced.\n \"\"\"\n unset_vars: set[str] = set() # Use set to avoid duplicates\n\n # Track which env vars have values\n env_vars_with_values: set[str] = set()\n\n for opt in self.all_options:\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # List-based vars - only track if any are set\n if opt.current_value == \"1\":\n env_vars_with_values.add(opt.get_env_var_name())\n else:\n # Regular env vars\n env_var = opt.get_env_var_name()\n if opt.current_value:\n env_vars_with_values.add(env_var)\n else:\n unset_vars.add(env_var)\n\n # Unset list vars that have no values set\n for list_var in [\"NVFUSER_DUMP\", \"NVFUSER_ENABLE\", \"NVFUSER_DISABLE\"]:\n if list_var not in env_vars_with_values:\n unset_vars.add(list_var)\n\n return sorted(list(unset_vars))\n\n\ndef simple_prompt_mode(config: EnvVarConfig) -> None:\n \"\"\"Simple prompt-based configuration mode (no curses).\"\"\"\n # ANSI color codes\n GREEN = \"\\033[92m\"\n CYAN = \"\\033[96m\"\n BOLD = \"\\033[1m\"\n RESET = \"\\033[0m\"\n\n print(\"=\" * 70)\n print(\"nvFuser Environment Configuration Tool - Simple Mode\")\n print(\"=\" * 70)\n print()\n\n for category in CATEGORY_NAMES.keys():\n if category not in config.categories:\n continue\n opts = config.categories[category]\n print(f\"\\n{CYAN}{BOLD}{CATEGORY_NAMES[category]}{RESET}\")\n print(\"-\" * 70)\n\n for opt in opts:\n # Show current value in green if set\n if opt.current_value:\n current = f\"{GREEN}{opt.current_value}{RESET}\"\n else:\n current = \"(not set)\"\n\n # Format the option name with type indicator\n opt_name = opt.name\n if opt.var_type == \"multi\":\n opt_name += \" [multi]\"\n\n print(f\"\\n{opt_name}:\")\n print(f\" Description: {opt.description}\")\n print(f\" Current: {current}\")\n\n match opt.var_type:\n case \"bool\":\n response = input(\" Enable? [y/N]: \").strip().lower()\n opt.current_value = \"1\" if response in [\"y\", \"yes\"] else None\n case \"multi\":\n print(f\" Choices: {', '.join(repr(c) for c in opt.choices)}\")\n default = opt.choices[0] if opt.choices else \"\"\n response = input(f\" Select [{default}]: \").strip()\n opt.current_value = response if response else default\n case \"int\" | \"string\":\n response = input(\" Value: \").strip()\n opt.current_value = response if response else None\n\n print(\"\\n\" + \"=\" * 70)\n print(f\"{BOLD}Configuration Summary{RESET}\")\n print(\"=\" * 70)\n\n exports = config.get_env_exports()\n if not exports:\n print(\"No environment variables configured.\")\n else:\n for var, val in exports.items():\n print(f'export {var}=\"{GREEN}{val}{RESET}\"')\n\n print(\"\\nSave configuration? [Y/n]: \", end=\"\")\n if input().strip().lower() not in [\"n\", \"no\"]:\n unsets = config.get_unset_vars()\n save_config(exports, unsets)\n print(\"\\nConfiguration saved to: nvfuser_env.sh\")\n print(\"To apply: source nvfuser_env.sh\")\n\n\ndef save_config(\n exports: dict[str, str],\n unsets: list[str] | None = None,\n filename: str = \"nvfuser_env.sh\",\n) -> None:\n \"\"\"Save configuration to shell script with both exports and unsets\"\"\"\n with open(filename, \"w\") as f:\n f.write(\"#!/bin/bash\\n\")\n f.write(\"# nvFuser Environment Configuration\\n\")\n f.write(\"# Generated by tools/configure_env.py\\n\\n\")\n\n # Unset unconfigured variables first\n if unsets is not None:\n f.write(\"# Unset unconfigured variables\\n\")\n for var in sorted(unsets):\n f.write(f\"unset {var}\\n\")\n f.write(\"\\n\")\n\n # Export configured variables\n if exports:\n f.write(\"# Export configured variables\\n\")\n for var, val in sorted(exports.items()):\n f.write(f'export {var}=\"{val}\"\\n')\n\n # Set secure permissions (600 for apply scripts, 755 for user-generated scripts)\n # If filename starts with a dot, it's likely a temporary apply script\n if os.path.basename(filename).startswith(\".\"):\n os.chmod(filename, 0o600) # Apply scripts: owner read/write only\n else:\n os.chmod(filename, 0o755) # User scripts: executable by all\n\n\ndef generate_script_mode(config: EnvVarConfig) -> None:\n \"\"\"Generate a shell script with current environment configuration.\"\"\"\n exports = config.get_env_exports()\n\n if not exports:\n print(\"No environment variables currently set.\")\n print(\"Run interactive mode to configure variables first.\")\n return\n\n unsets = config.get_unset_vars()\n save_config(exports, unsets)\n print(\"\\nConfiguration saved to: nvfuser_env.sh\")\n print(\"To apply: source nvfuser_env.sh\")\n\n\ndef try_curses_mode(config: EnvVarConfig) -> None:\n \"\"\"Try to run curses-based TUI mode.\"\"\"\n try:\n import curses\n from curses_ui import run_curses_ui\n\n curses.wrapper(lambda stdscr: run_curses_ui(stdscr, config))\n except ImportError:\n print(\"Error: curses module not available.\")\n print(\"Falling back to simple mode.\")\n simple_prompt_mode(config)\n except Exception as e:\n print(f\"Error running TUI mode: {e}\")\n print(\"Falling back to simple mode.\")\n simple_prompt_mode(config)\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Interactive nvFuser environment configuration tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n %(prog)s # Run interactive TUI\n %(prog)s --simple # Run simple prompt mode\n %(prog)s --generate-script # Generate shell script from current env\n \"\"\",\n )\n\n parser.add_argument(\n \"--simple\", action=\"store_true\", help=\"Use simple prompt mode instead of TUI\"\n )\n\n parser.add_argument(\n \"--generate-script\",\n action=\"store_true\",\n help=\"Generate shell script from current environment\",\n )\n\n parser.add_argument(\n \"--output\",\n default=\"nvfuser_env.sh\",\n help=\"Output filename for generated script (default: nvfuser_env.sh)\",\n )\n\n args = parser.parse_args()\n\n config = EnvVarConfig()\n\n if args.generate_script:\n generate_script_mode(config)\n elif args.simple:\n simple_prompt_mode(config)\n else:\n try_curses_mode(config)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env.EnvVarConfig","uri":"program://Fuser/class/tools.env-config.configure_env.EnvVarConfig#L33-L138","kind":"class","name":"EnvVarConfig","path":"tools/env-config/configure_env.py","language":"python","start_line":33,"end_line":138,"context_start_line":13,"context_end_line":158,"code":"Usage:\n python tools/configure_env.py # Interactive TUI mode\n python tools/configure_env.py --simple # Simple prompt mode\n python tools/configure_env.py --generate-script # Generate shell script\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport os\nfrom pathlib import Path\n\n# Load environment options from YAML\nfrom options_loader import load_options_from_yaml, EnvVarOption\n\n# Load configuration from YAML file\n_yaml_path = Path(__file__).parent / \"env_options.yaml\"\nCATEGORY_NAMES, ENV_VAR_DEFINITIONS = load_options_from_yaml(_yaml_path)\n\n\nclass EnvVarConfig:\n \"\"\"Manages the current configuration state.\"\"\"\n\n def __init__(self) -> None:\n # Use (name, env_var) tuple as key to handle options with same name\n # but different env vars (e.g., expr_simplify in DUMP vs DISABLE)\n self.options: dict[tuple[str, str | None], EnvVarOption] = {\n (opt.name, opt.env_var): opt for opt in ENV_VAR_DEFINITIONS\n }\n # Also maintain a list of all options for iteration\n self.all_options: list[EnvVarOption] = ENV_VAR_DEFINITIONS.copy()\n self.categories: dict[str, list[EnvVarOption]] = self._organize_by_category()\n self._load_current_values()\n\n def _organize_by_category(self) -> dict[str, list[EnvVarOption]]:\n \"\"\"Organize options by category.\"\"\"\n categories: dict[str, list[EnvVarOption]] = {}\n for opt in self.all_options:\n if opt.category not in categories:\n categories[opt.category] = []\n categories[opt.category].append(opt)\n return categories\n\n def _load_current_values(self) -> None:\n \"\"\"Load current values from environment.\"\"\"\n for opt in self.all_options:\n env_var_name = opt.get_env_var_name()\n\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # These are comma-separated list values\n list_val = os.environ.get(env_var_name, \"\")\n if list_val:\n list_items = [item.strip() for item in list_val.split(\",\")]\n if opt.name in list_items:\n opt.current_value = \"1\"\n else:\n # Regular environment variables\n if env_var_name in os.environ:\n val = os.environ[env_var_name]\n if opt.var_type == \"bool\":\n if val.upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]:\n opt.current_value = \"1\"\n else:\n opt.current_value = val\n\n def get_env_exports(self) -> dict[str, str]:\n \"\"\"Generate environment variable exports based on current configuration.\"\"\"\n exports: dict[str, str] = {}\n\n # Collect values for list-based env vars (DUMP, ENABLE, DISABLE)\n list_vars: dict[str, list[str]] = {} # Maps env_var_name -> list of values\n\n for opt in self.all_options:\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # List items\n if opt.current_value == \"1\":\n env_var = opt.get_env_var_name()\n if env_var not in list_vars:\n list_vars[env_var] = []\n list_vars[env_var].append(opt.name)\n else:\n # Regular env vars\n if opt.current_value is not None:\n env_var = opt.get_env_var_name()\n if opt.var_type == \"bool\":\n if opt.current_value == \"1\":\n exports[env_var] = \"1\"\n else:\n exports[env_var] = opt.current_value\n\n # Add list-based env vars as comma-separated strings\n for env_var, values in list_vars.items():\n exports[env_var] = \",\".join(values)\n\n return exports\n\n def get_unset_vars(self) -> list[str]:\n \"\"\"Get list of ALL variable names that should be unset (empty or unconfigured)\n\n This unsets all known nvFuser variables that aren't configured, ensuring a\n clean slate when the script is sourced.\n \"\"\"\n unset_vars: set[str] = set() # Use set to avoid duplicates\n\n # Track which env vars have values\n env_vars_with_values: set[str] = set()\n\n for opt in self.all_options:\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # List-based vars - only track if any are set\n if opt.current_value == \"1\":\n env_vars_with_values.add(opt.get_env_var_name())\n else:\n # Regular env vars\n env_var = opt.get_env_var_name()\n if opt.current_value:\n env_vars_with_values.add(env_var)\n else:\n unset_vars.add(env_var)\n\n # Unset list vars that have no values set\n for list_var in [\"NVFUSER_DUMP\", \"NVFUSER_ENABLE\", \"NVFUSER_DISABLE\"]:\n if list_var not in env_vars_with_values:\n unset_vars.add(list_var)\n\n return sorted(list(unset_vars))\n\n\ndef simple_prompt_mode(config: EnvVarConfig) -> None:\n \"\"\"Simple prompt-based configuration mode (no curses).\"\"\"\n # ANSI color codes\n GREEN = \"\\033[92m\"\n CYAN = \"\\033[96m\"\n BOLD = \"\\033[1m\"\n RESET = \"\\033[0m\"\n\n print(\"=\" * 70)\n print(\"nvFuser Environment Configuration Tool - Simple Mode\")\n print(\"=\" * 70)\n print()\n\n for category in CATEGORY_NAMES.keys():\n if category not in config.categories:\n continue\n opts = config.categories[category]\n print(f\"\\n{CYAN}{BOLD}{CATEGORY_NAMES[category]}{RESET}\")","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env.simple_prompt_mode","uri":"program://Fuser/function/tools.env-config.configure_env.simple_prompt_mode#L141-L206","kind":"function","name":"simple_prompt_mode","path":"tools/env-config/configure_env.py","language":"python","start_line":141,"end_line":206,"context_start_line":121,"context_end_line":226,"code":" if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # List-based vars - only track if any are set\n if opt.current_value == \"1\":\n env_vars_with_values.add(opt.get_env_var_name())\n else:\n # Regular env vars\n env_var = opt.get_env_var_name()\n if opt.current_value:\n env_vars_with_values.add(env_var)\n else:\n unset_vars.add(env_var)\n\n # Unset list vars that have no values set\n for list_var in [\"NVFUSER_DUMP\", \"NVFUSER_ENABLE\", \"NVFUSER_DISABLE\"]:\n if list_var not in env_vars_with_values:\n unset_vars.add(list_var)\n\n return sorted(list(unset_vars))\n\n\ndef simple_prompt_mode(config: EnvVarConfig) -> None:\n \"\"\"Simple prompt-based configuration mode (no curses).\"\"\"\n # ANSI color codes\n GREEN = \"\\033[92m\"\n CYAN = \"\\033[96m\"\n BOLD = \"\\033[1m\"\n RESET = \"\\033[0m\"\n\n print(\"=\" * 70)\n print(\"nvFuser Environment Configuration Tool - Simple Mode\")\n print(\"=\" * 70)\n print()\n\n for category in CATEGORY_NAMES.keys():\n if category not in config.categories:\n continue\n opts = config.categories[category]\n print(f\"\\n{CYAN}{BOLD}{CATEGORY_NAMES[category]}{RESET}\")\n print(\"-\" * 70)\n\n for opt in opts:\n # Show current value in green if set\n if opt.current_value:\n current = f\"{GREEN}{opt.current_value}{RESET}\"\n else:\n current = \"(not set)\"\n\n # Format the option name with type indicator\n opt_name = opt.name\n if opt.var_type == \"multi\":\n opt_name += \" [multi]\"\n\n print(f\"\\n{opt_name}:\")\n print(f\" Description: {opt.description}\")\n print(f\" Current: {current}\")\n\n match opt.var_type:\n case \"bool\":\n response = input(\" Enable? [y/N]: \").strip().lower()\n opt.current_value = \"1\" if response in [\"y\", \"yes\"] else None\n case \"multi\":\n print(f\" Choices: {', '.join(repr(c) for c in opt.choices)}\")\n default = opt.choices[0] if opt.choices else \"\"\n response = input(f\" Select [{default}]: \").strip()\n opt.current_value = response if response else default\n case \"int\" | \"string\":\n response = input(\" Value: \").strip()\n opt.current_value = response if response else None\n\n print(\"\\n\" + \"=\" * 70)\n print(f\"{BOLD}Configuration Summary{RESET}\")\n print(\"=\" * 70)\n\n exports = config.get_env_exports()\n if not exports:\n print(\"No environment variables configured.\")\n else:\n for var, val in exports.items():\n print(f'export {var}=\"{GREEN}{val}{RESET}\"')\n\n print(\"\\nSave configuration? [Y/n]: \", end=\"\")\n if input().strip().lower() not in [\"n\", \"no\"]:\n unsets = config.get_unset_vars()\n save_config(exports, unsets)\n print(\"\\nConfiguration saved to: nvfuser_env.sh\")\n print(\"To apply: source nvfuser_env.sh\")\n\n\ndef save_config(\n exports: dict[str, str],\n unsets: list[str] | None = None,\n filename: str = \"nvfuser_env.sh\",\n) -> None:\n \"\"\"Save configuration to shell script with both exports and unsets\"\"\"\n with open(filename, \"w\") as f:\n f.write(\"#!/bin/bash\\n\")\n f.write(\"# nvFuser Environment Configuration\\n\")\n f.write(\"# Generated by tools/configure_env.py\\n\\n\")\n\n # Unset unconfigured variables first\n if unsets is not None:\n f.write(\"# Unset unconfigured variables\\n\")\n for var in sorted(unsets):\n f.write(f\"unset {var}\\n\")\n f.write(\"\\n\")\n","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env.save_config","uri":"program://Fuser/function/tools.env-config.configure_env.save_config#L209-L238","kind":"function","name":"save_config","path":"tools/env-config/configure_env.py","language":"python","start_line":209,"end_line":238,"context_start_line":189,"context_end_line":258,"code":"\n print(\"\\n\" + \"=\" * 70)\n print(f\"{BOLD}Configuration Summary{RESET}\")\n print(\"=\" * 70)\n\n exports = config.get_env_exports()\n if not exports:\n print(\"No environment variables configured.\")\n else:\n for var, val in exports.items():\n print(f'export {var}=\"{GREEN}{val}{RESET}\"')\n\n print(\"\\nSave configuration? [Y/n]: \", end=\"\")\n if input().strip().lower() not in [\"n\", \"no\"]:\n unsets = config.get_unset_vars()\n save_config(exports, unsets)\n print(\"\\nConfiguration saved to: nvfuser_env.sh\")\n print(\"To apply: source nvfuser_env.sh\")\n\n\ndef save_config(\n exports: dict[str, str],\n unsets: list[str] | None = None,\n filename: str = \"nvfuser_env.sh\",\n) -> None:\n \"\"\"Save configuration to shell script with both exports and unsets\"\"\"\n with open(filename, \"w\") as f:\n f.write(\"#!/bin/bash\\n\")\n f.write(\"# nvFuser Environment Configuration\\n\")\n f.write(\"# Generated by tools/configure_env.py\\n\\n\")\n\n # Unset unconfigured variables first\n if unsets is not None:\n f.write(\"# Unset unconfigured variables\\n\")\n for var in sorted(unsets):\n f.write(f\"unset {var}\\n\")\n f.write(\"\\n\")\n\n # Export configured variables\n if exports:\n f.write(\"# Export configured variables\\n\")\n for var, val in sorted(exports.items()):\n f.write(f'export {var}=\"{val}\"\\n')\n\n # Set secure permissions (600 for apply scripts, 755 for user-generated scripts)\n # If filename starts with a dot, it's likely a temporary apply script\n if os.path.basename(filename).startswith(\".\"):\n os.chmod(filename, 0o600) # Apply scripts: owner read/write only\n else:\n os.chmod(filename, 0o755) # User scripts: executable by all\n\n\ndef generate_script_mode(config: EnvVarConfig) -> None:\n \"\"\"Generate a shell script with current environment configuration.\"\"\"\n exports = config.get_env_exports()\n\n if not exports:\n print(\"No environment variables currently set.\")\n print(\"Run interactive mode to configure variables first.\")\n return\n\n unsets = config.get_unset_vars()\n save_config(exports, unsets)\n print(\"\\nConfiguration saved to: nvfuser_env.sh\")\n print(\"To apply: source nvfuser_env.sh\")\n\n\ndef try_curses_mode(config: EnvVarConfig) -> None:\n \"\"\"Try to run curses-based TUI mode.\"\"\"\n try:","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env.generate_script_mode","uri":"program://Fuser/function/tools.env-config.configure_env.generate_script_mode#L241-L253","kind":"function","name":"generate_script_mode","path":"tools/env-config/configure_env.py","language":"python","start_line":241,"end_line":253,"context_start_line":221,"context_end_line":273,"code":" if unsets is not None:\n f.write(\"# Unset unconfigured variables\\n\")\n for var in sorted(unsets):\n f.write(f\"unset {var}\\n\")\n f.write(\"\\n\")\n\n # Export configured variables\n if exports:\n f.write(\"# Export configured variables\\n\")\n for var, val in sorted(exports.items()):\n f.write(f'export {var}=\"{val}\"\\n')\n\n # Set secure permissions (600 for apply scripts, 755 for user-generated scripts)\n # If filename starts with a dot, it's likely a temporary apply script\n if os.path.basename(filename).startswith(\".\"):\n os.chmod(filename, 0o600) # Apply scripts: owner read/write only\n else:\n os.chmod(filename, 0o755) # User scripts: executable by all\n\n\ndef generate_script_mode(config: EnvVarConfig) -> None:\n \"\"\"Generate a shell script with current environment configuration.\"\"\"\n exports = config.get_env_exports()\n\n if not exports:\n print(\"No environment variables currently set.\")\n print(\"Run interactive mode to configure variables first.\")\n return\n\n unsets = config.get_unset_vars()\n save_config(exports, unsets)\n print(\"\\nConfiguration saved to: nvfuser_env.sh\")\n print(\"To apply: source nvfuser_env.sh\")\n\n\ndef try_curses_mode(config: EnvVarConfig) -> None:\n \"\"\"Try to run curses-based TUI mode.\"\"\"\n try:\n import curses\n from curses_ui import run_curses_ui\n\n curses.wrapper(lambda stdscr: run_curses_ui(stdscr, config))\n except ImportError:\n print(\"Error: curses module not available.\")\n print(\"Falling back to simple mode.\")\n simple_prompt_mode(config)\n except Exception as e:\n print(f\"Error running TUI mode: {e}\")\n print(\"Falling back to simple mode.\")\n simple_prompt_mode(config)\n\n\ndef main() -> None:","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env.try_curses_mode","uri":"program://Fuser/function/tools.env-config.configure_env.try_curses_mode#L256-L270","kind":"function","name":"try_curses_mode","path":"tools/env-config/configure_env.py","language":"python","start_line":256,"end_line":270,"context_start_line":236,"context_end_line":290,"code":" os.chmod(filename, 0o600) # Apply scripts: owner read/write only\n else:\n os.chmod(filename, 0o755) # User scripts: executable by all\n\n\ndef generate_script_mode(config: EnvVarConfig) -> None:\n \"\"\"Generate a shell script with current environment configuration.\"\"\"\n exports = config.get_env_exports()\n\n if not exports:\n print(\"No environment variables currently set.\")\n print(\"Run interactive mode to configure variables first.\")\n return\n\n unsets = config.get_unset_vars()\n save_config(exports, unsets)\n print(\"\\nConfiguration saved to: nvfuser_env.sh\")\n print(\"To apply: source nvfuser_env.sh\")\n\n\ndef try_curses_mode(config: EnvVarConfig) -> None:\n \"\"\"Try to run curses-based TUI mode.\"\"\"\n try:\n import curses\n from curses_ui import run_curses_ui\n\n curses.wrapper(lambda stdscr: run_curses_ui(stdscr, config))\n except ImportError:\n print(\"Error: curses module not available.\")\n print(\"Falling back to simple mode.\")\n simple_prompt_mode(config)\n except Exception as e:\n print(f\"Error running TUI mode: {e}\")\n print(\"Falling back to simple mode.\")\n simple_prompt_mode(config)\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Interactive nvFuser environment configuration tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n %(prog)s # Run interactive TUI\n %(prog)s --simple # Run simple prompt mode\n %(prog)s --generate-script # Generate shell script from current env\n \"\"\",\n )\n\n parser.add_argument(\n \"--simple\", action=\"store_true\", help=\"Use simple prompt mode instead of TUI\"\n )\n\n parser.add_argument(\n \"--generate-script\",","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env.main","uri":"program://Fuser/function/tools.env-config.configure_env.main#L273-L310","kind":"function","name":"main","path":"tools/env-config/configure_env.py","language":"python","start_line":273,"end_line":310,"context_start_line":253,"context_end_line":314,"code":" print(\"To apply: source nvfuser_env.sh\")\n\n\ndef try_curses_mode(config: EnvVarConfig) -> None:\n \"\"\"Try to run curses-based TUI mode.\"\"\"\n try:\n import curses\n from curses_ui import run_curses_ui\n\n curses.wrapper(lambda stdscr: run_curses_ui(stdscr, config))\n except ImportError:\n print(\"Error: curses module not available.\")\n print(\"Falling back to simple mode.\")\n simple_prompt_mode(config)\n except Exception as e:\n print(f\"Error running TUI mode: {e}\")\n print(\"Falling back to simple mode.\")\n simple_prompt_mode(config)\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Interactive nvFuser environment configuration tool\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n %(prog)s # Run interactive TUI\n %(prog)s --simple # Run simple prompt mode\n %(prog)s --generate-script # Generate shell script from current env\n \"\"\",\n )\n\n parser.add_argument(\n \"--simple\", action=\"store_true\", help=\"Use simple prompt mode instead of TUI\"\n )\n\n parser.add_argument(\n \"--generate-script\",\n action=\"store_true\",\n help=\"Generate shell script from current environment\",\n )\n\n parser.add_argument(\n \"--output\",\n default=\"nvfuser_env.sh\",\n help=\"Output filename for generated script (default: nvfuser_env.sh)\",\n )\n\n args = parser.parse_args()\n\n config = EnvVarConfig()\n\n if args.generate_script:\n generate_script_mode(config)\n elif args.simple:\n simple_prompt_mode(config)\n else:\n try_curses_mode(config)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env.__init__","uri":"program://Fuser/function/tools.env-config.configure_env.__init__#L36-L45","kind":"function","name":"__init__","path":"tools/env-config/configure_env.py","language":"python","start_line":36,"end_line":45,"context_start_line":16,"context_end_line":65,"code":" python tools/configure_env.py --generate-script # Generate shell script\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport os\nfrom pathlib import Path\n\n# Load environment options from YAML\nfrom options_loader import load_options_from_yaml, EnvVarOption\n\n# Load configuration from YAML file\n_yaml_path = Path(__file__).parent / \"env_options.yaml\"\nCATEGORY_NAMES, ENV_VAR_DEFINITIONS = load_options_from_yaml(_yaml_path)\n\n\nclass EnvVarConfig:\n \"\"\"Manages the current configuration state.\"\"\"\n\n def __init__(self) -> None:\n # Use (name, env_var) tuple as key to handle options with same name\n # but different env vars (e.g., expr_simplify in DUMP vs DISABLE)\n self.options: dict[tuple[str, str | None], EnvVarOption] = {\n (opt.name, opt.env_var): opt for opt in ENV_VAR_DEFINITIONS\n }\n # Also maintain a list of all options for iteration\n self.all_options: list[EnvVarOption] = ENV_VAR_DEFINITIONS.copy()\n self.categories: dict[str, list[EnvVarOption]] = self._organize_by_category()\n self._load_current_values()\n\n def _organize_by_category(self) -> dict[str, list[EnvVarOption]]:\n \"\"\"Organize options by category.\"\"\"\n categories: dict[str, list[EnvVarOption]] = {}\n for opt in self.all_options:\n if opt.category not in categories:\n categories[opt.category] = []\n categories[opt.category].append(opt)\n return categories\n\n def _load_current_values(self) -> None:\n \"\"\"Load current values from environment.\"\"\"\n for opt in self.all_options:\n env_var_name = opt.get_env_var_name()\n\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # These are comma-separated list values\n list_val = os.environ.get(env_var_name, \"\")\n if list_val:\n list_items = [item.strip() for item in list_val.split(\",\")]","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env._organize_by_category","uri":"program://Fuser/function/tools.env-config.configure_env._organize_by_category#L47-L54","kind":"function","name":"_organize_by_category","path":"tools/env-config/configure_env.py","language":"python","start_line":47,"end_line":54,"context_start_line":27,"context_end_line":74,"code":"\n# Load configuration from YAML file\n_yaml_path = Path(__file__).parent / \"env_options.yaml\"\nCATEGORY_NAMES, ENV_VAR_DEFINITIONS = load_options_from_yaml(_yaml_path)\n\n\nclass EnvVarConfig:\n \"\"\"Manages the current configuration state.\"\"\"\n\n def __init__(self) -> None:\n # Use (name, env_var) tuple as key to handle options with same name\n # but different env vars (e.g., expr_simplify in DUMP vs DISABLE)\n self.options: dict[tuple[str, str | None], EnvVarOption] = {\n (opt.name, opt.env_var): opt for opt in ENV_VAR_DEFINITIONS\n }\n # Also maintain a list of all options for iteration\n self.all_options: list[EnvVarOption] = ENV_VAR_DEFINITIONS.copy()\n self.categories: dict[str, list[EnvVarOption]] = self._organize_by_category()\n self._load_current_values()\n\n def _organize_by_category(self) -> dict[str, list[EnvVarOption]]:\n \"\"\"Organize options by category.\"\"\"\n categories: dict[str, list[EnvVarOption]] = {}\n for opt in self.all_options:\n if opt.category not in categories:\n categories[opt.category] = []\n categories[opt.category].append(opt)\n return categories\n\n def _load_current_values(self) -> None:\n \"\"\"Load current values from environment.\"\"\"\n for opt in self.all_options:\n env_var_name = opt.get_env_var_name()\n\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # These are comma-separated list values\n list_val = os.environ.get(env_var_name, \"\")\n if list_val:\n list_items = [item.strip() for item in list_val.split(\",\")]\n if opt.name in list_items:\n opt.current_value = \"1\"\n else:\n # Regular environment variables\n if env_var_name in os.environ:\n val = os.environ[env_var_name]\n if opt.var_type == \"bool\":\n if val.upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]:\n opt.current_value = \"1\"","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env._load_current_values","uri":"program://Fuser/function/tools.env-config.configure_env._load_current_values#L56-L76","kind":"function","name":"_load_current_values","path":"tools/env-config/configure_env.py","language":"python","start_line":56,"end_line":76,"context_start_line":36,"context_end_line":96,"code":" def __init__(self) -> None:\n # Use (name, env_var) tuple as key to handle options with same name\n # but different env vars (e.g., expr_simplify in DUMP vs DISABLE)\n self.options: dict[tuple[str, str | None], EnvVarOption] = {\n (opt.name, opt.env_var): opt for opt in ENV_VAR_DEFINITIONS\n }\n # Also maintain a list of all options for iteration\n self.all_options: list[EnvVarOption] = ENV_VAR_DEFINITIONS.copy()\n self.categories: dict[str, list[EnvVarOption]] = self._organize_by_category()\n self._load_current_values()\n\n def _organize_by_category(self) -> dict[str, list[EnvVarOption]]:\n \"\"\"Organize options by category.\"\"\"\n categories: dict[str, list[EnvVarOption]] = {}\n for opt in self.all_options:\n if opt.category not in categories:\n categories[opt.category] = []\n categories[opt.category].append(opt)\n return categories\n\n def _load_current_values(self) -> None:\n \"\"\"Load current values from environment.\"\"\"\n for opt in self.all_options:\n env_var_name = opt.get_env_var_name()\n\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # These are comma-separated list values\n list_val = os.environ.get(env_var_name, \"\")\n if list_val:\n list_items = [item.strip() for item in list_val.split(\",\")]\n if opt.name in list_items:\n opt.current_value = \"1\"\n else:\n # Regular environment variables\n if env_var_name in os.environ:\n val = os.environ[env_var_name]\n if opt.var_type == \"bool\":\n if val.upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]:\n opt.current_value = \"1\"\n else:\n opt.current_value = val\n\n def get_env_exports(self) -> dict[str, str]:\n \"\"\"Generate environment variable exports based on current configuration.\"\"\"\n exports: dict[str, str] = {}\n\n # Collect values for list-based env vars (DUMP, ENABLE, DISABLE)\n list_vars: dict[str, list[str]] = {} # Maps env_var_name -> list of values\n\n for opt in self.all_options:\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # List items\n if opt.current_value == \"1\":\n env_var = opt.get_env_var_name()\n if env_var not in list_vars:\n list_vars[env_var] = []\n list_vars[env_var].append(opt.name)\n else:\n # Regular env vars\n if opt.current_value is not None:\n env_var = opt.get_env_var_name()","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env.get_env_exports","uri":"program://Fuser/function/tools.env-config.configure_env.get_env_exports#L78-L107","kind":"function","name":"get_env_exports","path":"tools/env-config/configure_env.py","language":"python","start_line":78,"end_line":107,"context_start_line":58,"context_end_line":127,"code":" for opt in self.all_options:\n env_var_name = opt.get_env_var_name()\n\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # These are comma-separated list values\n list_val = os.environ.get(env_var_name, \"\")\n if list_val:\n list_items = [item.strip() for item in list_val.split(\",\")]\n if opt.name in list_items:\n opt.current_value = \"1\"\n else:\n # Regular environment variables\n if env_var_name in os.environ:\n val = os.environ[env_var_name]\n if opt.var_type == \"bool\":\n if val.upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]:\n opt.current_value = \"1\"\n else:\n opt.current_value = val\n\n def get_env_exports(self) -> dict[str, str]:\n \"\"\"Generate environment variable exports based on current configuration.\"\"\"\n exports: dict[str, str] = {}\n\n # Collect values for list-based env vars (DUMP, ENABLE, DISABLE)\n list_vars: dict[str, list[str]] = {} # Maps env_var_name -> list of values\n\n for opt in self.all_options:\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # List items\n if opt.current_value == \"1\":\n env_var = opt.get_env_var_name()\n if env_var not in list_vars:\n list_vars[env_var] = []\n list_vars[env_var].append(opt.name)\n else:\n # Regular env vars\n if opt.current_value is not None:\n env_var = opt.get_env_var_name()\n if opt.var_type == \"bool\":\n if opt.current_value == \"1\":\n exports[env_var] = \"1\"\n else:\n exports[env_var] = opt.current_value\n\n # Add list-based env vars as comma-separated strings\n for env_var, values in list_vars.items():\n exports[env_var] = \",\".join(values)\n\n return exports\n\n def get_unset_vars(self) -> list[str]:\n \"\"\"Get list of ALL variable names that should be unset (empty or unconfigured)\n\n This unsets all known nvFuser variables that aren't configured, ensuring a\n clean slate when the script is sourced.\n \"\"\"\n unset_vars: set[str] = set() # Use set to avoid duplicates\n\n # Track which env vars have values\n env_vars_with_values: set[str] = set()\n\n for opt in self.all_options:\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # List-based vars - only track if any are set\n if opt.current_value == \"1\":\n env_vars_with_values.add(opt.get_env_var_name())\n else:\n # Regular env vars\n env_var = opt.get_env_var_name()","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.env-config.configure_env.get_unset_vars","uri":"program://Fuser/function/tools.env-config.configure_env.get_unset_vars#L109-L138","kind":"function","name":"get_unset_vars","path":"tools/env-config/configure_env.py","language":"python","start_line":109,"end_line":138,"context_start_line":89,"context_end_line":158,"code":" env_var = opt.get_env_var_name()\n if env_var not in list_vars:\n list_vars[env_var] = []\n list_vars[env_var].append(opt.name)\n else:\n # Regular env vars\n if opt.current_value is not None:\n env_var = opt.get_env_var_name()\n if opt.var_type == \"bool\":\n if opt.current_value == \"1\":\n exports[env_var] = \"1\"\n else:\n exports[env_var] = opt.current_value\n\n # Add list-based env vars as comma-separated strings\n for env_var, values in list_vars.items():\n exports[env_var] = \",\".join(values)\n\n return exports\n\n def get_unset_vars(self) -> list[str]:\n \"\"\"Get list of ALL variable names that should be unset (empty or unconfigured)\n\n This unsets all known nvFuser variables that aren't configured, ensuring a\n clean slate when the script is sourced.\n \"\"\"\n unset_vars: set[str] = set() # Use set to avoid duplicates\n\n # Track which env vars have values\n env_vars_with_values: set[str] = set()\n\n for opt in self.all_options:\n if opt.category in [\"dump\", \"enable\", \"disable\"]:\n # List-based vars - only track if any are set\n if opt.current_value == \"1\":\n env_vars_with_values.add(opt.get_env_var_name())\n else:\n # Regular env vars\n env_var = opt.get_env_var_name()\n if opt.current_value:\n env_vars_with_values.add(env_var)\n else:\n unset_vars.add(env_var)\n\n # Unset list vars that have no values set\n for list_var in [\"NVFUSER_DUMP\", \"NVFUSER_ENABLE\", \"NVFUSER_DISABLE\"]:\n if list_var not in env_vars_with_values:\n unset_vars.add(list_var)\n\n return sorted(list(unset_vars))\n\n\ndef simple_prompt_mode(config: EnvVarConfig) -> None:\n \"\"\"Simple prompt-based configuration mode (no curses).\"\"\"\n # ANSI color codes\n GREEN = \"\\033[92m\"\n CYAN = \"\\033[96m\"\n BOLD = \"\\033[1m\"\n RESET = \"\\033[0m\"\n\n print(\"=\" * 70)\n print(\"nvFuser Environment Configuration Tool - Simple Mode\")\n print(\"=\" * 70)\n print()\n\n for category in CATEGORY_NAMES.keys():\n if category not in config.categories:\n continue\n opts = config.categories[category]\n print(f\"\\n{CYAN}{BOLD}{CATEGORY_NAMES[category]}{RESET}\")","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter","uri":"program://Fuser/module/tools.linter.adapters.clangtidy_linter#L1-L297","kind":"module","name":"tools.linter.adapters.clangtidy_linter","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":1,"end_line":297,"context_start_line":1,"context_end_line":297,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport sysconfig\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, List, NamedTuple, Optional, Pattern\n\n# Nvfuser directory root\nresult = subprocess.run(\n [\"git\", \"rev-parse\", \"--show-toplevel\"],\n stdout=subprocess.PIPE,\n check=True,\n)\nNVFUSER_ROOT = result.stdout.decode(\"utf-8\").strip()\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\n# Returns '/usr/local/include/python'\ndef get_python_include_dir() -> str:\n return sysconfig.get_paths()[\"include\"]\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# c10/core/DispatchKey.cpp:281:26: error: 'k' used after it was moved [bugprone-use-after-move]\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n \\s(?P\\[.*\\])\n $\n \"\"\"\n)\n\n\ndef run_command(\n args: List[str],\n) -> subprocess.CompletedProcess[str]:\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n capture_output=True,\n check=True,\n text=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\n# Severity is either \"error\" or \"note\":\n# https://github.com/python/mypy/blob/8b47a032e1317fb8e3f9a818005a6b63e9bf0311/mypy/errors.py#L46-L47\nseverities = {\n \"error\": LintSeverity.ERROR,\n \"warning\": LintSeverity.WARNING,\n}\n\n\ndef clang_search_dirs() -> List[str]:\n # Compilers are ordered based on fallback preference\n # We pick the first one that is available on the system\n compilers = [\"clang\", \"gcc\", \"cpp\", \"cc\"]\n compilers = [c for c in compilers if shutil.which(c) is not None]\n if len(compilers) == 0:\n raise RuntimeError(f\"None of {compilers} were found\")\n compiler = compilers[0]\n\n result = subprocess.run(\n [compiler, \"-E\", \"-x\", \"c++\", \"-\", \"-v\"],\n stdin=subprocess.DEVNULL,\n capture_output=True,\n check=True,\n )\n stderr = result.stderr.decode().strip().split(\"\\n\")\n search_start = r\"#include.*search starts here:\"\n search_end = r\"End of search list.\"\n\n append_path = False\n search_paths = []\n for line in stderr:\n if re.match(search_start, line):\n if append_path:\n continue\n else:\n append_path = True\n elif re.match(search_end, line):\n break\n elif append_path:\n search_paths.append(line.strip())\n\n return search_paths\n\n\n# NVFUSER_USE_PCH=ON somehow requires the CUDA include dir e.g.\n# \"/usr/local/cuda-13.0/targets/x86_64-linux/include\". I'll try to add that in\n# a future PR.\ninclude_dir = [\n get_python_include_dir(),\n os.path.join(NVFUSER_ROOT, \"third_party/pybind11/include\"),\n] + clang_search_dirs()\n\ninclude_args = [\"--extra-arg=-Wno-unknown-warning-option\"]\nfor dir in include_dir:\n include_args += [\"--extra-arg\", f\"-I{dir}\"]\n\n\ndef check_file(\n filename: str,\n binary: str,\n build_dir: Path,\n) -> List[LintMessage]:\n try:\n proc = run_command(\n [binary, f\"-p={build_dir}\", *include_args, filename],\n )\n except subprocess.CalledProcessError as err:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"CLANGTIDY\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err}\\n\\nstdout:\\n{err.stdout}\\nstderr:\\n{err.stderr}\"\n ),\n )\n ]\n lint_messages = []\n try:\n # Change the current working directory to the build directory, since\n # clang-tidy will report files relative to the build directory.\n saved_cwd = os.getcwd()\n os.chdir(build_dir)\n\n for match in RESULTS_RE.finditer(proc.stdout):\n # Convert the reported path to an absolute path.\n abs_path = str(Path(match[\"file\"]).resolve())\n message = LintMessage(\n path=abs_path,\n name=match[\"code\"],\n description=match[\"message\"],\n line=int(match[\"line\"]),\n char=int(match[\"column\"])\n if match[\"column\"] is not None and not match[\"column\"].startswith(\"-\")\n else None,\n code=\"CLANGTIDY\",\n severity=severities.get(match[\"severity\"], LintSeverity.ERROR),\n original=None,\n replacement=None,\n )\n lint_messages.append(message)\n finally:\n os.chdir(saved_cwd)\n\n return lint_messages\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"clang-tidy wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--build-dir\",\n \"--build_dir\",\n required=True,\n help=(\n \"Where the compile_commands.json file is located. \"\n \"Gets passed to clang-tidy -p\"\n ),\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n try:\n llvm_bindir = subprocess.check_output(\n [\"llvm-config\", \"--bindir\"], text=True\n ).strip()\n except FileNotFoundError:\n err_msg = LintMessage(\n path=\"\",\n line=None,\n char=None,\n code=\"CLANGTIDY\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=\"llvm-config doesn't exist (is LLVM installed?).\",\n )\n print(json.dumps(err_msg._asdict()), flush=True)\n exit(0)\n\n binary_path = os.path.join(llvm_bindir, \"clang-tidy\")\n if not os.path.exists(binary_path):\n err_msg = LintMessage(\n path=\"\",\n line=None,\n char=None,\n code=\"CLANGTIDY\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=f\"Could not find clang-tidy binary at {binary_path} (is LLVM installed?)\",\n )\n print(json.dumps(err_msg._asdict()), flush=True)\n exit(0)\n\n abs_build_dir = Path(args.build_dir).resolve()\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=os.cpu_count(),\n thread_name_prefix=\"Thread\",\n ) as executor:\n futures = {\n executor.submit(\n check_file,\n filename,\n binary_path,\n abs_build_dir,\n ): filename\n for filename in args.filenames\n }\n for future in concurrent.futures.as_completed(futures):\n try:\n for lint_message in future.result():\n print(json.dumps(lint_message._asdict()), flush=True)\n except Exception:\n logging.critical('Failed at \"%s\".', futures[future])\n raise\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter.get_python_include_dir","uri":"program://Fuser/function/tools.linter.adapters.clangtidy_linter.get_python_include_dir#L27-L28","kind":"function","name":"get_python_include_dir","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":27,"end_line":28,"context_start_line":7,"context_end_line":48,"code":"import shutil\nimport subprocess\nimport sys\nimport sysconfig\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, List, NamedTuple, Optional, Pattern\n\n# Nvfuser directory root\nresult = subprocess.run(\n [\"git\", \"rev-parse\", \"--show-toplevel\"],\n stdout=subprocess.PIPE,\n check=True,\n)\nNVFUSER_ROOT = result.stdout.decode(\"utf-8\").strip()\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\n# Returns '/usr/local/include/python'\ndef get_python_include_dir() -> str:\n return sysconfig.get_paths()[\"include\"]\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter.eprint","uri":"program://Fuser/function/tools.linter.adapters.clangtidy_linter.eprint#L31-L32","kind":"function","name":"eprint","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":31,"end_line":32,"context_start_line":11,"context_end_line":52,"code":"import time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, List, NamedTuple, Optional, Pattern\n\n# Nvfuser directory root\nresult = subprocess.run(\n [\"git\", \"rev-parse\", \"--show-toplevel\"],\n stdout=subprocess.PIPE,\n check=True,\n)\nNVFUSER_ROOT = result.stdout.decode(\"utf-8\").strip()\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\n# Returns '/usr/local/include/python'\ndef get_python_include_dir() -> str:\n return sysconfig.get_paths()[\"include\"]\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter.LintSeverity","uri":"program://Fuser/class/tools.linter.adapters.clangtidy_linter.LintSeverity#L35-L39","kind":"class","name":"LintSeverity","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":35,"end_line":39,"context_start_line":15,"context_end_line":59,"code":"\n# Nvfuser directory root\nresult = subprocess.run(\n [\"git\", \"rev-parse\", \"--show-toplevel\"],\n stdout=subprocess.PIPE,\n check=True,\n)\nNVFUSER_ROOT = result.stdout.decode(\"utf-8\").strip()\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\n# Returns '/usr/local/include/python'\ndef get_python_include_dir() -> str:\n return sysconfig.get_paths()[\"include\"]\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# c10/core/DispatchKey.cpp:281:26: error: 'k' used after it was moved [bugprone-use-after-move]\nRESULTS_RE: Pattern[str] = re.compile(","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter.LintMessage","uri":"program://Fuser/class/tools.linter.adapters.clangtidy_linter.LintMessage#L42-L51","kind":"class","name":"LintMessage","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":42,"end_line":51,"context_start_line":22,"context_end_line":71,"code":"NVFUSER_ROOT = result.stdout.decode(\"utf-8\").strip()\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\n# Returns '/usr/local/include/python'\ndef get_python_include_dir() -> str:\n return sysconfig.get_paths()[\"include\"]\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# c10/core/DispatchKey.cpp:281:26: error: 'k' used after it was moved [bugprone-use-after-move]\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n \\s(?P\\[.*\\])\n $\n \"\"\"\n)\n","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter.as_posix","uri":"program://Fuser/function/tools.linter.adapters.clangtidy_linter.as_posix#L54-L55","kind":"function","name":"as_posix","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":54,"end_line":55,"context_start_line":34,"context_end_line":75,"code":"\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# c10/core/DispatchKey.cpp:281:26: error: 'k' used after it was moved [bugprone-use-after-move]\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n \\s(?P\\[.*\\])\n $\n \"\"\"\n)\n\n\ndef run_command(\n args: List[str],\n) -> subprocess.CompletedProcess[str]:","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter.run_command","uri":"program://Fuser/function/tools.linter.adapters.clangtidy_linter.run_command#L73-L87","kind":"function","name":"run_command","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":73,"end_line":87,"context_start_line":53,"context_end_line":107,"code":"\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# c10/core/DispatchKey.cpp:281:26: error: 'k' used after it was moved [bugprone-use-after-move]\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n \\s(?P\\[.*\\])\n $\n \"\"\"\n)\n\n\ndef run_command(\n args: List[str],\n) -> subprocess.CompletedProcess[str]:\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n capture_output=True,\n check=True,\n text=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\n# Severity is either \"error\" or \"note\":\n# https://github.com/python/mypy/blob/8b47a032e1317fb8e3f9a818005a6b63e9bf0311/mypy/errors.py#L46-L47\nseverities = {\n \"error\": LintSeverity.ERROR,\n \"warning\": LintSeverity.WARNING,\n}\n\n\ndef clang_search_dirs() -> List[str]:\n # Compilers are ordered based on fallback preference\n # We pick the first one that is available on the system\n compilers = [\"clang\", \"gcc\", \"cpp\", \"cc\"]\n compilers = [c for c in compilers if shutil.which(c) is not None]\n if len(compilers) == 0:\n raise RuntimeError(f\"None of {compilers} were found\")\n compiler = compilers[0]\n\n result = subprocess.run(","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter.clang_search_dirs","uri":"program://Fuser/function/tools.linter.adapters.clangtidy_linter.clang_search_dirs#L98-L130","kind":"function","name":"clang_search_dirs","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":98,"end_line":130,"context_start_line":78,"context_end_line":150,"code":" try:\n return subprocess.run(\n args,\n capture_output=True,\n check=True,\n text=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\n# Severity is either \"error\" or \"note\":\n# https://github.com/python/mypy/blob/8b47a032e1317fb8e3f9a818005a6b63e9bf0311/mypy/errors.py#L46-L47\nseverities = {\n \"error\": LintSeverity.ERROR,\n \"warning\": LintSeverity.WARNING,\n}\n\n\ndef clang_search_dirs() -> List[str]:\n # Compilers are ordered based on fallback preference\n # We pick the first one that is available on the system\n compilers = [\"clang\", \"gcc\", \"cpp\", \"cc\"]\n compilers = [c for c in compilers if shutil.which(c) is not None]\n if len(compilers) == 0:\n raise RuntimeError(f\"None of {compilers} were found\")\n compiler = compilers[0]\n\n result = subprocess.run(\n [compiler, \"-E\", \"-x\", \"c++\", \"-\", \"-v\"],\n stdin=subprocess.DEVNULL,\n capture_output=True,\n check=True,\n )\n stderr = result.stderr.decode().strip().split(\"\\n\")\n search_start = r\"#include.*search starts here:\"\n search_end = r\"End of search list.\"\n\n append_path = False\n search_paths = []\n for line in stderr:\n if re.match(search_start, line):\n if append_path:\n continue\n else:\n append_path = True\n elif re.match(search_end, line):\n break\n elif append_path:\n search_paths.append(line.strip())\n\n return search_paths\n\n\n# NVFUSER_USE_PCH=ON somehow requires the CUDA include dir e.g.\n# \"/usr/local/cuda-13.0/targets/x86_64-linux/include\". I'll try to add that in\n# a future PR.\ninclude_dir = [\n get_python_include_dir(),\n os.path.join(NVFUSER_ROOT, \"third_party/pybind11/include\"),\n] + clang_search_dirs()\n\ninclude_args = [\"--extra-arg=-Wno-unknown-warning-option\"]\nfor dir in include_dir:\n include_args += [\"--extra-arg\", f\"-I{dir}\"]\n\n\ndef check_file(\n filename: str,\n binary: str,\n build_dir: Path,\n) -> List[LintMessage]:","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter.check_file","uri":"program://Fuser/function/tools.linter.adapters.clangtidy_linter.check_file#L146-L198","kind":"function","name":"check_file","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":146,"end_line":198,"context_start_line":126,"context_end_line":218,"code":" break\n elif append_path:\n search_paths.append(line.strip())\n\n return search_paths\n\n\n# NVFUSER_USE_PCH=ON somehow requires the CUDA include dir e.g.\n# \"/usr/local/cuda-13.0/targets/x86_64-linux/include\". I'll try to add that in\n# a future PR.\ninclude_dir = [\n get_python_include_dir(),\n os.path.join(NVFUSER_ROOT, \"third_party/pybind11/include\"),\n] + clang_search_dirs()\n\ninclude_args = [\"--extra-arg=-Wno-unknown-warning-option\"]\nfor dir in include_dir:\n include_args += [\"--extra-arg\", f\"-I{dir}\"]\n\n\ndef check_file(\n filename: str,\n binary: str,\n build_dir: Path,\n) -> List[LintMessage]:\n try:\n proc = run_command(\n [binary, f\"-p={build_dir}\", *include_args, filename],\n )\n except subprocess.CalledProcessError as err:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"CLANGTIDY\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err}\\n\\nstdout:\\n{err.stdout}\\nstderr:\\n{err.stderr}\"\n ),\n )\n ]\n lint_messages = []\n try:\n # Change the current working directory to the build directory, since\n # clang-tidy will report files relative to the build directory.\n saved_cwd = os.getcwd()\n os.chdir(build_dir)\n\n for match in RESULTS_RE.finditer(proc.stdout):\n # Convert the reported path to an absolute path.\n abs_path = str(Path(match[\"file\"]).resolve())\n message = LintMessage(\n path=abs_path,\n name=match[\"code\"],\n description=match[\"message\"],\n line=int(match[\"line\"]),\n char=int(match[\"column\"])\n if match[\"column\"] is not None and not match[\"column\"].startswith(\"-\")\n else None,\n code=\"CLANGTIDY\",\n severity=severities.get(match[\"severity\"], LintSeverity.ERROR),\n original=None,\n replacement=None,\n )\n lint_messages.append(message)\n finally:\n os.chdir(saved_cwd)\n\n return lint_messages\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"clang-tidy wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--build-dir\",\n \"--build_dir\",\n required=True,\n help=(\n \"Where the compile_commands.json file is located. \"\n \"Gets passed to clang-tidy -p\"\n ),\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangtidy_linter.main","uri":"program://Fuser/function/tools.linter.adapters.clangtidy_linter.main#L201-L293","kind":"function","name":"main","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":201,"end_line":293,"context_start_line":181,"context_end_line":297,"code":" message = LintMessage(\n path=abs_path,\n name=match[\"code\"],\n description=match[\"message\"],\n line=int(match[\"line\"]),\n char=int(match[\"column\"])\n if match[\"column\"] is not None and not match[\"column\"].startswith(\"-\")\n else None,\n code=\"CLANGTIDY\",\n severity=severities.get(match[\"severity\"], LintSeverity.ERROR),\n original=None,\n replacement=None,\n )\n lint_messages.append(message)\n finally:\n os.chdir(saved_cwd)\n\n return lint_messages\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"clang-tidy wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--build-dir\",\n \"--build_dir\",\n required=True,\n help=(\n \"Where the compile_commands.json file is located. \"\n \"Gets passed to clang-tidy -p\"\n ),\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n try:\n llvm_bindir = subprocess.check_output(\n [\"llvm-config\", \"--bindir\"], text=True\n ).strip()\n except FileNotFoundError:\n err_msg = LintMessage(\n path=\"\",\n line=None,\n char=None,\n code=\"CLANGTIDY\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=\"llvm-config doesn't exist (is LLVM installed?).\",\n )\n print(json.dumps(err_msg._asdict()), flush=True)\n exit(0)\n\n binary_path = os.path.join(llvm_bindir, \"clang-tidy\")\n if not os.path.exists(binary_path):\n err_msg = LintMessage(\n path=\"\",\n line=None,\n char=None,\n code=\"CLANGTIDY\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=f\"Could not find clang-tidy binary at {binary_path} (is LLVM installed?)\",\n )\n print(json.dumps(err_msg._asdict()), flush=True)\n exit(0)\n\n abs_build_dir = Path(args.build_dir).resolve()\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=os.cpu_count(),\n thread_name_prefix=\"Thread\",\n ) as executor:\n futures = {\n executor.submit(\n check_file,\n filename,\n binary_path,\n abs_build_dir,\n ): filename\n for filename in args.filenames\n }\n for future in concurrent.futures.as_completed(futures):\n try:\n for lint_message in future.result():\n print(json.dumps(lint_message._asdict()), flush=True)\n except Exception:\n logging.critical('Failed at \"%s\".', futures[future])\n raise\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangformat_linter","uri":"program://Fuser/module/tools.linter.adapters.clangformat_linter#L1-L255","kind":"module","name":"tools.linter.adapters.clangformat_linter","path":"tools/linter/adapters/clangformat_linter.py","language":"python","start_line":1,"end_line":255,"context_start_line":1,"context_end_line":255,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, List, NamedTuple, Optional\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef _run_command(\n args: List[str],\n *,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n capture_output=True,\n timeout=timeout,\n check=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef run_command(\n args: List[str],\n *,\n retries: int,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, timeout=timeout)\n except subprocess.TimeoutExpired as err:\n if remaining_retries == 0:\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,\n err,\n )\n time.sleep(1)\n\n\ndef check_file(\n filename: str,\n binary: str,\n retries: int,\n timeout: int,\n) -> List[LintMessage]:\n try:\n with open(filename, \"rb\") as f:\n original = f.read()\n proc = run_command(\n [binary, filename],\n retries=retries,\n timeout=timeout,\n )\n except subprocess.TimeoutExpired:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.ERROR,\n name=\"timeout\",\n original=None,\n replacement=None,\n description=(\n \"clang-format timed out while trying to process a file. \"\n \"Please report an issue in pytorch/pytorch with the \"\n \"label 'module: lint'\"\n ),\n )\n ]\n except (OSError, subprocess.CalledProcessError) as err:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.ADVICE,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(err.cmd),\n stderr=err.stderr.decode(\"utf-8\").strip() or \"(empty)\",\n stdout=err.stdout.decode(\"utf-8\").strip() or \"(empty)\",\n )\n ),\n )\n ]\n\n replacement = proc.stdout\n if original == replacement:\n return []\n\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.WARNING,\n name=\"format\",\n original=original.decode(\"utf-8\"),\n replacement=replacement.decode(\"utf-8\"),\n description=\"See https://clang.llvm.org/docs/ClangFormat.html.\\nRun `lintrunner -a` to apply this patch.\",\n )\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Format files with clang-format.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out clang-format\",\n )\n parser.add_argument(\n \"--timeout\",\n default=90,\n type=int,\n help=\"seconds to wait for clang-format\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=(\n logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO\n ),\n stream=sys.stderr,\n )\n\n try:\n llvm_bindir = subprocess.check_output(\n [\"llvm-config\", \"--bindir\"], text=True\n ).strip()\n except FileNotFoundError:\n lint_message = LintMessage(\n path=None,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.ERROR,\n name=\"init-error\",\n original=None,\n replacement=None,\n description=\"llvm-config doesn't exist (is LLVM installed?).\",\n )\n print(json.dumps(lint_message._asdict()), flush=True)\n sys.exit(0)\n\n binary = os.path.join(llvm_bindir, \"clang-format\")\n if not Path(binary).exists():\n lint_message = LintMessage(\n path=None,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.ERROR,\n name=\"init-error\",\n original=None,\n replacement=None,\n description=(\n f\"Could not find clang-format binary at {binary} (is LLVM installed?)\",\n ),\n )\n print(json.dumps(lint_message._asdict()), flush=True)\n sys.exit(0)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=os.cpu_count(),\n thread_name_prefix=\"Thread\",\n ) as executor:\n futures = {\n executor.submit(check_file, x, binary, args.retries, args.timeout): x\n for x in args.filenames\n }\n for future in concurrent.futures.as_completed(futures):\n try:\n for lint_message in future.result():\n print(json.dumps(lint_message._asdict()), flush=True)\n except Exception:\n logging.critical('Failed at \"%s\".', futures[future])\n raise\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"ab7a752d0c1a1bbc7c9d82a565f3e7d162264f94767eaf61c434b7b41372ea7c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangformat_linter.eprint","uri":"program://Fuser/function/tools.linter.adapters.clangformat_linter.eprint#L14-L15","kind":"function","name":"eprint","path":"tools/linter/adapters/clangformat_linter.py","language":"python","start_line":14,"end_line":15,"context_start_line":1,"context_end_line":35,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, List, NamedTuple, Optional\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n","source_hash":"ab7a752d0c1a1bbc7c9d82a565f3e7d162264f94767eaf61c434b7b41372ea7c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangformat_linter.LintSeverity","uri":"program://Fuser/class/tools.linter.adapters.clangformat_linter.LintSeverity#L18-L22","kind":"class","name":"LintSeverity","path":"tools/linter/adapters/clangformat_linter.py","language":"python","start_line":18,"end_line":22,"context_start_line":1,"context_end_line":42,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, List, NamedTuple, Optional\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef _run_command(\n args: List[str],\n *,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))","source_hash":"ab7a752d0c1a1bbc7c9d82a565f3e7d162264f94767eaf61c434b7b41372ea7c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangformat_linter.LintMessage","uri":"program://Fuser/class/tools.linter.adapters.clangformat_linter.LintMessage#L25-L34","kind":"class","name":"LintMessage","path":"tools/linter/adapters/clangformat_linter.py","language":"python","start_line":25,"end_line":34,"context_start_line":5,"context_end_line":54,"code":"import os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, List, NamedTuple, Optional\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef _run_command(\n args: List[str],\n *,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n capture_output=True,\n timeout=timeout,\n check=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n","source_hash":"ab7a752d0c1a1bbc7c9d82a565f3e7d162264f94767eaf61c434b7b41372ea7c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangformat_linter._run_command","uri":"program://Fuser/function/tools.linter.adapters.clangformat_linter._run_command#L37-L53","kind":"function","name":"_run_command","path":"tools/linter/adapters/clangformat_linter.py","language":"python","start_line":37,"end_line":53,"context_start_line":17,"context_end_line":73,"code":"\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef _run_command(\n args: List[str],\n *,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n capture_output=True,\n timeout=timeout,\n check=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef run_command(\n args: List[str],\n *,\n retries: int,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, timeout=timeout)\n except subprocess.TimeoutExpired as err:\n if remaining_retries == 0:\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,","source_hash":"ab7a752d0c1a1bbc7c9d82a565f3e7d162264f94767eaf61c434b7b41372ea7c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangformat_linter.run_command","uri":"program://Fuser/function/tools.linter.adapters.clangformat_linter.run_command#L56-L76","kind":"function","name":"run_command","path":"tools/linter/adapters/clangformat_linter.py","language":"python","start_line":56,"end_line":76,"context_start_line":36,"context_end_line":96,"code":"\ndef _run_command(\n args: List[str],\n *,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n capture_output=True,\n timeout=timeout,\n check=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef run_command(\n args: List[str],\n *,\n retries: int,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, timeout=timeout)\n except subprocess.TimeoutExpired as err:\n if remaining_retries == 0:\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,\n err,\n )\n time.sleep(1)\n\n\ndef check_file(\n filename: str,\n binary: str,\n retries: int,\n timeout: int,\n) -> List[LintMessage]:\n try:\n with open(filename, \"rb\") as f:\n original = f.read()\n proc = run_command(\n [binary, filename],\n retries=retries,\n timeout=timeout,\n )\n except subprocess.TimeoutExpired:\n return [\n LintMessage(\n path=filename,","source_hash":"ab7a752d0c1a1bbc7c9d82a565f3e7d162264f94767eaf61c434b7b41372ea7c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangformat_linter.check_file","uri":"program://Fuser/function/tools.linter.adapters.clangformat_linter.check_file#L79-L156","kind":"function","name":"check_file","path":"tools/linter/adapters/clangformat_linter.py","language":"python","start_line":79,"end_line":156,"context_start_line":59,"context_end_line":176,"code":" retries: int,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, timeout=timeout)\n except subprocess.TimeoutExpired as err:\n if remaining_retries == 0:\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,\n err,\n )\n time.sleep(1)\n\n\ndef check_file(\n filename: str,\n binary: str,\n retries: int,\n timeout: int,\n) -> List[LintMessage]:\n try:\n with open(filename, \"rb\") as f:\n original = f.read()\n proc = run_command(\n [binary, filename],\n retries=retries,\n timeout=timeout,\n )\n except subprocess.TimeoutExpired:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.ERROR,\n name=\"timeout\",\n original=None,\n replacement=None,\n description=(\n \"clang-format timed out while trying to process a file. \"\n \"Please report an issue in pytorch/pytorch with the \"\n \"label 'module: lint'\"\n ),\n )\n ]\n except (OSError, subprocess.CalledProcessError) as err:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.ADVICE,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(err.cmd),\n stderr=err.stderr.decode(\"utf-8\").strip() or \"(empty)\",\n stdout=err.stdout.decode(\"utf-8\").strip() or \"(empty)\",\n )\n ),\n )\n ]\n\n replacement = proc.stdout\n if original == replacement:\n return []\n\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.WARNING,\n name=\"format\",\n original=original.decode(\"utf-8\"),\n replacement=replacement.decode(\"utf-8\"),\n description=\"See https://clang.llvm.org/docs/ClangFormat.html.\\nRun `lintrunner -a` to apply this patch.\",\n )\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Format files with clang-format.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out clang-format\",\n )\n parser.add_argument(\n \"--timeout\",\n default=90,\n type=int,\n help=\"seconds to wait for clang-format\",\n )\n parser.add_argument(","source_hash":"ab7a752d0c1a1bbc7c9d82a565f3e7d162264f94767eaf61c434b7b41372ea7c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.clangformat_linter.main","uri":"program://Fuser/function/tools.linter.adapters.clangformat_linter.main#L159-L251","kind":"function","name":"main","path":"tools/linter/adapters/clangformat_linter.py","language":"python","start_line":159,"end_line":251,"context_start_line":139,"context_end_line":255,"code":"\n replacement = proc.stdout\n if original == replacement:\n return []\n\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.WARNING,\n name=\"format\",\n original=original.decode(\"utf-8\"),\n replacement=replacement.decode(\"utf-8\"),\n description=\"See https://clang.llvm.org/docs/ClangFormat.html.\\nRun `lintrunner -a` to apply this patch.\",\n )\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Format files with clang-format.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out clang-format\",\n )\n parser.add_argument(\n \"--timeout\",\n default=90,\n type=int,\n help=\"seconds to wait for clang-format\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=(\n logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO\n ),\n stream=sys.stderr,\n )\n\n try:\n llvm_bindir = subprocess.check_output(\n [\"llvm-config\", \"--bindir\"], text=True\n ).strip()\n except FileNotFoundError:\n lint_message = LintMessage(\n path=None,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.ERROR,\n name=\"init-error\",\n original=None,\n replacement=None,\n description=\"llvm-config doesn't exist (is LLVM installed?).\",\n )\n print(json.dumps(lint_message._asdict()), flush=True)\n sys.exit(0)\n\n binary = os.path.join(llvm_bindir, \"clang-format\")\n if not Path(binary).exists():\n lint_message = LintMessage(\n path=None,\n line=None,\n char=None,\n code=\"CLANGFORMAT\",\n severity=LintSeverity.ERROR,\n name=\"init-error\",\n original=None,\n replacement=None,\n description=(\n f\"Could not find clang-format binary at {binary} (is LLVM installed?)\",\n ),\n )\n print(json.dumps(lint_message._asdict()), flush=True)\n sys.exit(0)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=os.cpu_count(),\n thread_name_prefix=\"Thread\",\n ) as executor:\n futures = {\n executor.submit(check_file, x, binary, args.retries, args.timeout): x\n for x in args.filenames\n }\n for future in concurrent.futures.as_completed(futures):\n try:\n for lint_message in future.result():\n print(json.dumps(lint_message._asdict()), flush=True)\n except Exception:\n logging.critical('Failed at \"%s\".', futures[future])\n raise\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"ab7a752d0c1a1bbc7c9d82a565f3e7d162264f94767eaf61c434b7b41372ea7c","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.mypy_linter","uri":"program://Fuser/module/tools.linter.adapters.mypy_linter#L1-L191","kind":"module","name":"tools.linter.adapters.mypy_linter","path":"tools/linter/adapters/mypy_linter.py","language":"python","start_line":1,"end_line":191,"context_start_line":1,"context_end_line":191,"code":"import argparse\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, Dict, List, NamedTuple, Optional, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# tools/linter/flake8_linter.py:15:13: error: Incompatibl...int\") [assignment]\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n \\s(?P\\[.*\\])\n $\n \"\"\"\n)\n\n\ndef run_command(\n args: List[str],\n *,\n extra_env: Optional[Dict[str, str]],\n retries: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\n# Severity is either \"error\" or \"note\":\n# https://github.com/python/mypy/blob/8b47a032e1317fb8e3f9a818005a6b63e9bf0311/mypy/errors.py#L46-L47\nseverities = {\n \"error\": LintSeverity.ERROR,\n \"note\": LintSeverity.ADVICE,\n}\n\n\ndef check_files(\n filenames: List[str],\n config: str,\n retries: int,\n) -> List[LintMessage]:\n try:\n proc = run_command(\n [sys.executable, \"-mmypy\", f\"--config={config}\"] + filenames,\n extra_env={},\n retries=retries,\n )\n except OSError as err:\n return [\n LintMessage(\n path=None,\n line=None,\n char=None,\n code=\"MYPY\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(f\"Failed due to {err.__class__.__name__}:\\n{err}\"),\n )\n ]\n stdout = str(proc.stdout, \"utf-8\").strip()\n return [\n LintMessage(\n path=match[\"file\"],\n name=match[\"code\"],\n description=match[\"message\"],\n line=int(match[\"line\"]),\n char=int(match[\"column\"])\n if match[\"column\"] is not None and not match[\"column\"].startswith(\"-\")\n else None,\n code=\"MYPY\",\n severity=severities.get(match[\"severity\"], LintSeverity.ERROR),\n original=None,\n replacement=None,\n )\n for match in RESULTS_RE.finditer(stdout)\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"mypy wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out mypy\",\n )\n parser.add_argument(\n \"--config\",\n required=True,\n help=\"path to an mypy .ini config file\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n # Use a dictionary here to preserve order. mypy cares about order,\n # tragically, e.g. https://github.com/python/mypy/issues/2015\n filenames: Dict[str, bool] = {}\n\n # If a stub file exists, have mypy check it instead of the original file, in\n # accordance with PEP-484 (see https://www.python.org/dev/peps/pep-0484/#stub-files)\n for filename in args.filenames:\n if filename.endswith(\".pyi\"):\n filenames[filename] = True\n continue\n\n stub_filename = filename.replace(\".py\", \".pyi\")\n if Path(stub_filename).exists():\n filenames[stub_filename] = True\n else:\n filenames[filename] = True\n\n lint_messages = check_files(list(filenames), args.config, args.retries)\n for lint_message in lint_messages:\n print(json.dumps(lint_message._asdict()), flush=True)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"949699ebe60f63f110fdf4c2e95477b56344b65788b1f121d9d6ab2de29e95da","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.mypy_linter.eprint","uri":"program://Fuser/function/tools.linter.adapters.mypy_linter.eprint#L17-L18","kind":"function","name":"eprint","path":"tools/linter/adapters/mypy_linter.py","language":"python","start_line":17,"end_line":18,"context_start_line":1,"context_end_line":38,"code":"import argparse\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, Dict, List, NamedTuple, Optional, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n","source_hash":"949699ebe60f63f110fdf4c2e95477b56344b65788b1f121d9d6ab2de29e95da","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.mypy_linter.LintSeverity","uri":"program://Fuser/class/tools.linter.adapters.mypy_linter.LintSeverity#L21-L25","kind":"class","name":"LintSeverity","path":"tools/linter/adapters/mypy_linter.py","language":"python","start_line":21,"end_line":25,"context_start_line":1,"context_end_line":45,"code":"import argparse\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, Dict, List, NamedTuple, Optional, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# tools/linter/flake8_linter.py:15:13: error: Incompatibl...int\") [assignment]\nRESULTS_RE: Pattern[str] = re.compile(","source_hash":"949699ebe60f63f110fdf4c2e95477b56344b65788b1f121d9d6ab2de29e95da","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.mypy_linter.LintMessage","uri":"program://Fuser/class/tools.linter.adapters.mypy_linter.LintMessage#L28-L37","kind":"class","name":"LintMessage","path":"tools/linter/adapters/mypy_linter.py","language":"python","start_line":28,"end_line":37,"context_start_line":8,"context_end_line":57,"code":"import time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, Dict, List, NamedTuple, Optional, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# tools/linter/flake8_linter.py:15:13: error: Incompatibl...int\") [assignment]\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n \\s(?P\\[.*\\])\n $\n \"\"\"\n)\n","source_hash":"949699ebe60f63f110fdf4c2e95477b56344b65788b1f121d9d6ab2de29e95da","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.mypy_linter.as_posix","uri":"program://Fuser/function/tools.linter.adapters.mypy_linter.as_posix#L40-L41","kind":"function","name":"as_posix","path":"tools/linter/adapters/mypy_linter.py","language":"python","start_line":40,"end_line":41,"context_start_line":20,"context_end_line":61,"code":"\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# tools/linter/flake8_linter.py:15:13: error: Incompatibl...int\") [assignment]\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n \\s(?P\\[.*\\])\n $\n \"\"\"\n)\n\n\ndef run_command(\n args: List[str],\n *,","source_hash":"949699ebe60f63f110fdf4c2e95477b56344b65788b1f121d9d6ab2de29e95da","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.mypy_linter.run_command","uri":"program://Fuser/function/tools.linter.adapters.mypy_linter.run_command#L59-L75","kind":"function","name":"run_command","path":"tools/linter/adapters/mypy_linter.py","language":"python","start_line":59,"end_line":75,"context_start_line":39,"context_end_line":95,"code":"\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# tools/linter/flake8_linter.py:15:13: error: Incompatibl...int\") [assignment]\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n \\s(?P\\[.*\\])\n $\n \"\"\"\n)\n\n\ndef run_command(\n args: List[str],\n *,\n extra_env: Optional[Dict[str, str]],\n retries: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\n# Severity is either \"error\" or \"note\":\n# https://github.com/python/mypy/blob/8b47a032e1317fb8e3f9a818005a6b63e9bf0311/mypy/errors.py#L46-L47\nseverities = {\n \"error\": LintSeverity.ERROR,\n \"note\": LintSeverity.ADVICE,\n}\n\n\ndef check_files(\n filenames: List[str],\n config: str,\n retries: int,\n) -> List[LintMessage]:\n try:\n proc = run_command(\n [sys.executable, \"-mmypy\", f\"--config={config}\"] + filenames,\n extra_env={},\n retries=retries,","source_hash":"949699ebe60f63f110fdf4c2e95477b56344b65788b1f121d9d6ab2de29e95da","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.mypy_linter.check_files","uri":"program://Fuser/function/tools.linter.adapters.mypy_linter.check_files#L86-L127","kind":"function","name":"check_files","path":"tools/linter/adapters/mypy_linter.py","language":"python","start_line":86,"end_line":127,"context_start_line":66,"context_end_line":147,"code":" start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\n# Severity is either \"error\" or \"note\":\n# https://github.com/python/mypy/blob/8b47a032e1317fb8e3f9a818005a6b63e9bf0311/mypy/errors.py#L46-L47\nseverities = {\n \"error\": LintSeverity.ERROR,\n \"note\": LintSeverity.ADVICE,\n}\n\n\ndef check_files(\n filenames: List[str],\n config: str,\n retries: int,\n) -> List[LintMessage]:\n try:\n proc = run_command(\n [sys.executable, \"-mmypy\", f\"--config={config}\"] + filenames,\n extra_env={},\n retries=retries,\n )\n except OSError as err:\n return [\n LintMessage(\n path=None,\n line=None,\n char=None,\n code=\"MYPY\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(f\"Failed due to {err.__class__.__name__}:\\n{err}\"),\n )\n ]\n stdout = str(proc.stdout, \"utf-8\").strip()\n return [\n LintMessage(\n path=match[\"file\"],\n name=match[\"code\"],\n description=match[\"message\"],\n line=int(match[\"line\"]),\n char=int(match[\"column\"])\n if match[\"column\"] is not None and not match[\"column\"].startswith(\"-\")\n else None,\n code=\"MYPY\",\n severity=severities.get(match[\"severity\"], LintSeverity.ERROR),\n original=None,\n replacement=None,\n )\n for match in RESULTS_RE.finditer(stdout)\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"mypy wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out mypy\",\n )\n parser.add_argument(\n \"--config\",\n required=True,\n help=\"path to an mypy .ini config file\",\n )\n parser.add_argument(\n \"--verbose\",","source_hash":"949699ebe60f63f110fdf4c2e95477b56344b65788b1f121d9d6ab2de29e95da","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.mypy_linter.main","uri":"program://Fuser/function/tools.linter.adapters.mypy_linter.main#L130-L187","kind":"function","name":"main","path":"tools/linter/adapters/mypy_linter.py","language":"python","start_line":130,"end_line":187,"context_start_line":110,"context_end_line":191,"code":" ]\n stdout = str(proc.stdout, \"utf-8\").strip()\n return [\n LintMessage(\n path=match[\"file\"],\n name=match[\"code\"],\n description=match[\"message\"],\n line=int(match[\"line\"]),\n char=int(match[\"column\"])\n if match[\"column\"] is not None and not match[\"column\"].startswith(\"-\")\n else None,\n code=\"MYPY\",\n severity=severities.get(match[\"severity\"], LintSeverity.ERROR),\n original=None,\n replacement=None,\n )\n for match in RESULTS_RE.finditer(stdout)\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"mypy wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out mypy\",\n )\n parser.add_argument(\n \"--config\",\n required=True,\n help=\"path to an mypy .ini config file\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n # Use a dictionary here to preserve order. mypy cares about order,\n # tragically, e.g. https://github.com/python/mypy/issues/2015\n filenames: Dict[str, bool] = {}\n\n # If a stub file exists, have mypy check it instead of the original file, in\n # accordance with PEP-484 (see https://www.python.org/dev/peps/pep-0484/#stub-files)\n for filename in args.filenames:\n if filename.endswith(\".pyi\"):\n filenames[filename] = True\n continue\n\n stub_filename = filename.replace(\".py\", \".pyi\")\n if Path(stub_filename).exists():\n filenames[stub_filename] = True\n else:\n filenames[filename] = True\n\n lint_messages = check_files(list(filenames), args.config, args.retries)\n for lint_message in lint_messages:\n print(json.dumps(lint_message._asdict()), flush=True)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"949699ebe60f63f110fdf4c2e95477b56344b65788b1f121d9d6ab2de29e95da","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.black_linter","uri":"program://Fuser/module/tools.linter.adapters.black_linter#L1-L228","kind":"module","name":"tools.linter.adapters.black_linter","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":1,"end_line":228,"context_start_line":1,"context_end_line":228,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional, BinaryIO\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef _run_command(\n args: List[str],\n *,\n stdin: BinaryIO,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdin=stdin,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=IS_WINDOWS, # So batch scripts are found.\n timeout=timeout,\n check=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef run_command(\n args: List[str],\n *,\n stdin: BinaryIO,\n retries: int,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, stdin=stdin, timeout=timeout)\n except subprocess.TimeoutExpired as err:\n if remaining_retries == 0:\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,\n err,\n )\n time.sleep(1)\n\n\ndef check_file(\n filename: str,\n retries: int,\n timeout: int,\n) -> List[LintMessage]:\n try:\n with open(filename, \"rb\") as f:\n original = f.read()\n with open(filename, \"rb\") as f:\n proc = run_command(\n [sys.executable, \"-mblack\", \"--stdin-filename\", filename, \"-\"],\n stdin=f,\n retries=retries,\n timeout=timeout,\n )\n except subprocess.TimeoutExpired:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"BLACK\",\n severity=LintSeverity.ERROR,\n name=\"timeout\",\n original=None,\n replacement=None,\n description=(\n \"black timed out while trying to process a file. \"\n \"Please report an issue in pytorch/pytorch with the \"\n \"label 'module: lint'\"\n ),\n )\n ]\n except (OSError, subprocess.CalledProcessError) as err:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"BLACK\",\n severity=LintSeverity.ADVICE,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(as_posix(x) for x in err.cmd),\n stderr=err.stderr.decode(\"utf-8\").strip() or \"(empty)\",\n stdout=err.stdout.decode(\"utf-8\").strip() or \"(empty)\",\n )\n ),\n )\n ]\n\n replacement = proc.stdout\n if original == replacement:\n return []\n\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"BLACK\",\n severity=LintSeverity.WARNING,\n name=\"format\",\n original=original.decode(\"utf-8\"),\n replacement=replacement.decode(\"utf-8\"),\n description=\"Run `lintrunner -a` to apply this patch.\",\n )\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Format files with black.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out black\",\n )\n parser.add_argument(\n \"--timeout\",\n default=90,\n type=int,\n help=\"seconds to wait for black\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=os.cpu_count(),\n thread_name_prefix=\"Thread\",\n ) as executor:\n futures = {\n executor.submit(check_file, x, args.retries, args.timeout): x\n for x in args.filenames\n }\n for future in concurrent.futures.as_completed(futures):\n try:\n for lint_message in future.result():\n print(json.dumps(lint_message._asdict()), flush=True)\n except Exception:\n logging.critical('Failed at \"%s\".', futures[future])\n raise\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.black_linter.eprint","uri":"program://Fuser/function/tools.linter.adapters.black_linter.eprint#L16-L17","kind":"function","name":"eprint","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":16,"end_line":17,"context_start_line":1,"context_end_line":37,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional, BinaryIO\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.black_linter.LintSeverity","uri":"program://Fuser/class/tools.linter.adapters.black_linter.LintSeverity#L20-L24","kind":"class","name":"LintSeverity","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":20,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional, BinaryIO\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef _run_command(\n args: List[str],","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.black_linter.LintMessage","uri":"program://Fuser/class/tools.linter.adapters.black_linter.LintMessage#L27-L36","kind":"class","name":"LintMessage","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":27,"end_line":36,"context_start_line":7,"context_end_line":56,"code":"import sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional, BinaryIO\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef _run_command(\n args: List[str],\n *,\n stdin: BinaryIO,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdin=stdin,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.black_linter.as_posix","uri":"program://Fuser/function/tools.linter.adapters.black_linter.as_posix#L39-L40","kind":"function","name":"as_posix","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":39,"end_line":40,"context_start_line":19,"context_end_line":60,"code":"\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef _run_command(\n args: List[str],\n *,\n stdin: BinaryIO,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdin=stdin,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=IS_WINDOWS, # So batch scripts are found.\n timeout=timeout,\n check=True,\n )","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.black_linter._run_command","uri":"program://Fuser/function/tools.linter.adapters.black_linter._run_command#L43-L63","kind":"function","name":"_run_command","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":43,"end_line":63,"context_start_line":23,"context_end_line":83,"code":" ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef _run_command(\n args: List[str],\n *,\n stdin: BinaryIO,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdin=stdin,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=IS_WINDOWS, # So batch scripts are found.\n timeout=timeout,\n check=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef run_command(\n args: List[str],\n *,\n stdin: BinaryIO,\n retries: int,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, stdin=stdin, timeout=timeout)\n except subprocess.TimeoutExpired as err:\n if remaining_retries == 0:\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.black_linter.run_command","uri":"program://Fuser/function/tools.linter.adapters.black_linter.run_command#L66-L87","kind":"function","name":"run_command","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":66,"end_line":87,"context_start_line":46,"context_end_line":107,"code":" stdin: BinaryIO,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdin=stdin,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=IS_WINDOWS, # So batch scripts are found.\n timeout=timeout,\n check=True,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef run_command(\n args: List[str],\n *,\n stdin: BinaryIO,\n retries: int,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, stdin=stdin, timeout=timeout)\n except subprocess.TimeoutExpired as err:\n if remaining_retries == 0:\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,\n err,\n )\n time.sleep(1)\n\n\ndef check_file(\n filename: str,\n retries: int,\n timeout: int,\n) -> List[LintMessage]:\n try:\n with open(filename, \"rb\") as f:\n original = f.read()\n with open(filename, \"rb\") as f:\n proc = run_command(\n [sys.executable, \"-mblack\", \"--stdin-filename\", filename, \"-\"],\n stdin=f,\n retries=retries,\n timeout=timeout,\n )\n except subprocess.TimeoutExpired:\n return [\n LintMessage(","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.black_linter.check_file","uri":"program://Fuser/function/tools.linter.adapters.black_linter.check_file#L90-L168","kind":"function","name":"check_file","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":90,"end_line":168,"context_start_line":70,"context_end_line":188,"code":" retries: int,\n timeout: int,\n) -> \"subprocess.CompletedProcess[bytes]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, stdin=stdin, timeout=timeout)\n except subprocess.TimeoutExpired as err:\n if remaining_retries == 0:\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,\n err,\n )\n time.sleep(1)\n\n\ndef check_file(\n filename: str,\n retries: int,\n timeout: int,\n) -> List[LintMessage]:\n try:\n with open(filename, \"rb\") as f:\n original = f.read()\n with open(filename, \"rb\") as f:\n proc = run_command(\n [sys.executable, \"-mblack\", \"--stdin-filename\", filename, \"-\"],\n stdin=f,\n retries=retries,\n timeout=timeout,\n )\n except subprocess.TimeoutExpired:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"BLACK\",\n severity=LintSeverity.ERROR,\n name=\"timeout\",\n original=None,\n replacement=None,\n description=(\n \"black timed out while trying to process a file. \"\n \"Please report an issue in pytorch/pytorch with the \"\n \"label 'module: lint'\"\n ),\n )\n ]\n except (OSError, subprocess.CalledProcessError) as err:\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"BLACK\",\n severity=LintSeverity.ADVICE,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(as_posix(x) for x in err.cmd),\n stderr=err.stderr.decode(\"utf-8\").strip() or \"(empty)\",\n stdout=err.stdout.decode(\"utf-8\").strip() or \"(empty)\",\n )\n ),\n )\n ]\n\n replacement = proc.stdout\n if original == replacement:\n return []\n\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"BLACK\",\n severity=LintSeverity.WARNING,\n name=\"format\",\n original=original.decode(\"utf-8\"),\n replacement=replacement.decode(\"utf-8\"),\n description=\"Run `lintrunner -a` to apply this patch.\",\n )\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Format files with black.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out black\",\n )\n parser.add_argument(\n \"--timeout\",\n default=90,\n type=int,\n help=\"seconds to wait for black\",\n )\n parser.add_argument(","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.black_linter.main","uri":"program://Fuser/function/tools.linter.adapters.black_linter.main#L171-L224","kind":"function","name":"main","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":171,"end_line":224,"context_start_line":151,"context_end_line":228,"code":"\n replacement = proc.stdout\n if original == replacement:\n return []\n\n return [\n LintMessage(\n path=filename,\n line=None,\n char=None,\n code=\"BLACK\",\n severity=LintSeverity.WARNING,\n name=\"format\",\n original=original.decode(\"utf-8\"),\n replacement=replacement.decode(\"utf-8\"),\n description=\"Run `lintrunner -a` to apply this patch.\",\n )\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Format files with black.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out black\",\n )\n parser.add_argument(\n \"--timeout\",\n default=90,\n type=int,\n help=\"seconds to wait for black\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=os.cpu_count(),\n thread_name_prefix=\"Thread\",\n ) as executor:\n futures = {\n executor.submit(check_file, x, args.retries, args.timeout): x\n for x in args.filenames\n }\n for future in concurrent.futures.as_completed(futures):\n try:\n for lint_message in future.result():\n print(json.dumps(lint_message._asdict()), flush=True)\n except Exception:\n logging.critical('Failed at \"%s\".', futures[future])\n raise\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.grep_linter","uri":"program://Fuser/module/tools.linter.adapters.grep_linter#L1-L221","kind":"module","name":"tools.linter.adapters.grep_linter","path":"tools/linter/adapters/grep_linter.py","language":"python","start_line":1,"end_line":221,"context_start_line":1,"context_end_line":221,"code":"\"\"\"\nGeneric linter that greps for a pattern and optionally suggests replacements.\n\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef run_command(\n args: List[str],\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef lint_file(\n matching_line: str,\n replace_pattern: str,\n linter_name: str,\n error_name: str,\n error_description: str,\n) -> LintMessage:\n # matching_line looks like:\n # tools/linter/clangtidy_linter.py:13:import foo.bar.baz\n split = matching_line.split(\":\")\n filename = split[0]\n\n original = None\n replacement = None\n if replace_pattern:\n with open(filename, \"r\") as f:\n original = f.read()\n\n try:\n proc = run_command([\"sed\", \"-r\", replace_pattern, filename])\n replacement = proc.stdout.decode(\"utf-8\")\n except Exception as err:\n return LintMessage(\n path=None,\n line=None,\n char=None,\n code=linter_name,\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(as_posix(x) for x in err.cmd),\n stderr=err.stderr.decode(\"utf-8\").strip() or \"(empty)\",\n stdout=err.stdout.decode(\"utf-8\").strip() or \"(empty)\",\n )\n ),\n )\n\n return LintMessage(\n path=split[0],\n line=int(split[1]),\n char=None,\n code=linter_name,\n severity=LintSeverity.ERROR,\n name=error_name,\n original=original,\n replacement=replacement,\n description=error_description,\n )\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"grep wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--pattern\",\n required=True,\n help=\"pattern to grep for\",\n )\n parser.add_argument(\n \"--linter-name\",\n required=True,\n help=\"name of the linter\",\n )\n parser.add_argument(\n \"--error-name\",\n required=True,\n help=\"human-readable description of what the error is\",\n )\n parser.add_argument(\n \"--error-description\",\n required=True,\n help=\"message to display when the pattern is found\",\n )\n parser.add_argument(\n \"--replace-pattern\",\n help=(\n \"the form of a pattern passed to `sed -r`. \"\n \"If specified, this will become proposed replacement text.\"\n ),\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n try:\n proc = run_command([\"grep\", \"-nEHI\", args.pattern, *args.filenames])\n except Exception as err:\n err_msg = LintMessage(\n path=None,\n line=None,\n char=None,\n code=args.linter_name,\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(as_posix(x) for x in err.cmd),\n stderr=err.stderr.decode(\"utf-8\").strip() or \"(empty)\",\n stdout=err.stdout.decode(\"utf-8\").strip() or \"(empty)\",\n )\n ),\n )\n print(json.dumps(err_msg._asdict()), flush=True)\n exit(0)\n\n lines = proc.stdout.decode().splitlines()\n for line in lines:\n lint_message = lint_file(\n line,\n args.replace_pattern,\n args.linter_name,\n args.error_name,\n args.error_description,\n )\n print(json.dumps(lint_message._asdict()), flush=True)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"b3f127c19e71d2af5a0daeb196969f74280a12ff7a669b425d92640865d1fc54","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.grep_linter.eprint","uri":"program://Fuser/function/tools.linter.adapters.grep_linter.eprint#L19-L20","kind":"function","name":"eprint","path":"tools/linter/adapters/grep_linter.py","language":"python","start_line":19,"end_line":20,"context_start_line":1,"context_end_line":40,"code":"\"\"\"\nGeneric linter that greps for a pattern and optionally suggests replacements.\n\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n","source_hash":"b3f127c19e71d2af5a0daeb196969f74280a12ff7a669b425d92640865d1fc54","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.grep_linter.LintSeverity","uri":"program://Fuser/class/tools.linter.adapters.grep_linter.LintSeverity#L23-L27","kind":"class","name":"LintSeverity","path":"tools/linter/adapters/grep_linter.py","language":"python","start_line":23,"end_line":27,"context_start_line":3,"context_end_line":47,"code":"\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef run_command(\n args: List[str],","source_hash":"b3f127c19e71d2af5a0daeb196969f74280a12ff7a669b425d92640865d1fc54","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.grep_linter.LintMessage","uri":"program://Fuser/class/tools.linter.adapters.grep_linter.LintMessage#L30-L39","kind":"class","name":"LintMessage","path":"tools/linter/adapters/grep_linter.py","language":"python","start_line":30,"end_line":39,"context_start_line":10,"context_end_line":59,"code":"import sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef run_command(\n args: List[str],\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)","source_hash":"b3f127c19e71d2af5a0daeb196969f74280a12ff7a669b425d92640865d1fc54","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.grep_linter.as_posix","uri":"program://Fuser/function/tools.linter.adapters.grep_linter.as_posix#L42-L43","kind":"function","name":"as_posix","path":"tools/linter/adapters/grep_linter.py","language":"python","start_line":42,"end_line":43,"context_start_line":22,"context_end_line":63,"code":"\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef run_command(\n args: List[str],\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef lint_file(\n matching_line: str,","source_hash":"b3f127c19e71d2af5a0daeb196969f74280a12ff7a669b425d92640865d1fc54","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.grep_linter.run_command","uri":"program://Fuser/function/tools.linter.adapters.grep_linter.run_command#L46-L59","kind":"function","name":"run_command","path":"tools/linter/adapters/grep_linter.py","language":"python","start_line":46,"end_line":59,"context_start_line":26,"context_end_line":79,"code":" ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef run_command(\n args: List[str],\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef lint_file(\n matching_line: str,\n replace_pattern: str,\n linter_name: str,\n error_name: str,\n error_description: str,\n) -> LintMessage:\n # matching_line looks like:\n # tools/linter/clangtidy_linter.py:13:import foo.bar.baz\n split = matching_line.split(\":\")\n filename = split[0]\n\n original = None\n replacement = None\n if replace_pattern:\n with open(filename, \"r\") as f:\n original = f.read()\n","source_hash":"b3f127c19e71d2af5a0daeb196969f74280a12ff7a669b425d92640865d1fc54","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.grep_linter.lint_file","uri":"program://Fuser/function/tools.linter.adapters.grep_linter.lint_file#L62-L120","kind":"function","name":"lint_file","path":"tools/linter/adapters/grep_linter.py","language":"python","start_line":62,"end_line":120,"context_start_line":42,"context_end_line":140,"code":"def as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\ndef run_command(\n args: List[str],\n) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef lint_file(\n matching_line: str,\n replace_pattern: str,\n linter_name: str,\n error_name: str,\n error_description: str,\n) -> LintMessage:\n # matching_line looks like:\n # tools/linter/clangtidy_linter.py:13:import foo.bar.baz\n split = matching_line.split(\":\")\n filename = split[0]\n\n original = None\n replacement = None\n if replace_pattern:\n with open(filename, \"r\") as f:\n original = f.read()\n\n try:\n proc = run_command([\"sed\", \"-r\", replace_pattern, filename])\n replacement = proc.stdout.decode(\"utf-8\")\n except Exception as err:\n return LintMessage(\n path=None,\n line=None,\n char=None,\n code=linter_name,\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(as_posix(x) for x in err.cmd),\n stderr=err.stderr.decode(\"utf-8\").strip() or \"(empty)\",\n stdout=err.stdout.decode(\"utf-8\").strip() or \"(empty)\",\n )\n ),\n )\n\n return LintMessage(\n path=split[0],\n line=int(split[1]),\n char=None,\n code=linter_name,\n severity=LintSeverity.ERROR,\n name=error_name,\n original=original,\n replacement=replacement,\n description=error_description,\n )\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"grep wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--pattern\",\n required=True,\n help=\"pattern to grep for\",\n )\n parser.add_argument(\n \"--linter-name\",\n required=True,\n help=\"name of the linter\",\n )\n parser.add_argument(\n \"--error-name\",\n required=True,","source_hash":"b3f127c19e71d2af5a0daeb196969f74280a12ff7a669b425d92640865d1fc54","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.grep_linter.main","uri":"program://Fuser/function/tools.linter.adapters.grep_linter.main#L123-L217","kind":"function","name":"main","path":"tools/linter/adapters/grep_linter.py","language":"python","start_line":123,"end_line":217,"context_start_line":103,"context_end_line":221,"code":" command=\" \".join(as_posix(x) for x in err.cmd),\n stderr=err.stderr.decode(\"utf-8\").strip() or \"(empty)\",\n stdout=err.stdout.decode(\"utf-8\").strip() or \"(empty)\",\n )\n ),\n )\n\n return LintMessage(\n path=split[0],\n line=int(split[1]),\n char=None,\n code=linter_name,\n severity=LintSeverity.ERROR,\n name=error_name,\n original=original,\n replacement=replacement,\n description=error_description,\n )\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"grep wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--pattern\",\n required=True,\n help=\"pattern to grep for\",\n )\n parser.add_argument(\n \"--linter-name\",\n required=True,\n help=\"name of the linter\",\n )\n parser.add_argument(\n \"--error-name\",\n required=True,\n help=\"human-readable description of what the error is\",\n )\n parser.add_argument(\n \"--error-description\",\n required=True,\n help=\"message to display when the pattern is found\",\n )\n parser.add_argument(\n \"--replace-pattern\",\n help=(\n \"the form of a pattern passed to `sed -r`. \"\n \"If specified, this will become proposed replacement text.\"\n ),\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n try:\n proc = run_command([\"grep\", \"-nEHI\", args.pattern, *args.filenames])\n except Exception as err:\n err_msg = LintMessage(\n path=None,\n line=None,\n char=None,\n code=args.linter_name,\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(as_posix(x) for x in err.cmd),\n stderr=err.stderr.decode(\"utf-8\").strip() or \"(empty)\",\n stdout=err.stdout.decode(\"utf-8\").strip() or \"(empty)\",\n )\n ),\n )\n print(json.dumps(err_msg._asdict()), flush=True)\n exit(0)\n\n lines = proc.stdout.decode().splitlines()\n for line in lines:\n lint_message = lint_file(\n line,\n args.replace_pattern,\n args.linter_name,\n args.error_name,\n args.error_description,\n )\n print(json.dumps(lint_message._asdict()), flush=True)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"b3f127c19e71d2af5a0daeb196969f74280a12ff7a669b425d92640865d1fc54","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.exec_linter","uri":"program://Fuser/module/tools.linter.adapters.exec_linter#L1-L86","kind":"module","name":"tools.linter.adapters.exec_linter","path":"tools/linter/adapters/exec_linter.py","language":"python","start_line":1,"end_line":86,"context_start_line":1,"context_end_line":86,"code":"\"\"\"\nEXEC: Ensure that source files are not executable.\n\"\"\"\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\n\nfrom enum import Enum\nfrom typing import NamedTuple, Optional\n\nLINTER_CODE = \"EXEC\"\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef check_file(filename: str) -> Optional[LintMessage]:\n is_executable = os.access(filename, os.X_OK)\n if is_executable:\n return LintMessage(\n path=filename,\n line=None,\n char=None,\n code=LINTER_CODE,\n severity=LintSeverity.ERROR,\n name=\"executable-permissions\",\n original=None,\n replacement=None,\n description=\"This file has executable permission; please remove it by using `chmod -x`.\",\n )\n return None\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"exec linter\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n lint_messages = []\n for filename in args.filenames:\n lint_message = check_file(filename)\n if lint_message is not None:\n lint_messages.append(lint_message)\n\n for lint_message in lint_messages:\n print(json.dumps(lint_message._asdict()), flush=True)","source_hash":"5907352556cf51f7acca69c1855941ed922cedd510e7bc5021f5d937b3b56de7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.exec_linter.LintSeverity","uri":"program://Fuser/class/tools.linter.adapters.exec_linter.LintSeverity#L16-L20","kind":"class","name":"LintSeverity","path":"tools/linter/adapters/exec_linter.py","language":"python","start_line":16,"end_line":20,"context_start_line":1,"context_end_line":40,"code":"\"\"\"\nEXEC: Ensure that source files are not executable.\n\"\"\"\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\n\nfrom enum import Enum\nfrom typing import NamedTuple, Optional\n\nLINTER_CODE = \"EXEC\"\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef check_file(filename: str) -> Optional[LintMessage]:\n is_executable = os.access(filename, os.X_OK)\n if is_executable:\n return LintMessage(\n path=filename,\n line=None,","source_hash":"5907352556cf51f7acca69c1855941ed922cedd510e7bc5021f5d937b3b56de7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.exec_linter.LintMessage","uri":"program://Fuser/class/tools.linter.adapters.exec_linter.LintMessage#L23-L32","kind":"class","name":"LintMessage","path":"tools/linter/adapters/exec_linter.py","language":"python","start_line":23,"end_line":32,"context_start_line":3,"context_end_line":52,"code":"\"\"\"\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\n\nfrom enum import Enum\nfrom typing import NamedTuple, Optional\n\nLINTER_CODE = \"EXEC\"\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef check_file(filename: str) -> Optional[LintMessage]:\n is_executable = os.access(filename, os.X_OK)\n if is_executable:\n return LintMessage(\n path=filename,\n line=None,\n char=None,\n code=LINTER_CODE,\n severity=LintSeverity.ERROR,\n name=\"executable-permissions\",\n original=None,\n replacement=None,\n description=\"This file has executable permission; please remove it by using `chmod -x`.\",\n )\n return None\n\n\nif __name__ == \"__main__\":","source_hash":"5907352556cf51f7acca69c1855941ed922cedd510e7bc5021f5d937b3b56de7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.exec_linter.check_file","uri":"program://Fuser/function/tools.linter.adapters.exec_linter.check_file#L35-L49","kind":"function","name":"check_file","path":"tools/linter/adapters/exec_linter.py","language":"python","start_line":35,"end_line":49,"context_start_line":15,"context_end_line":69,"code":"\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef check_file(filename: str) -> Optional[LintMessage]:\n is_executable = os.access(filename, os.X_OK)\n if is_executable:\n return LintMessage(\n path=filename,\n line=None,\n char=None,\n code=LINTER_CODE,\n severity=LintSeverity.ERROR,\n name=\"executable-permissions\",\n original=None,\n replacement=None,\n description=\"This file has executable permission; please remove it by using `chmod -x`.\",\n )\n return None\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"exec linter\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n\n args = parser.parse_args()\n\n logging.basicConfig(","source_hash":"5907352556cf51f7acca69c1855941ed922cedd510e7bc5021f5d937b3b56de7","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.pip_init","uri":"program://Fuser/module/tools.linter.adapters.pip_init#L1-L83","kind":"module","name":"tools.linter.adapters.pip_init","path":"tools/linter/adapters/pip_init.py","language":"python","start_line":1,"end_line":83,"context_start_line":1,"context_end_line":83,"code":"\"\"\"\nInitializer script that installs stuff to pip.\n\"\"\"\nimport os\nimport argparse\nimport logging\nimport subprocess\nimport sys\nimport time\n\nfrom typing import List\n\n\ndef run_command(args: List[str]) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(args, check=True)\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"pip initializer\")\n parser.add_argument(\n \"packages\",\n nargs=\"+\",\n help=\"pip packages to install\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"--dry-run\", help=\"do not install anything, just print what would be done.\"\n )\n parser.add_argument(\n \"--no-binary\",\n help=\"do not use pre-compiled binaries from pip.\",\n action=\"store_true\",\n )\n\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET if args.verbose else logging.DEBUG,\n stream=sys.stderr,\n )\n\n pip_args = [\"pip3\", \"install\"]\n\n # If we are in a global install, use `--user` to install so that you do not\n # need root access in order to initialize linters.\n #\n # However, `pip install --user` interacts poorly with virtualenvs (see:\n # https://bit.ly/3vD4kvl) and conda (see: https://bit.ly/3KG7ZfU). So in\n # these cases perform a regular installation.\n in_conda = os.environ.get(\"CONDA_PREFIX\") is not None\n in_virtualenv = os.environ.get(\"VIRTUAL_ENV\") is not None\n if not in_conda and not in_virtualenv:\n pip_args.append(\"--user\")\n\n pip_args.extend(args.packages)\n\n for package in args.packages:\n package_name, _, version = package.partition(\"=\")\n if version == \"\":\n raise RuntimeError(\n \"Package {package_name} did not have a version specified. \"\n \"Please specify a version to produce a consistent linting experience.\"\n )\n if args.no_binary:\n pip_args.append(f\"--no-binary={package_name}\")\n\n dry_run = args.dry_run == \"1\"\n if dry_run:\n print(f\"Would have run: {pip_args}\")\n sys.exit(0)\n\n run_command(pip_args)","source_hash":"3c98724f8b55f84bb7c05e2b64aa8bc8a00a0c2a65b25540406421ec3a85138a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.pip_init.run_command","uri":"program://Fuser/function/tools.linter.adapters.pip_init.run_command#L14-L21","kind":"function","name":"run_command","path":"tools/linter/adapters/pip_init.py","language":"python","start_line":14,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"\"\"\"\nInitializer script that installs stuff to pip.\n\"\"\"\nimport os\nimport argparse\nimport logging\nimport subprocess\nimport sys\nimport time\n\nfrom typing import List\n\n\ndef run_command(args: List[str]) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(args, check=True)\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"pip initializer\")\n parser.add_argument(\n \"packages\",\n nargs=\"+\",\n help=\"pip packages to install\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"--dry-run\", help=\"do not install anything, just print what would be done.\"\n )\n parser.add_argument(\n \"--no-binary\",\n help=\"do not use pre-compiled binaries from pip.\",","source_hash":"3c98724f8b55f84bb7c05e2b64aa8bc8a00a0c2a65b25540406421ec3a85138a","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter","uri":"program://Fuser/module/tools.linter.adapters.flake8_linter#L1-L373","kind":"module","name":"tools.linter.adapters.flake8_linter","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":1,"end_line":373,"context_start_line":1,"context_end_line":373,"code":"import argparse\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, Dict, List, NamedTuple, Optional, Set, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# fmt: off\n# https://www.flake8rules.com/\nDOCUMENTED_IN_FLAKE8RULES: Set[str] = {\n \"E101\", \"E111\", \"E112\", \"E113\", \"E114\", \"E115\", \"E116\", \"E117\",\n \"E121\", \"E122\", \"E123\", \"E124\", \"E125\", \"E126\", \"E127\", \"E128\", \"E129\",\n \"E131\", \"E133\",\n \"E201\", \"E202\", \"E203\",\n \"E211\",\n \"E221\", \"E222\", \"E223\", \"E224\", \"E225\", \"E226\", \"E227\", \"E228\",\n \"E231\",\n \"E241\", \"E242\",\n \"E251\",\n \"E261\", \"E262\", \"E265\", \"E266\",\n \"E271\", \"E272\", \"E273\", \"E274\", \"E275\",\n \"E301\", \"E302\", \"E303\", \"E304\", \"E305\", \"E306\",\n \"E401\", \"E402\",\n \"E501\", \"E502\",\n \"E701\", \"E702\", \"E703\", \"E704\",\n \"E711\", \"E712\", \"E713\", \"E714\",\n \"E721\", \"E722\",\n \"E731\",\n \"E741\", \"E742\", \"E743\",\n \"E901\", \"E902\", \"E999\",\n \"W191\",\n \"W291\", \"W292\", \"W293\",\n \"W391\",\n \"W503\", \"W504\",\n \"W601\", \"W602\", \"W603\", \"W604\", \"W605\",\n \"F401\", \"F402\", \"F403\", \"F404\", \"F405\",\n \"F811\", \"F812\",\n \"F821\", \"F822\", \"F823\",\n \"F831\",\n \"F841\",\n \"F901\",\n \"C901\",\n}\n\n# https://pypi.org/project/flake8-comprehensions/#rules\nDOCUMENTED_IN_FLAKE8COMPREHENSIONS: Set[str] = {\n \"C400\", \"C401\", \"C402\", \"C403\", \"C404\", \"C405\", \"C406\", \"C407\", \"C408\", \"C409\",\n \"C410\",\n \"C411\", \"C412\", \"C413\", \"C413\", \"C414\", \"C415\", \"C416\",\n}\n\n# https://github.com/PyCQA/flake8-bugbear#list-of-warnings\nDOCUMENTED_IN_BUGBEAR: Set[str] = {\n \"B001\", \"B002\", \"B003\", \"B004\", \"B005\", \"B006\", \"B007\", \"B008\", \"B009\", \"B010\",\n \"B011\", \"B012\", \"B013\", \"B014\", \"B015\",\n \"B301\", \"B302\", \"B303\", \"B304\", \"B305\", \"B306\",\n \"B901\", \"B902\", \"B903\", \"B950\",\n}\n# fmt: on\n\n\n# stdin:2: W802 undefined name 'foo'\n# stdin:3:6: T484 Name 'foo' is not defined\n# stdin:3:-100: W605 invalid escape sequence '\\/'\n# stdin:3:1: E302 expected 2 blank lines, found 1\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n $\n \"\"\"\n)\n\n\ndef _test_results_re() -> None:\n \"\"\"\n >>> def t(s): return RESULTS_RE.search(s).groupdict()\n\n >>> t(r\"file.py:80:1: E302 expected 2 blank lines, found 1\")\n ... # doctest: +NORMALIZE_WHITESPACE\n {'file': 'file.py', 'line': '80', 'column': '1', 'code': 'E302',\n 'message': 'expected 2 blank lines, found 1'}\n\n >>> t(r\"file.py:7:1: P201: Resource `stdout` is acquired but not always released.\")\n ... # doctest: +NORMALIZE_WHITESPACE\n {'file': 'file.py', 'line': '7', 'column': '1', 'code': 'P201',\n 'message': 'Resource `stdout` is acquired but not always released.'}\n\n >>> t(r\"file.py:8:-10: W605 invalid escape sequence '/'\")\n ... # doctest: +NORMALIZE_WHITESPACE\n {'file': 'file.py', 'line': '8', 'column': '-10', 'code': 'W605',\n 'message': \"invalid escape sequence '/'\"}\n \"\"\"\n pass\n\n\ndef _run_command(\n args: List[str],\n *,\n extra_env: Optional[Dict[str, str]],\n) -> \"subprocess.CompletedProcess[str]\":\n logging.debug(\n \"$ %s\",\n \" \".join(\n ([f\"{k}={v}\" for (k, v) in extra_env.items()] if extra_env else []) + args\n ),\n )\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n check=True,\n encoding=\"utf-8\",\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef run_command(\n args: List[str],\n *,\n extra_env: Optional[Dict[str, str]],\n retries: int,\n) -> \"subprocess.CompletedProcess[str]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, extra_env=extra_env)\n except subprocess.CalledProcessError as err:\n if remaining_retries == 0 or not re.match(\n r\"^ERROR:1:1: X000 linting with .+ timed out after \\d+ seconds\",\n err.stdout,\n ):\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,\n err,\n )\n time.sleep(1)\n\n\ndef get_issue_severity(code: str) -> LintSeverity:\n # \"B901\": `return x` inside a generator\n # \"B902\": Invalid first argument to a method\n # \"B903\": __slots__ efficiency\n # \"B950\": Line too long\n # \"C4\": Flake8 Comprehensions\n # \"C9\": Cyclomatic complexity\n # \"E2\": PEP8 horizontal whitespace \"errors\"\n # \"E3\": PEP8 blank line \"errors\"\n # \"E5\": PEP8 line length \"errors\"\n # \"F401\": Name imported but unused\n # \"F403\": Star imports used\n # \"F405\": Name possibly from star imports\n # \"T400\": type checking Notes\n # \"T49\": internal type checker errors or unmatched messages\n if any(\n code.startswith(x)\n for x in [\n \"B9\",\n \"C4\",\n \"C9\",\n \"E2\",\n \"E3\",\n \"E5\",\n \"F401\",\n \"F403\",\n \"F405\",\n \"T400\",\n \"T49\",\n ]\n ):\n return LintSeverity.ADVICE\n\n # \"F821\": Undefined name\n # \"E999\": syntax error\n if any(code.startswith(x) for x in [\"F821\", \"E999\"]):\n return LintSeverity.ERROR\n\n # \"F\": PyFlakes Error\n # \"B\": flake8-bugbear Error\n # \"E\": PEP8 \"Error\"\n # \"W\": PEP8 Warning\n # possibly other plugins...\n return LintSeverity.WARNING\n\n\ndef get_issue_documentation_url(code: str) -> str:\n if code in DOCUMENTED_IN_FLAKE8RULES:\n return f\"https://www.flake8rules.com/rules/{code}.html\"\n\n if code in DOCUMENTED_IN_FLAKE8COMPREHENSIONS:\n return \"https://pypi.org/project/flake8-comprehensions/#rules\"\n\n if code in DOCUMENTED_IN_BUGBEAR:\n return \"https://github.com/PyCQA/flake8-bugbear#list-of-warnings\"\n\n return \"\"\n\n\ndef check_files(\n filenames: List[str],\n flake8_plugins_path: Optional[str],\n severities: Dict[str, LintSeverity],\n retries: int,\n) -> List[LintMessage]:\n try:\n proc = run_command(\n [sys.executable, \"-mflake8\", \"--exit-zero\"] + filenames,\n extra_env={\"FLAKE8_PLUGINS_PATH\": flake8_plugins_path}\n if flake8_plugins_path\n else None,\n retries=retries,\n )\n except (OSError, subprocess.CalledProcessError) as err:\n return [\n LintMessage(\n path=None,\n line=None,\n char=None,\n code=\"FLAKE8\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(as_posix(x) for x in err.cmd),\n stderr=err.stderr.strip() or \"(empty)\",\n stdout=err.stdout.strip() or \"(empty)\",\n )\n ),\n )\n ]\n\n return [\n LintMessage(\n path=match[\"file\"],\n name=match[\"code\"],\n description=\"{}\\nSee {}\".format(\n match[\"message\"],\n get_issue_documentation_url(match[\"code\"]),\n ),\n line=int(match[\"line\"]),\n char=int(match[\"column\"])\n if match[\"column\"] is not None and not match[\"column\"].startswith(\"-\")\n else None,\n code=\"FLAKE8\",\n severity=severities.get(match[\"code\"]) or get_issue_severity(match[\"code\"]),\n original=None,\n replacement=None,\n )\n for match in RESULTS_RE.finditer(proc.stdout)\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Flake8 wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--flake8-plugins-path\",\n help=\"FLAKE8_PLUGINS_PATH env value\",\n )\n parser.add_argument(\n \"--severity\",\n action=\"append\",\n help=\"map code to severity (e.g. `B950:advice`)\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out flake8\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n flake8_plugins_path = (\n None\n if args.flake8_plugins_path is None\n else os.path.realpath(args.flake8_plugins_path)\n )\n\n severities: Dict[str, LintSeverity] = {}\n if args.severity:\n for severity in args.severity:\n parts = severity.split(\":\", 1)\n assert len(parts) == 2, f\"invalid severity `{severity}`\"\n severities[parts[0]] = LintSeverity(parts[1])\n\n lint_messages = check_files(\n args.filenames, flake8_plugins_path, severities, args.retries\n )\n for lint_message in lint_messages:\n print(json.dumps(lint_message._asdict()), flush=True)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter.eprint","uri":"program://Fuser/function/tools.linter.adapters.flake8_linter.eprint#L16-L17","kind":"function","name":"eprint","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":16,"end_line":17,"context_start_line":1,"context_end_line":37,"code":"import argparse\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, Dict, List, NamedTuple, Optional, Set, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter.LintSeverity","uri":"program://Fuser/class/tools.linter.adapters.flake8_linter.LintSeverity#L20-L24","kind":"class","name":"LintSeverity","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":20,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"import argparse\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, Dict, List, NamedTuple, Optional, Set, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# fmt: off\n# https://www.flake8rules.com/","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter.LintMessage","uri":"program://Fuser/class/tools.linter.adapters.flake8_linter.LintMessage#L27-L36","kind":"class","name":"LintMessage","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":27,"end_line":36,"context_start_line":7,"context_end_line":56,"code":"import sys\nimport time\nfrom enum import Enum\nfrom typing import Any, Dict, List, NamedTuple, Optional, Set, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# fmt: off\n# https://www.flake8rules.com/\nDOCUMENTED_IN_FLAKE8RULES: Set[str] = {\n \"E101\", \"E111\", \"E112\", \"E113\", \"E114\", \"E115\", \"E116\", \"E117\",\n \"E121\", \"E122\", \"E123\", \"E124\", \"E125\", \"E126\", \"E127\", \"E128\", \"E129\",\n \"E131\", \"E133\",\n \"E201\", \"E202\", \"E203\",\n \"E211\",\n \"E221\", \"E222\", \"E223\", \"E224\", \"E225\", \"E226\", \"E227\", \"E228\",\n \"E231\",\n \"E241\", \"E242\",\n \"E251\",\n \"E261\", \"E262\", \"E265\", \"E266\",\n \"E271\", \"E272\", \"E273\", \"E274\", \"E275\",","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter.as_posix","uri":"program://Fuser/function/tools.linter.adapters.flake8_linter.as_posix#L39-L40","kind":"function","name":"as_posix","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":39,"end_line":40,"context_start_line":19,"context_end_line":60,"code":"\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef as_posix(name: str) -> str:\n return name.replace(\"\\\\\", \"/\") if IS_WINDOWS else name\n\n\n# fmt: off\n# https://www.flake8rules.com/\nDOCUMENTED_IN_FLAKE8RULES: Set[str] = {\n \"E101\", \"E111\", \"E112\", \"E113\", \"E114\", \"E115\", \"E116\", \"E117\",\n \"E121\", \"E122\", \"E123\", \"E124\", \"E125\", \"E126\", \"E127\", \"E128\", \"E129\",\n \"E131\", \"E133\",\n \"E201\", \"E202\", \"E203\",\n \"E211\",\n \"E221\", \"E222\", \"E223\", \"E224\", \"E225\", \"E226\", \"E227\", \"E228\",\n \"E231\",\n \"E241\", \"E242\",\n \"E251\",\n \"E261\", \"E262\", \"E265\", \"E266\",\n \"E271\", \"E272\", \"E273\", \"E274\", \"E275\",\n \"E301\", \"E302\", \"E303\", \"E304\", \"E305\", \"E306\",\n \"E401\", \"E402\",\n \"E501\", \"E502\",\n \"E701\", \"E702\", \"E703\", \"E704\",","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter._test_results_re","uri":"program://Fuser/function/tools.linter.adapters.flake8_linter._test_results_re#L114-L133","kind":"function","name":"_test_results_re","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":114,"end_line":133,"context_start_line":94,"context_end_line":153,"code":"# fmt: on\n\n\n# stdin:2: W802 undefined name 'foo'\n# stdin:3:6: T484 Name 'foo' is not defined\n# stdin:3:-100: W605 invalid escape sequence '\\/'\n# stdin:3:1: E302 expected 2 blank lines, found 1\nRESULTS_RE: Pattern[str] = re.compile(\n r\"\"\"(?mx)\n ^\n (?P.*?):\n (?P\\d+):\n (?:(?P-?\\d+):)?\n \\s(?P\\S+?):?\n \\s(?P.*)\n $\n \"\"\"\n)\n\n\ndef _test_results_re() -> None:\n \"\"\"\n >>> def t(s): return RESULTS_RE.search(s).groupdict()\n\n >>> t(r\"file.py:80:1: E302 expected 2 blank lines, found 1\")\n ... # doctest: +NORMALIZE_WHITESPACE\n {'file': 'file.py', 'line': '80', 'column': '1', 'code': 'E302',\n 'message': 'expected 2 blank lines, found 1'}\n\n >>> t(r\"file.py:7:1: P201: Resource `stdout` is acquired but not always released.\")\n ... # doctest: +NORMALIZE_WHITESPACE\n {'file': 'file.py', 'line': '7', 'column': '1', 'code': 'P201',\n 'message': 'Resource `stdout` is acquired but not always released.'}\n\n >>> t(r\"file.py:8:-10: W605 invalid escape sequence '/'\")\n ... # doctest: +NORMALIZE_WHITESPACE\n {'file': 'file.py', 'line': '8', 'column': '-10', 'code': 'W605',\n 'message': \"invalid escape sequence '/'\"}\n \"\"\"\n pass\n\n\ndef _run_command(\n args: List[str],\n *,\n extra_env: Optional[Dict[str, str]],\n) -> \"subprocess.CompletedProcess[str]\":\n logging.debug(\n \"$ %s\",\n \" \".join(\n ([f\"{k}={v}\" for (k, v) in extra_env.items()] if extra_env else []) + args\n ),\n )\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n check=True,","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter._run_command","uri":"program://Fuser/function/tools.linter.adapters.flake8_linter._run_command#L136-L158","kind":"function","name":"_run_command","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":136,"end_line":158,"context_start_line":116,"context_end_line":178,"code":" >>> def t(s): return RESULTS_RE.search(s).groupdict()\n\n >>> t(r\"file.py:80:1: E302 expected 2 blank lines, found 1\")\n ... # doctest: +NORMALIZE_WHITESPACE\n {'file': 'file.py', 'line': '80', 'column': '1', 'code': 'E302',\n 'message': 'expected 2 blank lines, found 1'}\n\n >>> t(r\"file.py:7:1: P201: Resource `stdout` is acquired but not always released.\")\n ... # doctest: +NORMALIZE_WHITESPACE\n {'file': 'file.py', 'line': '7', 'column': '1', 'code': 'P201',\n 'message': 'Resource `stdout` is acquired but not always released.'}\n\n >>> t(r\"file.py:8:-10: W605 invalid escape sequence '/'\")\n ... # doctest: +NORMALIZE_WHITESPACE\n {'file': 'file.py', 'line': '8', 'column': '-10', 'code': 'W605',\n 'message': \"invalid escape sequence '/'\"}\n \"\"\"\n pass\n\n\ndef _run_command(\n args: List[str],\n *,\n extra_env: Optional[Dict[str, str]],\n) -> \"subprocess.CompletedProcess[str]\":\n logging.debug(\n \"$ %s\",\n \" \".join(\n ([f\"{k}={v}\" for (k, v) in extra_env.items()] if extra_env else []) + args\n ),\n )\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n check=True,\n encoding=\"utf-8\",\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef run_command(\n args: List[str],\n *,\n extra_env: Optional[Dict[str, str]],\n retries: int,\n) -> \"subprocess.CompletedProcess[str]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, extra_env=extra_env)\n except subprocess.CalledProcessError as err:\n if remaining_retries == 0 or not re.match(\n r\"^ERROR:1:1: X000 linting with .+ timed out after \\d+ seconds\",\n err.stdout,\n ):\n raise err\n remaining_retries -= 1\n logging.warning(","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter.run_command","uri":"program://Fuser/function/tools.linter.adapters.flake8_linter.run_command#L161-L184","kind":"function","name":"run_command","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":161,"end_line":184,"context_start_line":141,"context_end_line":204,"code":" logging.debug(\n \"$ %s\",\n \" \".join(\n ([f\"{k}={v}\" for (k, v) in extra_env.items()] if extra_env else []) + args\n ),\n )\n start_time = time.monotonic()\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n check=True,\n encoding=\"utf-8\",\n )\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)\n\n\ndef run_command(\n args: List[str],\n *,\n extra_env: Optional[Dict[str, str]],\n retries: int,\n) -> \"subprocess.CompletedProcess[str]\":\n remaining_retries = retries\n while True:\n try:\n return _run_command(args, extra_env=extra_env)\n except subprocess.CalledProcessError as err:\n if remaining_retries == 0 or not re.match(\n r\"^ERROR:1:1: X000 linting with .+ timed out after \\d+ seconds\",\n err.stdout,\n ):\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,\n err,\n )\n time.sleep(1)\n\n\ndef get_issue_severity(code: str) -> LintSeverity:\n # \"B901\": `return x` inside a generator\n # \"B902\": Invalid first argument to a method\n # \"B903\": __slots__ efficiency\n # \"B950\": Line too long\n # \"C4\": Flake8 Comprehensions\n # \"C9\": Cyclomatic complexity\n # \"E2\": PEP8 horizontal whitespace \"errors\"\n # \"E3\": PEP8 blank line \"errors\"\n # \"E5\": PEP8 line length \"errors\"\n # \"F401\": Name imported but unused\n # \"F403\": Star imports used\n # \"F405\": Name possibly from star imports\n # \"T400\": type checking Notes\n # \"T49\": internal type checker errors or unmatched messages\n if any(\n code.startswith(x)\n for x in [","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter.get_issue_severity","uri":"program://Fuser/function/tools.linter.adapters.flake8_linter.get_issue_severity#L187-L230","kind":"function","name":"get_issue_severity","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":187,"end_line":230,"context_start_line":167,"context_end_line":250,"code":" remaining_retries = retries\n while True:\n try:\n return _run_command(args, extra_env=extra_env)\n except subprocess.CalledProcessError as err:\n if remaining_retries == 0 or not re.match(\n r\"^ERROR:1:1: X000 linting with .+ timed out after \\d+ seconds\",\n err.stdout,\n ):\n raise err\n remaining_retries -= 1\n logging.warning(\n \"(%s/%s) Retrying because command failed with: %r\",\n retries - remaining_retries,\n retries,\n err,\n )\n time.sleep(1)\n\n\ndef get_issue_severity(code: str) -> LintSeverity:\n # \"B901\": `return x` inside a generator\n # \"B902\": Invalid first argument to a method\n # \"B903\": __slots__ efficiency\n # \"B950\": Line too long\n # \"C4\": Flake8 Comprehensions\n # \"C9\": Cyclomatic complexity\n # \"E2\": PEP8 horizontal whitespace \"errors\"\n # \"E3\": PEP8 blank line \"errors\"\n # \"E5\": PEP8 line length \"errors\"\n # \"F401\": Name imported but unused\n # \"F403\": Star imports used\n # \"F405\": Name possibly from star imports\n # \"T400\": type checking Notes\n # \"T49\": internal type checker errors or unmatched messages\n if any(\n code.startswith(x)\n for x in [\n \"B9\",\n \"C4\",\n \"C9\",\n \"E2\",\n \"E3\",\n \"E5\",\n \"F401\",\n \"F403\",\n \"F405\",\n \"T400\",\n \"T49\",\n ]\n ):\n return LintSeverity.ADVICE\n\n # \"F821\": Undefined name\n # \"E999\": syntax error\n if any(code.startswith(x) for x in [\"F821\", \"E999\"]):\n return LintSeverity.ERROR\n\n # \"F\": PyFlakes Error\n # \"B\": flake8-bugbear Error\n # \"E\": PEP8 \"Error\"\n # \"W\": PEP8 Warning\n # possibly other plugins...\n return LintSeverity.WARNING\n\n\ndef get_issue_documentation_url(code: str) -> str:\n if code in DOCUMENTED_IN_FLAKE8RULES:\n return f\"https://www.flake8rules.com/rules/{code}.html\"\n\n if code in DOCUMENTED_IN_FLAKE8COMPREHENSIONS:\n return \"https://pypi.org/project/flake8-comprehensions/#rules\"\n\n if code in DOCUMENTED_IN_BUGBEAR:\n return \"https://github.com/PyCQA/flake8-bugbear#list-of-warnings\"\n\n return \"\"\n\n\ndef check_files(\n filenames: List[str],\n flake8_plugins_path: Optional[str],\n severities: Dict[str, LintSeverity],\n retries: int,","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter.get_issue_documentation_url","uri":"program://Fuser/function/tools.linter.adapters.flake8_linter.get_issue_documentation_url#L233-L243","kind":"function","name":"get_issue_documentation_url","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":233,"end_line":243,"context_start_line":213,"context_end_line":263,"code":" \"F405\",\n \"T400\",\n \"T49\",\n ]\n ):\n return LintSeverity.ADVICE\n\n # \"F821\": Undefined name\n # \"E999\": syntax error\n if any(code.startswith(x) for x in [\"F821\", \"E999\"]):\n return LintSeverity.ERROR\n\n # \"F\": PyFlakes Error\n # \"B\": flake8-bugbear Error\n # \"E\": PEP8 \"Error\"\n # \"W\": PEP8 Warning\n # possibly other plugins...\n return LintSeverity.WARNING\n\n\ndef get_issue_documentation_url(code: str) -> str:\n if code in DOCUMENTED_IN_FLAKE8RULES:\n return f\"https://www.flake8rules.com/rules/{code}.html\"\n\n if code in DOCUMENTED_IN_FLAKE8COMPREHENSIONS:\n return \"https://pypi.org/project/flake8-comprehensions/#rules\"\n\n if code in DOCUMENTED_IN_BUGBEAR:\n return \"https://github.com/PyCQA/flake8-bugbear#list-of-warnings\"\n\n return \"\"\n\n\ndef check_files(\n filenames: List[str],\n flake8_plugins_path: Optional[str],\n severities: Dict[str, LintSeverity],\n retries: int,\n) -> List[LintMessage]:\n try:\n proc = run_command(\n [sys.executable, \"-mflake8\", \"--exit-zero\"] + filenames,\n extra_env={\"FLAKE8_PLUGINS_PATH\": flake8_plugins_path}\n if flake8_plugins_path\n else None,\n retries=retries,\n )\n except (OSError, subprocess.CalledProcessError) as err:\n return [\n LintMessage(\n path=None,","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter.check_files","uri":"program://Fuser/function/tools.linter.adapters.flake8_linter.check_files#L246-L307","kind":"function","name":"check_files","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":246,"end_line":307,"context_start_line":226,"context_end_line":327,"code":" # \"B\": flake8-bugbear Error\n # \"E\": PEP8 \"Error\"\n # \"W\": PEP8 Warning\n # possibly other plugins...\n return LintSeverity.WARNING\n\n\ndef get_issue_documentation_url(code: str) -> str:\n if code in DOCUMENTED_IN_FLAKE8RULES:\n return f\"https://www.flake8rules.com/rules/{code}.html\"\n\n if code in DOCUMENTED_IN_FLAKE8COMPREHENSIONS:\n return \"https://pypi.org/project/flake8-comprehensions/#rules\"\n\n if code in DOCUMENTED_IN_BUGBEAR:\n return \"https://github.com/PyCQA/flake8-bugbear#list-of-warnings\"\n\n return \"\"\n\n\ndef check_files(\n filenames: List[str],\n flake8_plugins_path: Optional[str],\n severities: Dict[str, LintSeverity],\n retries: int,\n) -> List[LintMessage]:\n try:\n proc = run_command(\n [sys.executable, \"-mflake8\", \"--exit-zero\"] + filenames,\n extra_env={\"FLAKE8_PLUGINS_PATH\": flake8_plugins_path}\n if flake8_plugins_path\n else None,\n retries=retries,\n )\n except (OSError, subprocess.CalledProcessError) as err:\n return [\n LintMessage(\n path=None,\n line=None,\n char=None,\n code=\"FLAKE8\",\n severity=LintSeverity.ERROR,\n name=\"command-failed\",\n original=None,\n replacement=None,\n description=(\n f\"Failed due to {err.__class__.__name__}:\\n{err}\"\n if not isinstance(err, subprocess.CalledProcessError)\n else (\n \"COMMAND (exit code {returncode})\\n\"\n \"{command}\\n\\n\"\n \"STDERR\\n{stderr}\\n\\n\"\n \"STDOUT\\n{stdout}\"\n ).format(\n returncode=err.returncode,\n command=\" \".join(as_posix(x) for x in err.cmd),\n stderr=err.stderr.strip() or \"(empty)\",\n stdout=err.stdout.strip() or \"(empty)\",\n )\n ),\n )\n ]\n\n return [\n LintMessage(\n path=match[\"file\"],\n name=match[\"code\"],\n description=\"{}\\nSee {}\".format(\n match[\"message\"],\n get_issue_documentation_url(match[\"code\"]),\n ),\n line=int(match[\"line\"]),\n char=int(match[\"column\"])\n if match[\"column\"] is not None and not match[\"column\"].startswith(\"-\")\n else None,\n code=\"FLAKE8\",\n severity=severities.get(match[\"code\"]) or get_issue_severity(match[\"code\"]),\n original=None,\n replacement=None,\n )\n for match in RESULTS_RE.finditer(proc.stdout)\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Flake8 wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--flake8-plugins-path\",\n help=\"FLAKE8_PLUGINS_PATH env value\",\n )\n parser.add_argument(\n \"--severity\",\n action=\"append\",\n help=\"map code to severity (e.g. `B950:advice`)\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.flake8_linter.main","uri":"program://Fuser/function/tools.linter.adapters.flake8_linter.main#L310-L369","kind":"function","name":"main","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":310,"end_line":369,"context_start_line":290,"context_end_line":373,"code":" LintMessage(\n path=match[\"file\"],\n name=match[\"code\"],\n description=\"{}\\nSee {}\".format(\n match[\"message\"],\n get_issue_documentation_url(match[\"code\"]),\n ),\n line=int(match[\"line\"]),\n char=int(match[\"column\"])\n if match[\"column\"] is not None and not match[\"column\"].startswith(\"-\")\n else None,\n code=\"FLAKE8\",\n severity=severities.get(match[\"code\"]) or get_issue_severity(match[\"code\"]),\n original=None,\n replacement=None,\n )\n for match in RESULTS_RE.finditer(proc.stdout)\n ]\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(\n description=\"Flake8 wrapper linter.\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--flake8-plugins-path\",\n help=\"FLAKE8_PLUGINS_PATH env value\",\n )\n parser.add_argument(\n \"--severity\",\n action=\"append\",\n help=\"map code to severity (e.g. `B950:advice`)\",\n )\n parser.add_argument(\n \"--retries\",\n default=3,\n type=int,\n help=\"times to retry timed out flake8\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"verbose logging\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n flake8_plugins_path = (\n None\n if args.flake8_plugins_path is None\n else os.path.realpath(args.flake8_plugins_path)\n )\n\n severities: Dict[str, LintSeverity] = {}\n if args.severity:\n for severity in args.severity:\n parts = severity.split(\":\", 1)\n assert len(parts) == 2, f\"invalid severity `{severity}`\"\n severities[parts[0]] = LintSeverity(parts[1])\n\n lint_messages = check_files(\n args.filenames, flake8_plugins_path, severities, args.retries\n )\n for lint_message in lint_messages:\n print(json.dumps(lint_message._asdict()), flush=True)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.newlines_linter","uri":"program://Fuser/module/tools.linter.adapters.newlines_linter#L1-L135","kind":"module","name":"tools.linter.adapters.newlines_linter","path":"tools/linter/adapters/newlines_linter.py","language":"python","start_line":1,"end_line":135,"context_start_line":1,"context_end_line":135,"code":"\"\"\"\nNEWLINE: Checks files to make sure there are no trailing newlines.\n\"\"\"\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\n\nfrom enum import Enum\nfrom typing import NamedTuple, Optional\n\nNEWLINE = 10 # ASCII \"\\n\"\nLINTER_CODE = \"NEWLINE\"\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef correct_trailing_newlines(filename: str) -> bool:\n with open(filename, \"rb\") as f:\n a = len(f.read(2))\n if a == 0:\n return True\n elif a == 1:\n # file is wrong whether or not the only byte is a newline\n return False\n else:\n f.seek(-2, os.SEEK_END)\n b, c = f.read(2)\n # no ASCII byte is part of any non-ASCII character in UTF-8\n return b != NEWLINE and c == NEWLINE\n\n\ndef check_file(filename: str) -> Optional[LintMessage]:\n logging.debug(\"Checking file %s\", filename)\n\n with open(filename, \"rb\") as f:\n a = len(f.read(2))\n if a == 0:\n # File is empty, just leave it alone.\n return None\n\n if a == 1:\n # file is wrong whether or not the only byte is a newline\n return LintMessage(\n path=filename,\n line=None,\n char=None,\n code=LINTER_CODE,\n severity=LintSeverity.ERROR,\n name=\"testestTrailing newline\",\n original=None,\n replacement=None,\n description=\"Trailing newline found. Run `lintrunner --take NEWLINE -a` to apply changes.\",\n )\n\n # Read the last two bytes\n f.seek(-2, os.SEEK_END)\n b, c = f.read(2)\n # no ASCII byte is part of any non-ASCII character in UTF-8\n if b != NEWLINE and c == NEWLINE:\n return None\n\n f.seek(0)\n try:\n original = f.read().decode(\"utf-8\")\n except Exception as err:\n return None\n\n return LintMessage(\n path=filename,\n line=None,\n char=None,\n code=LINTER_CODE,\n severity=LintSeverity.ERROR,\n name=\"Trailing newline\",\n original=original,\n replacement=original.rstrip(\"\\n\") + \"\\n\",\n description=\"Trailing newline found. Run `lintrunner --take NEWLINE -a` to apply changes.\",\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"native functions linter\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"location of native_functions.yaml\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n\n args = parser.parse_args()\n\n logging.basicConfig(\n format=\"<%(threadName)s:%(levelname)s> %(message)s\",\n level=logging.NOTSET\n if args.verbose\n else logging.DEBUG\n if len(args.filenames) < 1000\n else logging.INFO,\n stream=sys.stderr,\n )\n\n lint_messages = []\n for filename in args.filenames:\n lint_message = check_file(filename)\n if lint_message is not None:\n lint_messages.append(lint_message)\n\n for lint_message in lint_messages:\n print(json.dumps(lint_message._asdict()), flush=True)","source_hash":"2c6de3301ceaf1dffb02fff6d4d6dc4a0ed4ff8b1bba82953886cf9d2be0ba0e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.newlines_linter.LintSeverity","uri":"program://Fuser/class/tools.linter.adapters.newlines_linter.LintSeverity#L17-L21","kind":"class","name":"LintSeverity","path":"tools/linter/adapters/newlines_linter.py","language":"python","start_line":17,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"\"\"\"\nNEWLINE: Checks files to make sure there are no trailing newlines.\n\"\"\"\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\n\nfrom enum import Enum\nfrom typing import NamedTuple, Optional\n\nNEWLINE = 10 # ASCII \"\\n\"\nLINTER_CODE = \"NEWLINE\"\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef correct_trailing_newlines(filename: str) -> bool:\n with open(filename, \"rb\") as f:\n a = len(f.read(2))\n if a == 0:\n return True\n elif a == 1:","source_hash":"2c6de3301ceaf1dffb02fff6d4d6dc4a0ed4ff8b1bba82953886cf9d2be0ba0e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.newlines_linter.LintMessage","uri":"program://Fuser/class/tools.linter.adapters.newlines_linter.LintMessage#L24-L33","kind":"class","name":"LintMessage","path":"tools/linter/adapters/newlines_linter.py","language":"python","start_line":24,"end_line":33,"context_start_line":4,"context_end_line":53,"code":"import argparse\nimport json\nimport logging\nimport os\nimport sys\n\nfrom enum import Enum\nfrom typing import NamedTuple, Optional\n\nNEWLINE = 10 # ASCII \"\\n\"\nLINTER_CODE = \"NEWLINE\"\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef correct_trailing_newlines(filename: str) -> bool:\n with open(filename, \"rb\") as f:\n a = len(f.read(2))\n if a == 0:\n return True\n elif a == 1:\n # file is wrong whether or not the only byte is a newline\n return False\n else:\n f.seek(-2, os.SEEK_END)\n b, c = f.read(2)\n # no ASCII byte is part of any non-ASCII character in UTF-8\n return b != NEWLINE and c == NEWLINE\n\n\ndef check_file(filename: str) -> Optional[LintMessage]:\n logging.debug(\"Checking file %s\", filename)\n","source_hash":"2c6de3301ceaf1dffb02fff6d4d6dc4a0ed4ff8b1bba82953886cf9d2be0ba0e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.newlines_linter.correct_trailing_newlines","uri":"program://Fuser/function/tools.linter.adapters.newlines_linter.correct_trailing_newlines#L36-L48","kind":"function","name":"correct_trailing_newlines","path":"tools/linter/adapters/newlines_linter.py","language":"python","start_line":36,"end_line":48,"context_start_line":16,"context_end_line":68,"code":"\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n\n\nclass LintMessage(NamedTuple):\n path: Optional[str]\n line: Optional[int]\n char: Optional[int]\n code: str\n severity: LintSeverity\n name: str\n original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef correct_trailing_newlines(filename: str) -> bool:\n with open(filename, \"rb\") as f:\n a = len(f.read(2))\n if a == 0:\n return True\n elif a == 1:\n # file is wrong whether or not the only byte is a newline\n return False\n else:\n f.seek(-2, os.SEEK_END)\n b, c = f.read(2)\n # no ASCII byte is part of any non-ASCII character in UTF-8\n return b != NEWLINE and c == NEWLINE\n\n\ndef check_file(filename: str) -> Optional[LintMessage]:\n logging.debug(\"Checking file %s\", filename)\n\n with open(filename, \"rb\") as f:\n a = len(f.read(2))\n if a == 0:\n # File is empty, just leave it alone.\n return None\n\n if a == 1:\n # file is wrong whether or not the only byte is a newline\n return LintMessage(\n path=filename,\n line=None,\n char=None,\n code=LINTER_CODE,\n severity=LintSeverity.ERROR,\n name=\"testestTrailing newline\",","source_hash":"2c6de3301ceaf1dffb02fff6d4d6dc4a0ed4ff8b1bba82953886cf9d2be0ba0e","truncated":false} {"repo_id":"Fuser","entity_id":"py:tools.linter.adapters.newlines_linter.check_file","uri":"program://Fuser/function/tools.linter.adapters.newlines_linter.check_file#L51-L97","kind":"function","name":"check_file","path":"tools/linter/adapters/newlines_linter.py","language":"python","start_line":51,"end_line":97,"context_start_line":31,"context_end_line":117,"code":" original: Optional[str]\n replacement: Optional[str]\n description: Optional[str]\n\n\ndef correct_trailing_newlines(filename: str) -> bool:\n with open(filename, \"rb\") as f:\n a = len(f.read(2))\n if a == 0:\n return True\n elif a == 1:\n # file is wrong whether or not the only byte is a newline\n return False\n else:\n f.seek(-2, os.SEEK_END)\n b, c = f.read(2)\n # no ASCII byte is part of any non-ASCII character in UTF-8\n return b != NEWLINE and c == NEWLINE\n\n\ndef check_file(filename: str) -> Optional[LintMessage]:\n logging.debug(\"Checking file %s\", filename)\n\n with open(filename, \"rb\") as f:\n a = len(f.read(2))\n if a == 0:\n # File is empty, just leave it alone.\n return None\n\n if a == 1:\n # file is wrong whether or not the only byte is a newline\n return LintMessage(\n path=filename,\n line=None,\n char=None,\n code=LINTER_CODE,\n severity=LintSeverity.ERROR,\n name=\"testestTrailing newline\",\n original=None,\n replacement=None,\n description=\"Trailing newline found. Run `lintrunner --take NEWLINE -a` to apply changes.\",\n )\n\n # Read the last two bytes\n f.seek(-2, os.SEEK_END)\n b, c = f.read(2)\n # no ASCII byte is part of any non-ASCII character in UTF-8\n if b != NEWLINE and c == NEWLINE:\n return None\n\n f.seek(0)\n try:\n original = f.read().decode(\"utf-8\")\n except Exception as err:\n return None\n\n return LintMessage(\n path=filename,\n line=None,\n char=None,\n code=LINTER_CODE,\n severity=LintSeverity.ERROR,\n name=\"Trailing newline\",\n original=original,\n replacement=original.rstrip(\"\\n\") + \"\\n\",\n description=\"Trailing newline found. Run `lintrunner --take NEWLINE -a` to apply changes.\",\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"native functions linter\",\n fromfile_prefix_chars=\"@\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n help=\"location of native_functions.yaml\",\n )\n parser.add_argument(\n \"filenames\",\n nargs=\"+\",\n help=\"paths to lint\",\n )\n\n args = parser.parse_args()\n","source_hash":"2c6de3301ceaf1dffb02fff6d4d6dc4a0ed4ff8b1bba82953886cf9d2be0ba0e","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_batchnorm_bwd","uri":"program://Fuser/module/benchmarks.python.test_batchnorm_bwd#L1-L56","kind":"module","name":"benchmarks.python.test_batchnorm_bwd","path":"benchmarks/python/test_batchnorm_bwd.py","language":"python","start_line":1,"end_line":56,"context_start_line":1,"context_end_line":56,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_bwd_nvf_benchmark, norm_bwd_baseline_benchmark\nfrom .core import DEFAULT_EXECUTORS\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n norm_bwd_nvf_benchmark(\n benchmark,\n size,\n dtype,\n \"batch_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n eps,\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_bwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_bwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"batch_norm\"\n )","source_hash":"a3f518d903c06c1fe97bcc8a340d77be788797383d9a369f320b3df4d66e0704","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_batchnorm_bwd.test_batchnorm_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_batchnorm_bwd.test_batchnorm_bwd_nvf_benchmark#L20-L38","kind":"function","name":"test_batchnorm_bwd_nvf_benchmark","path":"benchmarks/python/test_batchnorm_bwd.py","language":"python","start_line":20,"end_line":38,"context_start_line":1,"context_end_line":56,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_bwd_nvf_benchmark, norm_bwd_baseline_benchmark\nfrom .core import DEFAULT_EXECUTORS\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n norm_bwd_nvf_benchmark(\n benchmark,\n size,\n dtype,\n \"batch_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n eps,\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_bwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_bwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"batch_norm\"\n )","source_hash":"a3f518d903c06c1fe97bcc8a340d77be788797383d9a369f320b3df4d66e0704","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_batchnorm_bwd.test_batchnorm_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_batchnorm_bwd.test_batchnorm_bwd_baseline_benchmark#L51-L56","kind":"function","name":"test_batchnorm_bwd_baseline_benchmark","path":"benchmarks/python/test_batchnorm_bwd.py","language":"python","start_line":51,"end_line":56,"context_start_line":31,"context_end_line":56,"code":" size,\n dtype,\n \"batch_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n eps,\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_bwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_bwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"batch_norm\"\n )","source_hash":"a3f518d903c06c1fe97bcc8a340d77be788797383d9a369f320b3df4d66e0704","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_silu_mul_fwd","uri":"program://Fuser/module/benchmarks.python.test_silu_mul_fwd#L1-L81","kind":"module","name":"benchmarks.python.test_silu_mul_fwd","path":"benchmarks/python/test_silu_mul_fwd.py","language":"python","start_line":1,"end_line":81,"context_start_line":1,"context_end_line":81,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import silu_mul\n\n\ndef silu_mul_fwd_fusion(fd: FusionDefinition, dtype: DataType):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.neg(T0)\n T3 = fd.ops.exp(T2)\n S4 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T5 = fd.ops.add(S4, T3)\n T6 = fd.ops.reciprocal(T5)\n T7 = fd.ops.mul(T0, T6)\n T8 = fd.ops.mul(T7, T1)\n if dtype in PROMOTE_DTYPES:\n T8 = fd.ops.cast(T8, dtype=dtype)\n fd.add_output(T8)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(*size, device=\"cuda\", dtype=dtype) for _ in range(2)]\n\n with FusionDefinition() as fd:\n silu_mul_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = silu_mul(inputs)\n fd.validate(inputs, [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = [\n torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n for _ in range(2)\n ]\n\n benchmark_fn = with_executor(executor, silu_mul)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(\n benchmark,\n benchmark_fn,\n inputs,\n )","source_hash":"4d8f0e634311a56821d7b545bc707c063f1e11b06b48a12b84f6e24e62075358","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_silu_mul_fwd.silu_mul_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_silu_mul_fwd.silu_mul_fwd_fusion#L13-L32","kind":"function","name":"silu_mul_fwd_fusion","path":"benchmarks/python/test_silu_mul_fwd.py","language":"python","start_line":13,"end_line":32,"context_start_line":1,"context_end_line":52,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import silu_mul\n\n\ndef silu_mul_fwd_fusion(fd: FusionDefinition, dtype: DataType):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.neg(T0)\n T3 = fd.ops.exp(T2)\n S4 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T5 = fd.ops.add(S4, T3)\n T6 = fd.ops.reciprocal(T5)\n T7 = fd.ops.mul(T0, T6)\n T8 = fd.ops.mul(T7, T1)\n if dtype in PROMOTE_DTYPES:\n T8 = fd.ops.cast(T8, dtype=dtype)\n fd.add_output(T8)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(*size, device=\"cuda\", dtype=dtype) for _ in range(2)]\n\n with FusionDefinition() as fd:\n silu_mul_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = silu_mul(inputs)\n fd.validate(inputs, [eager_output])\n","source_hash":"4d8f0e634311a56821d7b545bc707c063f1e11b06b48a12b84f6e24e62075358","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_silu_mul_fwd.test_silu_mul_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_silu_mul_fwd.test_silu_mul_fwd_nvf_benchmark#L38-L54","kind":"function","name":"test_silu_mul_fwd_nvf_benchmark","path":"benchmarks/python/test_silu_mul_fwd.py","language":"python","start_line":38,"end_line":54,"context_start_line":18,"context_end_line":74,"code":" shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.neg(T0)\n T3 = fd.ops.exp(T2)\n S4 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T5 = fd.ops.add(S4, T3)\n T6 = fd.ops.reciprocal(T5)\n T7 = fd.ops.mul(T0, T6)\n T8 = fd.ops.mul(T7, T1)\n if dtype in PROMOTE_DTYPES:\n T8 = fd.ops.cast(T8, dtype=dtype)\n fd.add_output(T8)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(*size, device=\"cuda\", dtype=dtype) for _ in range(2)]\n\n with FusionDefinition() as fd:\n silu_mul_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = silu_mul(inputs)\n fd.validate(inputs, [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = [\n torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n for _ in range(2)\n ]\n\n benchmark_fn = with_executor(executor, silu_mul)","source_hash":"4d8f0e634311a56821d7b545bc707c063f1e11b06b48a12b84f6e24e62075358","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_silu_mul_fwd.test_silu_mul_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_silu_mul_fwd.test_silu_mul_fwd_baseline_benchmark#L61-L81","kind":"function","name":"test_silu_mul_fwd_baseline_benchmark","path":"benchmarks/python/test_silu_mul_fwd.py","language":"python","start_line":61,"end_line":81,"context_start_line":41,"context_end_line":81,"code":" dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(*size, device=\"cuda\", dtype=dtype) for _ in range(2)]\n\n with FusionDefinition() as fd:\n silu_mul_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = silu_mul(inputs)\n fd.validate(inputs, [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = [\n torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n for _ in range(2)\n ]\n\n benchmark_fn = with_executor(executor, silu_mul)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(\n benchmark,\n benchmark_fn,\n inputs,\n )","source_hash":"4d8f0e634311a56821d7b545bc707c063f1e11b06b48a12b84f6e24e62075358","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_fwd","uri":"program://Fuser/module/benchmarks.python.test_gelu_fwd#L1-L87","kind":"module","name":"benchmarks.python.test_gelu_fwd","path":"benchmarks/python/test_gelu_fwd.py","language":"python","start_line":1,"end_line":87,"context_start_line":1,"context_end_line":87,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import gelu\n\n\ndef gelu_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n input = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n bias = fd.ops.cast(bias, dtype=DataType.Float)\n S_079 = fd.define_scalar(0.79788456)\n S_004 = fd.define_scalar(0.044715)\n bias = fd.ops.broadcast_in_dim(bias, shape=[1, input.size(-1)], broadcast_dims=[1])\n T1 = fd.ops.add(input, bias)\n T2 = fd.ops.mul(S_079, T1)\n T3 = fd.ops.mul(S_004, T1)\n T4 = fd.ops.mul(T3, T1)\n S1 = fd.define_scalar(1.0)\n T5 = fd.ops.add(T4, S1)\n T6 = fd.ops.mul(T2, T5)\n T7 = fd.ops.tanh(T6)\n T8 = fd.ops.add(S1, T7)\n T9 = fd.ops.mul(T8, T1)\n S2 = fd.define_scalar(0.50)\n T10 = fd.ops.mul(S2, T9)\n if dtype in PROMOTE_DTYPES:\n T10 = fd.ops.cast(T10, dtype=dtype)\n fd.add_output(T10)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True), # in_tensor\n torch.ones(size[-1], device=\"cuda\", dtype=dtype), # bias\n ]\n with FusionDefinition() as fd:\n gelu_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = gelu(inputs)\n fd.validate(inputs, [eager_output])\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True), # in_tensor\n torch.ones(size[-1], device=\"cuda\", dtype=dtype), # bias\n ]\n\n benchmark_fn = with_executor(executor, gelu)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(benchmark, benchmark_fn, inputs)","source_hash":"75b06dbb6abc59d14857581dec18deb385ce5d94f5c77f3f32e107dc272480b1","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_fwd.gelu_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_gelu_fwd.gelu_fwd_fusion#L13-L41","kind":"function","name":"gelu_fwd_fusion","path":"benchmarks/python/test_gelu_fwd.py","language":"python","start_line":13,"end_line":41,"context_start_line":1,"context_end_line":61,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import gelu\n\n\ndef gelu_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n input = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n bias = fd.ops.cast(bias, dtype=DataType.Float)\n S_079 = fd.define_scalar(0.79788456)\n S_004 = fd.define_scalar(0.044715)\n bias = fd.ops.broadcast_in_dim(bias, shape=[1, input.size(-1)], broadcast_dims=[1])\n T1 = fd.ops.add(input, bias)\n T2 = fd.ops.mul(S_079, T1)\n T3 = fd.ops.mul(S_004, T1)\n T4 = fd.ops.mul(T3, T1)\n S1 = fd.define_scalar(1.0)\n T5 = fd.ops.add(T4, S1)\n T6 = fd.ops.mul(T2, T5)\n T7 = fd.ops.tanh(T6)\n T8 = fd.ops.add(S1, T7)\n T9 = fd.ops.mul(T8, T1)\n S2 = fd.define_scalar(0.50)\n T10 = fd.ops.mul(S2, T9)\n if dtype in PROMOTE_DTYPES:\n T10 = fd.ops.cast(T10, dtype=dtype)\n fd.add_output(T10)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True), # in_tensor\n torch.ones(size[-1], device=\"cuda\", dtype=dtype), # bias\n ]\n with FusionDefinition() as fd:\n gelu_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = gelu(inputs)","source_hash":"75b06dbb6abc59d14857581dec18deb385ce5d94f5c77f3f32e107dc272480b1","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_fwd.test_gelu_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_gelu_fwd.test_gelu_fwd_nvf_benchmark#L47-L64","kind":"function","name":"test_gelu_fwd_nvf_benchmark","path":"benchmarks/python/test_gelu_fwd.py","language":"python","start_line":47,"end_line":64,"context_start_line":27,"context_end_line":84,"code":" T1 = fd.ops.add(input, bias)\n T2 = fd.ops.mul(S_079, T1)\n T3 = fd.ops.mul(S_004, T1)\n T4 = fd.ops.mul(T3, T1)\n S1 = fd.define_scalar(1.0)\n T5 = fd.ops.add(T4, S1)\n T6 = fd.ops.mul(T2, T5)\n T7 = fd.ops.tanh(T6)\n T8 = fd.ops.add(S1, T7)\n T9 = fd.ops.mul(T8, T1)\n S2 = fd.define_scalar(0.50)\n T10 = fd.ops.mul(S2, T9)\n if dtype in PROMOTE_DTYPES:\n T10 = fd.ops.cast(T10, dtype=dtype)\n fd.add_output(T10)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True), # in_tensor\n torch.ones(size[-1], device=\"cuda\", dtype=dtype), # bias\n ]\n with FusionDefinition() as fd:\n gelu_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = gelu(inputs)\n fd.validate(inputs, [eager_output])\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True), # in_tensor\n torch.ones(size[-1], device=\"cuda\", dtype=dtype), # bias\n ]\n\n benchmark_fn = with_executor(executor, gelu)","source_hash":"75b06dbb6abc59d14857581dec18deb385ce5d94f5c77f3f32e107dc272480b1","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_fwd.test_gelu_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_gelu_fwd.test_gelu_fwd_baseline_benchmark#L71-L87","kind":"function","name":"test_gelu_fwd_baseline_benchmark","path":"benchmarks/python/test_gelu_fwd.py","language":"python","start_line":71,"end_line":87,"context_start_line":51,"context_end_line":87,"code":" disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True), # in_tensor\n torch.ones(size[-1], device=\"cuda\", dtype=dtype), # bias\n ]\n with FusionDefinition() as fd:\n gelu_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = gelu(inputs)\n fd.validate(inputs, [eager_output])\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True), # in_tensor\n torch.ones(size[-1], device=\"cuda\", dtype=dtype), # bias\n ]\n\n benchmark_fn = with_executor(executor, gelu)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(benchmark, benchmark_fn, inputs)","source_hash":"75b06dbb6abc59d14857581dec18deb385ce5d94f5c77f3f32e107dc272480b1","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_bwd","uri":"program://Fuser/module/benchmarks.python.test_dropout_layernorm_bwd#L1-L226","kind":"module","name":"benchmarks.python.test_dropout_layernorm_bwd","path":"benchmarks/python/test_dropout_layernorm_bwd.py","language":"python","start_line":1,"end_line":226,"context_start_line":1,"context_end_line":226,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_layernorm\n\n\ndef dropout_layernorm_bwd_fusion(\n fd: FusionDefinition, dtype: DataType, dropout_p: float\n) -> None:\n \"\"\"\n Backward pass fusion definition for computing:\n output = layernorm (input2 + dropout (input1 p=dropout_p))\n\n Fusion inputs: inputs, dropout_mask, rms, grads, weights\n Fusion outputs: grad_input, grad_weights, grad_bias\n \"\"\"\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Bool, is_cpu=False\n ) # mask\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n ) # mean\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n ) # invstd\n T4 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # grads\n T5 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False\n ) # weights\n T6 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # input1\n\n T7 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # input2\n\n if dtype in PROMOTE_DTYPES:\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n T5 = fd.ops.cast(T5, dtype=DataType.Float)\n T6 = fd.ops.cast(T6, dtype=DataType.Float)\n T7 = fd.ops.cast(T7, dtype=DataType.Float)\n\n T9 = fd.ops.mul(T6, T1)\n S10 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T11 = fd.ops.mul(T9, S10)\n T12 = fd.ops.add(T7, T11)\n\n T16 = fd.ops.broadcast_in_dim(T2, shape=[T6.size(0), 1], broadcast_dims=[0])\n V19 = T6.shape()\n T20 = fd.ops.broadcast_in_dim(T16, shape=V19, broadcast_dims=[0, 1])\n T21 = fd.ops.sub(T12, T20)\n T25 = fd.ops.broadcast_in_dim(T3, shape=V19, broadcast_dims=[0, 1])\n T26 = fd.ops.mul(T21, T25)\n T30 = fd.ops.broadcast_in_dim(T5, shape=V19, broadcast_dims=[1])\n T35 = fd.ops.sum(T4, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T37 = fd.ops.mul(T4, T30)\n T38 = fd.ops.mul(T4, T26)\n T39 = fd.ops.sum(T38, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T41 = fd.ops.mul(T37, T25)\n T42 = fd.ops.mul(T37, T21)\n T43 = fd.ops.sum(T42, dims=[1], keepdim=False, dtype=DataType.Null)\n T47 = fd.ops.broadcast_in_dim(T43, shape=[T6.size(0), 1], broadcast_dims=[0])\n T48 = fd.ops.neg(T41)\n T49 = fd.ops.sum(T48, dims=[1], keepdim=False, dtype=DataType.Null)\n T53 = fd.ops.broadcast_in_dim(T49, shape=[T6.size(0), 1], broadcast_dims=[0])\n S54 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T55 = fd.ops.mul(S54, T47)\n S56 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T57 = fd.ops.pow(T3, S56)\n T58 = fd.ops.mul(T55, T57)\n T61 = fd.ops.sum(T53, dims=[1], keepdim=False, dtype=DataType.Null)\n T62 = fd.ops.sum(T58, dims=[1], keepdim=False, dtype=DataType.Null)\n T66 = fd.ops.broadcast_in_dim(T62, shape=[T6.size(0), 1], broadcast_dims=[0])\n T70 = fd.ops.broadcast_in_dim(T66, shape=V19, broadcast_dims=[0, 1])\n T74 = fd.ops.broadcast_in_dim(T2, shape=[T6.size(0), 1], broadcast_dims=[0])\n T78 = fd.ops.broadcast_in_dim(T74, shape=V19, broadcast_dims=[0, 1])\n S79 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T80 = fd.ops.mul(S79, T70)\n T81 = fd.ops.sub(T12, T78)\n T82 = fd.ops.mul(T80, T81)\n S84 = fd.ops.reciprocal(T6.size(1))\n T85 = fd.ops.mul(T82, S84)\n T89 = fd.ops.broadcast_in_dim(T61, shape=[T6.size(0), 1], broadcast_dims=[0])\n T93 = fd.ops.broadcast_in_dim(T89, shape=V19, broadcast_dims=[0, 1])\n T95 = fd.ops.mul(S84, T93)\n T96 = fd.ops.add(T85, T95)\n T97 = fd.ops.add(T41, T96)\n\n T100 = fd.ops.mul(T97, S10)\n T101 = fd.ops.mul(T100, T1)\n\n if dtype in PROMOTE_DTYPES:\n T35 = fd.ops.cast(T35, dtype=dtype)\n T39 = fd.ops.cast(T39, dtype=dtype)\n T97 = fd.ops.cast(T97, dtype=dtype)\n T101 = fd.ops.cast(T101, dtype=dtype)\n\n fd.add_output(T101)\n fd.add_output(T97)\n fd.add_output(T39)\n fd.add_output(T35)\n\n\ndef dropout_layernorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output, grad_out).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"mean\": (size[0], torch.float),\n \"invstd\": (size[0], torch.float),\n \"grad_out\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n # Outputs\n \"grad_in1\": (size, dtype),\n \"grad_in2\": (size, dtype),\n \"grad_weights\": (size[1], dtype),\n \"grad_bias\": (size[1], dtype),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\ndef test_dropout_layernorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n dropout_p = 0.2\n dropout_mask = torch.lt(torch.rand(*size, device=\"cuda\"), 1 - dropout_p)\n # Manually compute dropout for validation\n x = input2 + 1 / (1 - dropout_p) * dropout_mask * input1\n\n mean = x.to(torch.float).mean(dim=-1)\n variance = x.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n with FusionDefinition() as fd:\n dropout_layernorm_bwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p=dropout_p\n )\n if not disable_validation:\n eager_output = torch.nn.functional.layer_norm(\n x.to(torch.double),\n input1.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n\n eager_output.backward(grads.to(torch.double))\n fd.validate(\n [dropout_mask, mean, invstd, grads, weights, input1, input2],\n [input1.grad, input2.grad, weights.grad, bias.grad],\n )\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [dropout_mask, mean, invstd, grads, weights, input1, input2],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_dropout_layernorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n dropout_p = 0.2\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, dropout_layernorm)\n fwd_inputs = [input1, input2, weights, bias, dropout_p]\n outputs = fwd_fn(fwd_inputs)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=dropout_layernorm_bwd_iobytes(size, dtype),\n )","source_hash":"3788276db1818e20d07d3b6d0685aa9f2bad06cec01af931b61b76bf3be5c7fd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_bwd.dropout_layernorm_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_dropout_layernorm_bwd.dropout_layernorm_bwd_fusion#L20-L120","kind":"function","name":"dropout_layernorm_bwd_fusion","path":"benchmarks/python/test_dropout_layernorm_bwd.py","language":"python","start_line":20,"end_line":120,"context_start_line":1,"context_end_line":140,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_layernorm\n\n\ndef dropout_layernorm_bwd_fusion(\n fd: FusionDefinition, dtype: DataType, dropout_p: float\n) -> None:\n \"\"\"\n Backward pass fusion definition for computing:\n output = layernorm (input2 + dropout (input1 p=dropout_p))\n\n Fusion inputs: inputs, dropout_mask, rms, grads, weights\n Fusion outputs: grad_input, grad_weights, grad_bias\n \"\"\"\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Bool, is_cpu=False\n ) # mask\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n ) # mean\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n ) # invstd\n T4 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # grads\n T5 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False\n ) # weights\n T6 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # input1\n\n T7 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # input2\n\n if dtype in PROMOTE_DTYPES:\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n T5 = fd.ops.cast(T5, dtype=DataType.Float)\n T6 = fd.ops.cast(T6, dtype=DataType.Float)\n T7 = fd.ops.cast(T7, dtype=DataType.Float)\n\n T9 = fd.ops.mul(T6, T1)\n S10 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T11 = fd.ops.mul(T9, S10)\n T12 = fd.ops.add(T7, T11)\n\n T16 = fd.ops.broadcast_in_dim(T2, shape=[T6.size(0), 1], broadcast_dims=[0])\n V19 = T6.shape()\n T20 = fd.ops.broadcast_in_dim(T16, shape=V19, broadcast_dims=[0, 1])\n T21 = fd.ops.sub(T12, T20)\n T25 = fd.ops.broadcast_in_dim(T3, shape=V19, broadcast_dims=[0, 1])\n T26 = fd.ops.mul(T21, T25)\n T30 = fd.ops.broadcast_in_dim(T5, shape=V19, broadcast_dims=[1])\n T35 = fd.ops.sum(T4, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T37 = fd.ops.mul(T4, T30)\n T38 = fd.ops.mul(T4, T26)\n T39 = fd.ops.sum(T38, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T41 = fd.ops.mul(T37, T25)\n T42 = fd.ops.mul(T37, T21)\n T43 = fd.ops.sum(T42, dims=[1], keepdim=False, dtype=DataType.Null)\n T47 = fd.ops.broadcast_in_dim(T43, shape=[T6.size(0), 1], broadcast_dims=[0])\n T48 = fd.ops.neg(T41)\n T49 = fd.ops.sum(T48, dims=[1], keepdim=False, dtype=DataType.Null)\n T53 = fd.ops.broadcast_in_dim(T49, shape=[T6.size(0), 1], broadcast_dims=[0])\n S54 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T55 = fd.ops.mul(S54, T47)\n S56 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T57 = fd.ops.pow(T3, S56)\n T58 = fd.ops.mul(T55, T57)\n T61 = fd.ops.sum(T53, dims=[1], keepdim=False, dtype=DataType.Null)\n T62 = fd.ops.sum(T58, dims=[1], keepdim=False, dtype=DataType.Null)\n T66 = fd.ops.broadcast_in_dim(T62, shape=[T6.size(0), 1], broadcast_dims=[0])\n T70 = fd.ops.broadcast_in_dim(T66, shape=V19, broadcast_dims=[0, 1])\n T74 = fd.ops.broadcast_in_dim(T2, shape=[T6.size(0), 1], broadcast_dims=[0])\n T78 = fd.ops.broadcast_in_dim(T74, shape=V19, broadcast_dims=[0, 1])\n S79 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T80 = fd.ops.mul(S79, T70)\n T81 = fd.ops.sub(T12, T78)\n T82 = fd.ops.mul(T80, T81)\n S84 = fd.ops.reciprocal(T6.size(1))\n T85 = fd.ops.mul(T82, S84)\n T89 = fd.ops.broadcast_in_dim(T61, shape=[T6.size(0), 1], broadcast_dims=[0])\n T93 = fd.ops.broadcast_in_dim(T89, shape=V19, broadcast_dims=[0, 1])\n T95 = fd.ops.mul(S84, T93)\n T96 = fd.ops.add(T85, T95)\n T97 = fd.ops.add(T41, T96)\n\n T100 = fd.ops.mul(T97, S10)\n T101 = fd.ops.mul(T100, T1)\n\n if dtype in PROMOTE_DTYPES:\n T35 = fd.ops.cast(T35, dtype=dtype)\n T39 = fd.ops.cast(T39, dtype=dtype)\n T97 = fd.ops.cast(T97, dtype=dtype)\n T101 = fd.ops.cast(T101, dtype=dtype)\n\n fd.add_output(T101)\n fd.add_output(T97)\n fd.add_output(T39)\n fd.add_output(T35)\n\n\ndef dropout_layernorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output, grad_out).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"mean\": (size[0], torch.float),\n \"invstd\": (size[0], torch.float),\n \"grad_out\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n # Outputs\n \"grad_in1\": (size, dtype),\n \"grad_in2\": (size, dtype),\n \"grad_weights\": (size[1], dtype),\n \"grad_bias\": (size[1], dtype),\n }\n return compute_total_iobytes(nvf_inp_out)","source_hash":"3788276db1818e20d07d3b6d0685aa9f2bad06cec01af931b61b76bf3be5c7fd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_bwd.dropout_layernorm_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_dropout_layernorm_bwd.dropout_layernorm_bwd_iobytes#L123-L140","kind":"function","name":"dropout_layernorm_bwd_iobytes","path":"benchmarks/python/test_dropout_layernorm_bwd.py","language":"python","start_line":123,"end_line":140,"context_start_line":103,"context_end_line":160,"code":" T93 = fd.ops.broadcast_in_dim(T89, shape=V19, broadcast_dims=[0, 1])\n T95 = fd.ops.mul(S84, T93)\n T96 = fd.ops.add(T85, T95)\n T97 = fd.ops.add(T41, T96)\n\n T100 = fd.ops.mul(T97, S10)\n T101 = fd.ops.mul(T100, T1)\n\n if dtype in PROMOTE_DTYPES:\n T35 = fd.ops.cast(T35, dtype=dtype)\n T39 = fd.ops.cast(T39, dtype=dtype)\n T97 = fd.ops.cast(T97, dtype=dtype)\n T101 = fd.ops.cast(T101, dtype=dtype)\n\n fd.add_output(T101)\n fd.add_output(T97)\n fd.add_output(T39)\n fd.add_output(T35)\n\n\ndef dropout_layernorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output, grad_out).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"mean\": (size[0], torch.float),\n \"invstd\": (size[0], torch.float),\n \"grad_out\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n # Outputs\n \"grad_in1\": (size, dtype),\n \"grad_in2\": (size, dtype),\n \"grad_weights\": (size[1], dtype),\n \"grad_bias\": (size[1], dtype),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\ndef test_dropout_layernorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n dropout_p = 0.2","source_hash":"3788276db1818e20d07d3b6d0685aa9f2bad06cec01af931b61b76bf3be5c7fd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_bwd.test_dropout_layernorm_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_dropout_layernorm_bwd.test_dropout_layernorm_bwd_nvf_benchmark#L146-L191","kind":"function","name":"test_dropout_layernorm_bwd_nvf_benchmark","path":"benchmarks/python/test_dropout_layernorm_bwd.py","language":"python","start_line":146,"end_line":191,"context_start_line":126,"context_end_line":211,"code":" # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"mean\": (size[0], torch.float),\n \"invstd\": (size[0], torch.float),\n \"grad_out\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n # Outputs\n \"grad_in1\": (size, dtype),\n \"grad_in2\": (size, dtype),\n \"grad_weights\": (size[1], dtype),\n \"grad_bias\": (size[1], dtype),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\ndef test_dropout_layernorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n dropout_p = 0.2\n dropout_mask = torch.lt(torch.rand(*size, device=\"cuda\"), 1 - dropout_p)\n # Manually compute dropout for validation\n x = input2 + 1 / (1 - dropout_p) * dropout_mask * input1\n\n mean = x.to(torch.float).mean(dim=-1)\n variance = x.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n with FusionDefinition() as fd:\n dropout_layernorm_bwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p=dropout_p\n )\n if not disable_validation:\n eager_output = torch.nn.functional.layer_norm(\n x.to(torch.double),\n input1.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n\n eager_output.backward(grads.to(torch.double))\n fd.validate(\n [dropout_mask, mean, invstd, grads, weights, input1, input2],\n [input1.grad, input2.grad, weights.grad, bias.grad],\n )\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [dropout_mask, mean, invstd, grads, weights, input1, input2],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_dropout_layernorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n dropout_p = 0.2\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)","source_hash":"3788276db1818e20d07d3b6d0685aa9f2bad06cec01af931b61b76bf3be5c7fd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_bwd.test_dropout_layernorm_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_dropout_layernorm_bwd.test_dropout_layernorm_bwd_baseline_benchmark#L199-L226","kind":"function","name":"test_dropout_layernorm_bwd_baseline_benchmark","path":"benchmarks/python/test_dropout_layernorm_bwd.py","language":"python","start_line":199,"end_line":226,"context_start_line":179,"context_end_line":226,"code":" )\n\n eager_output.backward(grads.to(torch.double))\n fd.validate(\n [dropout_mask, mean, invstd, grads, weights, input1, input2],\n [input1.grad, input2.grad, weights.grad, bias.grad],\n )\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [dropout_mask, mean, invstd, grads, weights, input1, input2],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_dropout_layernorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n dropout_p = 0.2\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, dropout_layernorm)\n fwd_inputs = [input1, input2, weights, bias, dropout_p]\n outputs = fwd_fn(fwd_inputs)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=dropout_layernorm_bwd_iobytes(size, dtype),\n )","source_hash":"3788276db1818e20d07d3b6d0685aa9f2bad06cec01af931b61b76bf3be5c7fd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_benchmarking_setupy","uri":"program://Fuser/module/benchmarks.python.test_benchmarking_setupy#L1-L13","kind":"module","name":"benchmarks.python.test_benchmarking_setupy","path":"benchmarks/python/test_benchmarking_setupy.py","language":"python","start_line":1,"end_line":13,"context_start_line":1,"context_end_line":13,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\n\n\ndef test_env_vars_are_set():\n for var in [\n \"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\",\n \"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\",\n ]:\n assert os.environ[var] == \"1\"","source_hash":"0a8a6a5f852d5c0a6fd56a4e513606c8a9970bcc0e94c9e0977eb8bc74718a75","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_benchmarking_setupy.test_env_vars_are_set","uri":"program://Fuser/function/benchmarks.python.test_benchmarking_setupy.test_env_vars_are_set#L8-L13","kind":"function","name":"test_env_vars_are_set","path":"benchmarks/python/test_benchmarking_setupy.py","language":"python","start_line":8,"end_line":13,"context_start_line":1,"context_end_line":13,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\n\n\ndef test_env_vars_are_set():\n for var in [\n \"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\",\n \"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\",\n ]:\n assert os.environ[var] == \"1\"","source_hash":"0a8a6a5f852d5c0a6fd56a4e513606c8a9970bcc0e94c9e0977eb8bc74718a75","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_add_fwd","uri":"program://Fuser/module/benchmarks.python.test_rmsnorm_add_fwd#L1-L105","kind":"module","name":"benchmarks.python.test_rmsnorm_add_fwd","path":"benchmarks/python/test_rmsnorm_add_fwd.py","language":"python","start_line":1,"end_line":105,"context_start_line":1,"context_end_line":105,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n with_executor,\n DEFAULT_EXECUTORS,\n check_module_available,\n)\nimport torch\nfrom .global_params import FLOAT_DTYPES, BENCHMARK_CONFIG\nfrom .torch_ops import rmsnorm_add\nimport itertools\nfrom random import sample\nfrom typing import List, Tuple\n\nif check_module_available(\"flashinfer\"):\n from flashinfer import fused_add_rmsnorm\n\n\ndef generate_input_sizes_rmsnorm_add(dims: int = 2) -> List[Tuple]:\n \"\"\"\n Local version of generate_input_sizes specifically for rmsnorm_add_fwd tests.\n Uses batch sizes [1, 2, 4, 8, 16, 32, ..., 16384] (powers of 2).\n Uses hidden sizes [256, 512, 768, 1024, ..., 16384] (step size 256).\n \"\"\"\n inputs = []\n\n if dims == 2:\n input_ranges = []\n\n step_size = 256\n # Use powers of 2 from 1 to 16384 for batch sizes\n batch_range = [2**i for i in range(0, 15)] # [1, 2, 4, 8, 16, 32, ..., 16384]\n\n # Hidden range is always [256, 512, 768, 1024, ..., 16384]\n hidden_range = list(range(step_size, 16384 + 1, step_size))\n\n # Use the same hidden range for all batch sizes since it's already capped at 16384\n input_ranges.append((batch_range, hidden_range))\n\n for batch_range_subset, hidden_range_subset in input_ranges:\n inputs.extend(\n list(itertools.product(batch_range_subset, hidden_range_subset))\n )\n else:\n raise NotImplementedError(\n f\"Generating input sizes of dimension {dims} is not implemented for rmsnorm_add\"\n )\n\n if BENCHMARK_CONFIG[\"num_inputs\"] is not None:\n inputs = sample(inputs, BENCHMARK_CONFIG[\"num_inputs\"])\n\n return inputs\n\n\n# flash infer does inplace update of inputs and residual tensors\n# needs to explicitly return the updated tensors to correctly compute IO bytes\n# https://github.com/flashinfer-ai/flashinfer/blob/ba2b4aa636c4ecf99981794767ffbf89267720cd/flashinfer/norm.py#L106\ndef flashinfer_rmsnorm_add_wrapper(inputs_list):\n inputs, weights, residual = inputs_list\n fused_add_rmsnorm(inputs, residual, weights)\n return inputs, residual\n\n\n@pytest.mark.parametrize(\n \"executor\",\n DEFAULT_EXECUTORS\n + [\n pytest.param(\n \"flashinfer\",\n marks=pytest.mark.skipif(\n not check_module_available(\"flashinfer\"),\n reason=\"flashinfer executor is not available on this device\",\n ),\n )\n ],\n)\n@pytest.mark.parametrize(\"size\", generate_input_sizes_rmsnorm_add(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_add_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=False)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=False)\n residual = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=False)\n # requires flashinfer to be installed\n # `pip install flashinfer-python` works in pjnl container\n if executor == \"flashinfer\":\n benchmark_fn = flashinfer_rmsnorm_add_wrapper\n else:\n benchmark_fn = with_executor(executor, rmsnorm_add)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, weights, residual],\n )","source_hash":"97d2303f237539385d3a74041f54c0537965f0686e792c5d35b9ae83cff8613c","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_add_fwd.generate_input_sizes_rmsnorm_add","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_add_fwd.generate_input_sizes_rmsnorm_add#L23-L56","kind":"function","name":"generate_input_sizes_rmsnorm_add","path":"benchmarks/python/test_rmsnorm_add_fwd.py","language":"python","start_line":23,"end_line":56,"context_start_line":3,"context_end_line":76,"code":"# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n with_executor,\n DEFAULT_EXECUTORS,\n check_module_available,\n)\nimport torch\nfrom .global_params import FLOAT_DTYPES, BENCHMARK_CONFIG\nfrom .torch_ops import rmsnorm_add\nimport itertools\nfrom random import sample\nfrom typing import List, Tuple\n\nif check_module_available(\"flashinfer\"):\n from flashinfer import fused_add_rmsnorm\n\n\ndef generate_input_sizes_rmsnorm_add(dims: int = 2) -> List[Tuple]:\n \"\"\"\n Local version of generate_input_sizes specifically for rmsnorm_add_fwd tests.\n Uses batch sizes [1, 2, 4, 8, 16, 32, ..., 16384] (powers of 2).\n Uses hidden sizes [256, 512, 768, 1024, ..., 16384] (step size 256).\n \"\"\"\n inputs = []\n\n if dims == 2:\n input_ranges = []\n\n step_size = 256\n # Use powers of 2 from 1 to 16384 for batch sizes\n batch_range = [2**i for i in range(0, 15)] # [1, 2, 4, 8, 16, 32, ..., 16384]\n\n # Hidden range is always [256, 512, 768, 1024, ..., 16384]\n hidden_range = list(range(step_size, 16384 + 1, step_size))\n\n # Use the same hidden range for all batch sizes since it's already capped at 16384\n input_ranges.append((batch_range, hidden_range))\n\n for batch_range_subset, hidden_range_subset in input_ranges:\n inputs.extend(\n list(itertools.product(batch_range_subset, hidden_range_subset))\n )\n else:\n raise NotImplementedError(\n f\"Generating input sizes of dimension {dims} is not implemented for rmsnorm_add\"\n )\n\n if BENCHMARK_CONFIG[\"num_inputs\"] is not None:\n inputs = sample(inputs, BENCHMARK_CONFIG[\"num_inputs\"])\n\n return inputs\n\n\n# flash infer does inplace update of inputs and residual tensors\n# needs to explicitly return the updated tensors to correctly compute IO bytes\n# https://github.com/flashinfer-ai/flashinfer/blob/ba2b4aa636c4ecf99981794767ffbf89267720cd/flashinfer/norm.py#L106\ndef flashinfer_rmsnorm_add_wrapper(inputs_list):\n inputs, weights, residual = inputs_list\n fused_add_rmsnorm(inputs, residual, weights)\n return inputs, residual\n\n\n@pytest.mark.parametrize(\n \"executor\",\n DEFAULT_EXECUTORS\n + [\n pytest.param(\n \"flashinfer\",\n marks=pytest.mark.skipif(\n not check_module_available(\"flashinfer\"),\n reason=\"flashinfer executor is not available on this device\",","source_hash":"97d2303f237539385d3a74041f54c0537965f0686e792c5d35b9ae83cff8613c","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_add_fwd.flashinfer_rmsnorm_add_wrapper","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_add_fwd.flashinfer_rmsnorm_add_wrapper#L62-L65","kind":"function","name":"flashinfer_rmsnorm_add_wrapper","path":"benchmarks/python/test_rmsnorm_add_fwd.py","language":"python","start_line":62,"end_line":65,"context_start_line":42,"context_end_line":85,"code":" input_ranges.append((batch_range, hidden_range))\n\n for batch_range_subset, hidden_range_subset in input_ranges:\n inputs.extend(\n list(itertools.product(batch_range_subset, hidden_range_subset))\n )\n else:\n raise NotImplementedError(\n f\"Generating input sizes of dimension {dims} is not implemented for rmsnorm_add\"\n )\n\n if BENCHMARK_CONFIG[\"num_inputs\"] is not None:\n inputs = sample(inputs, BENCHMARK_CONFIG[\"num_inputs\"])\n\n return inputs\n\n\n# flash infer does inplace update of inputs and residual tensors\n# needs to explicitly return the updated tensors to correctly compute IO bytes\n# https://github.com/flashinfer-ai/flashinfer/blob/ba2b4aa636c4ecf99981794767ffbf89267720cd/flashinfer/norm.py#L106\ndef flashinfer_rmsnorm_add_wrapper(inputs_list):\n inputs, weights, residual = inputs_list\n fused_add_rmsnorm(inputs, residual, weights)\n return inputs, residual\n\n\n@pytest.mark.parametrize(\n \"executor\",\n DEFAULT_EXECUTORS\n + [\n pytest.param(\n \"flashinfer\",\n marks=pytest.mark.skipif(\n not check_module_available(\"flashinfer\"),\n reason=\"flashinfer executor is not available on this device\",\n ),\n )\n ],\n)\n@pytest.mark.parametrize(\"size\", generate_input_sizes_rmsnorm_add(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_add_fwd_baseline_benchmark(\n benchmark,","source_hash":"97d2303f237539385d3a74041f54c0537965f0686e792c5d35b9ae83cff8613c","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_add_fwd.test_rmsnorm_add_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_add_fwd.test_rmsnorm_add_fwd_baseline_benchmark#L84-L105","kind":"function","name":"test_rmsnorm_add_fwd_baseline_benchmark","path":"benchmarks/python/test_rmsnorm_add_fwd.py","language":"python","start_line":84,"end_line":105,"context_start_line":64,"context_end_line":105,"code":" fused_add_rmsnorm(inputs, residual, weights)\n return inputs, residual\n\n\n@pytest.mark.parametrize(\n \"executor\",\n DEFAULT_EXECUTORS\n + [\n pytest.param(\n \"flashinfer\",\n marks=pytest.mark.skipif(\n not check_module_available(\"flashinfer\"),\n reason=\"flashinfer executor is not available on this device\",\n ),\n )\n ],\n)\n@pytest.mark.parametrize(\"size\", generate_input_sizes_rmsnorm_add(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_add_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=False)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=False)\n residual = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=False)\n # requires flashinfer to be installed\n # `pip install flashinfer-python` works in pjnl container\n if executor == \"flashinfer\":\n benchmark_fn = flashinfer_rmsnorm_add_wrapper\n else:\n benchmark_fn = with_executor(executor, rmsnorm_add)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, weights, residual],\n )","source_hash":"97d2303f237539385d3a74041f54c0537965f0686e792c5d35b9ae83cff8613c","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest","uri":"program://Fuser/module/benchmarks.python.conftest#L1-L210","kind":"module","name":"benchmarks.python.conftest","path":"benchmarks/python/conftest.py","language":"python","start_line":1,"end_line":210,"context_start_line":1,"context_end_line":210,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .core import BENCHMARK_CONFIG\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\nimport os\n\nORIGINAL_ENV_VARS = {}\n\n\ndef pytest_sessionstart(session):\n for var, value in [\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\", \"1\"),\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\", \"1\"),\n ]:\n ORIGINAL_ENV_VARS[var] = os.environ.get(var)\n os.environ[var] = value\n\n\ndef pytest_sessionfinish(session):\n for var, value in ORIGINAL_ENV_VARS.items():\n if value is not None:\n os.environ[var] = value\n else:\n os.environ.pop(var, None)\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--disable-validation\",\n action=\"store_true\",\n help=\"Disable output validation in benchmarks.\",\n )\n parser.addoption(\n \"--disable-benchmarking\",\n action=\"store_true\",\n help=\"Disable benchmarking.\",\n )\n parser.addoption(\n \"--benchmark-eager\",\n action=\"store_true\",\n help=\"Benchmarks torch eager mode.\",\n )\n parser.addoption(\n \"--benchmark-thunder\",\n action=\"store_true\",\n help=\"Benchmarks thunder jit.\",\n )\n parser.addoption(\n \"--benchmark-torchcompile\",\n action=\"store_true\",\n help=\"Benchmarks torch.compile mode.\",\n )\n parser.addoption(\n \"--benchmark-thunder-torchcompile\",\n action=\"store_true\",\n help=\"Benchmarks torch.compile mode.\",\n )\n parser.addoption(\n \"--benchmark-flashinfer\",\n action=\"store_true\",\n help=\"Benchmarks flashinfer mode.\",\n )\n parser.addoption(\n \"--benchmark-quack\",\n action=\"store_true\",\n help=\"Benchmarks quack mode.\",\n )\n # pytest-benchmark does not have CLI options to set rounds/warmup_rounds for benchmark.pedantic.\n # The following two options are used to overwrite the default values through CLI.\n parser.addoption(\n \"--benchmark-rounds\",\n action=\"store\",\n default=10,\n help=\"Number of rounds for each benchmark.\",\n )\n\n parser.addoption(\n \"--benchmark-warmup-rounds\",\n action=\"store\",\n default=1,\n help=\"Number of warmup rounds for each benchmark.\",\n )\n\n parser.addoption(\n \"--benchmark-num-inputs\",\n action=\"store\",\n default=None,\n help=\"Number of inputs to randomly sample for each benchmark.\",\n )\n\n parser.addoption(\n \"--with-nsys\",\n action=\"store_true\",\n default=False,\n help=\"Run benchmark scripts with nsys. Disable all other profilers.\",\n )\n\n\n@pytest.fixture\ndef disable_validation(request):\n return request.config.getoption(\"--disable-validation\")\n\n\n@pytest.fixture\ndef disable_benchmarking(request):\n return request.config.getoption(\"--disable-benchmarking\")\n\n\ndef pytest_make_parametrize_id(val, argname):\n if isinstance(val, tuple):\n return f'{argname}=[{\"_\".join(str(v) for v in val)}]'\n return f\"{argname}={repr(val)}\"\n\n\ndef pytest_benchmark_update_machine_info(config, machine_info):\n machine_info.update(DEVICE_PROPERTIES)\n\n\ndef pytest_configure(config):\n BENCHMARK_CONFIG[\"rounds\"] = int(config.getoption(\"--benchmark-rounds\"))\n BENCHMARK_CONFIG[\"warmup_rounds\"] = int(\n config.getoption(\"--benchmark-warmup-rounds\")\n )\n BENCHMARK_CONFIG[\"with_nsys\"] = config.getoption(\"--with-nsys\")\n\n if config.getoption(\"--benchmark-num-inputs\"):\n BENCHMARK_CONFIG[\"num_inputs\"] = int(config.getoption(\"--benchmark-num-inputs\"))\n\n # Scheduler markers may become stale and are not 100% accurate.\n config.addinivalue_line(\n \"markers\",\n \"inner_outer_persistent: mark tests using inner_outer_persistent scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"inner_persistent: mark tests using inner_persistent scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"outer_persistent: mark tests using outer_persistent scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"reduction: mark tests using reduction scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"matmul: mark tests using matmul scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"resize: mark tests using resize scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"transpose: mark tests using transpose scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"pointwise: mark tests using pointwise scheduler if not being segmented.\",\n )\n\n\ndef pytest_collection_modifyitems(session, config, items):\n \"\"\"\n The baseline benchmarks use `executor` parameter with\n values [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"] that are optionally\n run using `--benchmark-{executor}` flag. They are skipped by\n default.\n \"\"\"\n\n from nvfuser_direct.pytorch_utils import retry_on_oom_or_skip_test\n\n executors = [\n \"eager\",\n \"torchcompile\",\n \"thunder\",\n \"thunder-torchcompile\",\n \"flashinfer\",\n \"quack\",\n ]\n\n def get_test_executor(item) -> str | None:\n if hasattr(item, \"callspec\") and \"executor\" in item.callspec.params:\n test_executor = item.callspec.params[\"executor\"]\n assert (\n test_executor in executors\n ), f\"Expected executor to be one of 'eager', 'torchcompile', 'thunder', 'thunder-torchcompile', found {test_executor}.\"\n return test_executor\n return None\n\n executors_to_skip = []\n\n for executor in executors:\n if not config.getoption(f\"--benchmark-{executor}\"):\n executors_to_skip.append(executor)\n\n for item in items:\n item.obj = retry_on_oom_or_skip_test(item.obj)\n\n test_executor = get_test_executor(item)\n\n if test_executor is not None and test_executor in executors_to_skip:\n item.add_marker(\n pytest.mark.skip(\n reason=f\"need --benchmark-{test_executor} option to run.\"\n )\n )","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.pytest_sessionstart","uri":"program://Fuser/function/benchmarks.python.conftest.pytest_sessionstart#L12-L18","kind":"function","name":"pytest_sessionstart","path":"benchmarks/python/conftest.py","language":"python","start_line":12,"end_line":18,"context_start_line":1,"context_end_line":38,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .core import BENCHMARK_CONFIG\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\nimport os\n\nORIGINAL_ENV_VARS = {}\n\n\ndef pytest_sessionstart(session):\n for var, value in [\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\", \"1\"),\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\", \"1\"),\n ]:\n ORIGINAL_ENV_VARS[var] = os.environ.get(var)\n os.environ[var] = value\n\n\ndef pytest_sessionfinish(session):\n for var, value in ORIGINAL_ENV_VARS.items():\n if value is not None:\n os.environ[var] = value\n else:\n os.environ.pop(var, None)\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--disable-validation\",\n action=\"store_true\",\n help=\"Disable output validation in benchmarks.\",\n )\n parser.addoption(\n \"--disable-benchmarking\",\n action=\"store_true\",\n help=\"Disable benchmarking.\",","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.pytest_sessionfinish","uri":"program://Fuser/function/benchmarks.python.conftest.pytest_sessionfinish#L21-L26","kind":"function","name":"pytest_sessionfinish","path":"benchmarks/python/conftest.py","language":"python","start_line":21,"end_line":26,"context_start_line":1,"context_end_line":46,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .core import BENCHMARK_CONFIG\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\nimport os\n\nORIGINAL_ENV_VARS = {}\n\n\ndef pytest_sessionstart(session):\n for var, value in [\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\", \"1\"),\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\", \"1\"),\n ]:\n ORIGINAL_ENV_VARS[var] = os.environ.get(var)\n os.environ[var] = value\n\n\ndef pytest_sessionfinish(session):\n for var, value in ORIGINAL_ENV_VARS.items():\n if value is not None:\n os.environ[var] = value\n else:\n os.environ.pop(var, None)\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--disable-validation\",\n action=\"store_true\",\n help=\"Disable output validation in benchmarks.\",\n )\n parser.addoption(\n \"--disable-benchmarking\",\n action=\"store_true\",\n help=\"Disable benchmarking.\",\n )\n parser.addoption(\n \"--benchmark-eager\",\n action=\"store_true\",\n help=\"Benchmarks torch eager mode.\",\n )\n parser.addoption(\n \"--benchmark-thunder\",","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.pytest_addoption","uri":"program://Fuser/function/benchmarks.python.conftest.pytest_addoption#L29-L98","kind":"function","name":"pytest_addoption","path":"benchmarks/python/conftest.py","language":"python","start_line":29,"end_line":98,"context_start_line":9,"context_end_line":118,"code":"ORIGINAL_ENV_VARS = {}\n\n\ndef pytest_sessionstart(session):\n for var, value in [\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\", \"1\"),\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\", \"1\"),\n ]:\n ORIGINAL_ENV_VARS[var] = os.environ.get(var)\n os.environ[var] = value\n\n\ndef pytest_sessionfinish(session):\n for var, value in ORIGINAL_ENV_VARS.items():\n if value is not None:\n os.environ[var] = value\n else:\n os.environ.pop(var, None)\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--disable-validation\",\n action=\"store_true\",\n help=\"Disable output validation in benchmarks.\",\n )\n parser.addoption(\n \"--disable-benchmarking\",\n action=\"store_true\",\n help=\"Disable benchmarking.\",\n )\n parser.addoption(\n \"--benchmark-eager\",\n action=\"store_true\",\n help=\"Benchmarks torch eager mode.\",\n )\n parser.addoption(\n \"--benchmark-thunder\",\n action=\"store_true\",\n help=\"Benchmarks thunder jit.\",\n )\n parser.addoption(\n \"--benchmark-torchcompile\",\n action=\"store_true\",\n help=\"Benchmarks torch.compile mode.\",\n )\n parser.addoption(\n \"--benchmark-thunder-torchcompile\",\n action=\"store_true\",\n help=\"Benchmarks torch.compile mode.\",\n )\n parser.addoption(\n \"--benchmark-flashinfer\",\n action=\"store_true\",\n help=\"Benchmarks flashinfer mode.\",\n )\n parser.addoption(\n \"--benchmark-quack\",\n action=\"store_true\",\n help=\"Benchmarks quack mode.\",\n )\n # pytest-benchmark does not have CLI options to set rounds/warmup_rounds for benchmark.pedantic.\n # The following two options are used to overwrite the default values through CLI.\n parser.addoption(\n \"--benchmark-rounds\",\n action=\"store\",\n default=10,\n help=\"Number of rounds for each benchmark.\",\n )\n\n parser.addoption(\n \"--benchmark-warmup-rounds\",\n action=\"store\",\n default=1,\n help=\"Number of warmup rounds for each benchmark.\",\n )\n\n parser.addoption(\n \"--benchmark-num-inputs\",\n action=\"store\",\n default=None,\n help=\"Number of inputs to randomly sample for each benchmark.\",\n )\n\n parser.addoption(\n \"--with-nsys\",\n action=\"store_true\",\n default=False,\n help=\"Run benchmark scripts with nsys. Disable all other profilers.\",\n )\n\n\n@pytest.fixture\ndef disable_validation(request):\n return request.config.getoption(\"--disable-validation\")\n\n\n@pytest.fixture\ndef disable_benchmarking(request):\n return request.config.getoption(\"--disable-benchmarking\")\n\n\ndef pytest_make_parametrize_id(val, argname):\n if isinstance(val, tuple):\n return f'{argname}=[{\"_\".join(str(v) for v in val)}]'\n return f\"{argname}={repr(val)}\"\n\n\ndef pytest_benchmark_update_machine_info(config, machine_info):\n machine_info.update(DEVICE_PROPERTIES)","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.disable_validation","uri":"program://Fuser/function/benchmarks.python.conftest.disable_validation#L102-L103","kind":"function","name":"disable_validation","path":"benchmarks/python/conftest.py","language":"python","start_line":102,"end_line":103,"context_start_line":82,"context_end_line":123,"code":" default=1,\n help=\"Number of warmup rounds for each benchmark.\",\n )\n\n parser.addoption(\n \"--benchmark-num-inputs\",\n action=\"store\",\n default=None,\n help=\"Number of inputs to randomly sample for each benchmark.\",\n )\n\n parser.addoption(\n \"--with-nsys\",\n action=\"store_true\",\n default=False,\n help=\"Run benchmark scripts with nsys. Disable all other profilers.\",\n )\n\n\n@pytest.fixture\ndef disable_validation(request):\n return request.config.getoption(\"--disable-validation\")\n\n\n@pytest.fixture\ndef disable_benchmarking(request):\n return request.config.getoption(\"--disable-benchmarking\")\n\n\ndef pytest_make_parametrize_id(val, argname):\n if isinstance(val, tuple):\n return f'{argname}=[{\"_\".join(str(v) for v in val)}]'\n return f\"{argname}={repr(val)}\"\n\n\ndef pytest_benchmark_update_machine_info(config, machine_info):\n machine_info.update(DEVICE_PROPERTIES)\n\n\ndef pytest_configure(config):\n BENCHMARK_CONFIG[\"rounds\"] = int(config.getoption(\"--benchmark-rounds\"))\n BENCHMARK_CONFIG[\"warmup_rounds\"] = int(","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.disable_benchmarking","uri":"program://Fuser/function/benchmarks.python.conftest.disable_benchmarking#L107-L108","kind":"function","name":"disable_benchmarking","path":"benchmarks/python/conftest.py","language":"python","start_line":107,"end_line":108,"context_start_line":87,"context_end_line":128,"code":" \"--benchmark-num-inputs\",\n action=\"store\",\n default=None,\n help=\"Number of inputs to randomly sample for each benchmark.\",\n )\n\n parser.addoption(\n \"--with-nsys\",\n action=\"store_true\",\n default=False,\n help=\"Run benchmark scripts with nsys. Disable all other profilers.\",\n )\n\n\n@pytest.fixture\ndef disable_validation(request):\n return request.config.getoption(\"--disable-validation\")\n\n\n@pytest.fixture\ndef disable_benchmarking(request):\n return request.config.getoption(\"--disable-benchmarking\")\n\n\ndef pytest_make_parametrize_id(val, argname):\n if isinstance(val, tuple):\n return f'{argname}=[{\"_\".join(str(v) for v in val)}]'\n return f\"{argname}={repr(val)}\"\n\n\ndef pytest_benchmark_update_machine_info(config, machine_info):\n machine_info.update(DEVICE_PROPERTIES)\n\n\ndef pytest_configure(config):\n BENCHMARK_CONFIG[\"rounds\"] = int(config.getoption(\"--benchmark-rounds\"))\n BENCHMARK_CONFIG[\"warmup_rounds\"] = int(\n config.getoption(\"--benchmark-warmup-rounds\")\n )\n BENCHMARK_CONFIG[\"with_nsys\"] = config.getoption(\"--with-nsys\")\n\n if config.getoption(\"--benchmark-num-inputs\"):","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.pytest_make_parametrize_id","uri":"program://Fuser/function/benchmarks.python.conftest.pytest_make_parametrize_id#L111-L114","kind":"function","name":"pytest_make_parametrize_id","path":"benchmarks/python/conftest.py","language":"python","start_line":111,"end_line":114,"context_start_line":91,"context_end_line":134,"code":" )\n\n parser.addoption(\n \"--with-nsys\",\n action=\"store_true\",\n default=False,\n help=\"Run benchmark scripts with nsys. Disable all other profilers.\",\n )\n\n\n@pytest.fixture\ndef disable_validation(request):\n return request.config.getoption(\"--disable-validation\")\n\n\n@pytest.fixture\ndef disable_benchmarking(request):\n return request.config.getoption(\"--disable-benchmarking\")\n\n\ndef pytest_make_parametrize_id(val, argname):\n if isinstance(val, tuple):\n return f'{argname}=[{\"_\".join(str(v) for v in val)}]'\n return f\"{argname}={repr(val)}\"\n\n\ndef pytest_benchmark_update_machine_info(config, machine_info):\n machine_info.update(DEVICE_PROPERTIES)\n\n\ndef pytest_configure(config):\n BENCHMARK_CONFIG[\"rounds\"] = int(config.getoption(\"--benchmark-rounds\"))\n BENCHMARK_CONFIG[\"warmup_rounds\"] = int(\n config.getoption(\"--benchmark-warmup-rounds\")\n )\n BENCHMARK_CONFIG[\"with_nsys\"] = config.getoption(\"--with-nsys\")\n\n if config.getoption(\"--benchmark-num-inputs\"):\n BENCHMARK_CONFIG[\"num_inputs\"] = int(config.getoption(\"--benchmark-num-inputs\"))\n\n # Scheduler markers may become stale and are not 100% accurate.\n config.addinivalue_line(\n \"markers\",\n \"inner_outer_persistent: mark tests using inner_outer_persistent scheduler if not being segmented.\",","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.pytest_benchmark_update_machine_info","uri":"program://Fuser/function/benchmarks.python.conftest.pytest_benchmark_update_machine_info#L117-L118","kind":"function","name":"pytest_benchmark_update_machine_info","path":"benchmarks/python/conftest.py","language":"python","start_line":117,"end_line":118,"context_start_line":97,"context_end_line":138,"code":" help=\"Run benchmark scripts with nsys. Disable all other profilers.\",\n )\n\n\n@pytest.fixture\ndef disable_validation(request):\n return request.config.getoption(\"--disable-validation\")\n\n\n@pytest.fixture\ndef disable_benchmarking(request):\n return request.config.getoption(\"--disable-benchmarking\")\n\n\ndef pytest_make_parametrize_id(val, argname):\n if isinstance(val, tuple):\n return f'{argname}=[{\"_\".join(str(v) for v in val)}]'\n return f\"{argname}={repr(val)}\"\n\n\ndef pytest_benchmark_update_machine_info(config, machine_info):\n machine_info.update(DEVICE_PROPERTIES)\n\n\ndef pytest_configure(config):\n BENCHMARK_CONFIG[\"rounds\"] = int(config.getoption(\"--benchmark-rounds\"))\n BENCHMARK_CONFIG[\"warmup_rounds\"] = int(\n config.getoption(\"--benchmark-warmup-rounds\")\n )\n BENCHMARK_CONFIG[\"with_nsys\"] = config.getoption(\"--with-nsys\")\n\n if config.getoption(\"--benchmark-num-inputs\"):\n BENCHMARK_CONFIG[\"num_inputs\"] = int(config.getoption(\"--benchmark-num-inputs\"))\n\n # Scheduler markers may become stale and are not 100% accurate.\n config.addinivalue_line(\n \"markers\",\n \"inner_outer_persistent: mark tests using inner_outer_persistent scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"inner_persistent: mark tests using inner_persistent scheduler if not being segmented.\",","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.pytest_configure","uri":"program://Fuser/function/benchmarks.python.conftest.pytest_configure#L121-L163","kind":"function","name":"pytest_configure","path":"benchmarks/python/conftest.py","language":"python","start_line":121,"end_line":163,"context_start_line":101,"context_end_line":183,"code":"@pytest.fixture\ndef disable_validation(request):\n return request.config.getoption(\"--disable-validation\")\n\n\n@pytest.fixture\ndef disable_benchmarking(request):\n return request.config.getoption(\"--disable-benchmarking\")\n\n\ndef pytest_make_parametrize_id(val, argname):\n if isinstance(val, tuple):\n return f'{argname}=[{\"_\".join(str(v) for v in val)}]'\n return f\"{argname}={repr(val)}\"\n\n\ndef pytest_benchmark_update_machine_info(config, machine_info):\n machine_info.update(DEVICE_PROPERTIES)\n\n\ndef pytest_configure(config):\n BENCHMARK_CONFIG[\"rounds\"] = int(config.getoption(\"--benchmark-rounds\"))\n BENCHMARK_CONFIG[\"warmup_rounds\"] = int(\n config.getoption(\"--benchmark-warmup-rounds\")\n )\n BENCHMARK_CONFIG[\"with_nsys\"] = config.getoption(\"--with-nsys\")\n\n if config.getoption(\"--benchmark-num-inputs\"):\n BENCHMARK_CONFIG[\"num_inputs\"] = int(config.getoption(\"--benchmark-num-inputs\"))\n\n # Scheduler markers may become stale and are not 100% accurate.\n config.addinivalue_line(\n \"markers\",\n \"inner_outer_persistent: mark tests using inner_outer_persistent scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"inner_persistent: mark tests using inner_persistent scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"outer_persistent: mark tests using outer_persistent scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"reduction: mark tests using reduction scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"matmul: mark tests using matmul scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"resize: mark tests using resize scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"transpose: mark tests using transpose scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"pointwise: mark tests using pointwise scheduler if not being segmented.\",\n )\n\n\ndef pytest_collection_modifyitems(session, config, items):\n \"\"\"\n The baseline benchmarks use `executor` parameter with\n values [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"] that are optionally\n run using `--benchmark-{executor}` flag. They are skipped by\n default.\n \"\"\"\n\n from nvfuser_direct.pytorch_utils import retry_on_oom_or_skip_test\n\n executors = [\n \"eager\",\n \"torchcompile\",\n \"thunder\",\n \"thunder-torchcompile\",\n \"flashinfer\",\n \"quack\",\n ]","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.pytest_collection_modifyitems","uri":"program://Fuser/function/benchmarks.python.conftest.pytest_collection_modifyitems#L166-L210","kind":"function","name":"pytest_collection_modifyitems","path":"benchmarks/python/conftest.py","language":"python","start_line":166,"end_line":210,"context_start_line":146,"context_end_line":210,"code":" \"reduction: mark tests using reduction scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"matmul: mark tests using matmul scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"resize: mark tests using resize scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"transpose: mark tests using transpose scheduler if not being segmented.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"pointwise: mark tests using pointwise scheduler if not being segmented.\",\n )\n\n\ndef pytest_collection_modifyitems(session, config, items):\n \"\"\"\n The baseline benchmarks use `executor` parameter with\n values [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"] that are optionally\n run using `--benchmark-{executor}` flag. They are skipped by\n default.\n \"\"\"\n\n from nvfuser_direct.pytorch_utils import retry_on_oom_or_skip_test\n\n executors = [\n \"eager\",\n \"torchcompile\",\n \"thunder\",\n \"thunder-torchcompile\",\n \"flashinfer\",\n \"quack\",\n ]\n\n def get_test_executor(item) -> str | None:\n if hasattr(item, \"callspec\") and \"executor\" in item.callspec.params:\n test_executor = item.callspec.params[\"executor\"]\n assert (\n test_executor in executors\n ), f\"Expected executor to be one of 'eager', 'torchcompile', 'thunder', 'thunder-torchcompile', found {test_executor}.\"\n return test_executor\n return None\n\n executors_to_skip = []\n\n for executor in executors:\n if not config.getoption(f\"--benchmark-{executor}\"):\n executors_to_skip.append(executor)\n\n for item in items:\n item.obj = retry_on_oom_or_skip_test(item.obj)\n\n test_executor = get_test_executor(item)\n\n if test_executor is not None and test_executor in executors_to_skip:\n item.add_marker(\n pytest.mark.skip(\n reason=f\"need --benchmark-{test_executor} option to run.\"\n )\n )","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.conftest.get_test_executor","uri":"program://Fuser/function/benchmarks.python.conftest.get_test_executor#L185-L192","kind":"function","name":"get_test_executor","path":"benchmarks/python/conftest.py","language":"python","start_line":185,"end_line":192,"context_start_line":165,"context_end_line":210,"code":"\ndef pytest_collection_modifyitems(session, config, items):\n \"\"\"\n The baseline benchmarks use `executor` parameter with\n values [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"] that are optionally\n run using `--benchmark-{executor}` flag. They are skipped by\n default.\n \"\"\"\n\n from nvfuser_direct.pytorch_utils import retry_on_oom_or_skip_test\n\n executors = [\n \"eager\",\n \"torchcompile\",\n \"thunder\",\n \"thunder-torchcompile\",\n \"flashinfer\",\n \"quack\",\n ]\n\n def get_test_executor(item) -> str | None:\n if hasattr(item, \"callspec\") and \"executor\" in item.callspec.params:\n test_executor = item.callspec.params[\"executor\"]\n assert (\n test_executor in executors\n ), f\"Expected executor to be one of 'eager', 'torchcompile', 'thunder', 'thunder-torchcompile', found {test_executor}.\"\n return test_executor\n return None\n\n executors_to_skip = []\n\n for executor in executors:\n if not config.getoption(f\"--benchmark-{executor}\"):\n executors_to_skip.append(executor)\n\n for item in items:\n item.obj = retry_on_oom_or_skip_test(item.obj)\n\n test_executor = get_test_executor(item)\n\n if test_executor is not None and test_executor in executors_to_skip:\n item.add_marker(\n pytest.mark.skip(\n reason=f\"need --benchmark-{test_executor} option to run.\"\n )\n )","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scatter_reduce","uri":"program://Fuser/module/benchmarks.python.test_scatter_reduce#L1-L100","kind":"module","name":"benchmarks.python.test_scatter_reduce","path":"benchmarks/python/test_scatter_reduce.py","language":"python","start_line":1,"end_line":100,"context_start_line":1,"context_end_line":100,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\n\nimport torch\n\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nfrom .global_params import FLOAT_DTYPES\nfrom .torch_ops import scatter_reduce\n\n# (top_k, hidden) configurations seen in models.\nTEST_CONFIGS = [\n (8, 7168), # deepseek r1\n]\n\nSEQ_LENGTHS = [\n 1024,\n 2048,\n 3072,\n 4096,\n 8192,\n 12288,\n 16384,\n 20480,\n 24576,\n 28672,\n 32768,\n]\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"topk_hidden\", TEST_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_scatter_reduce_fwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n topk_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n hidden_states = torch.randn(\n (seq_length * topk_hidden[0], topk_hidden[1]), device=\"cuda\", requires_grad=True\n )\n logits = torch.randn(seq_length * topk_hidden[0], device=\"cuda\")\n idxs = logits.argsort()\n topk_weight = torch.randn((seq_length, topk_hidden[0]), device=\"cuda\")\n\n benchmark_fn = with_executor(executor, scatter_reduce, **kwargs)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [hidden_states, idxs, topk_weight],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"topk_hidden\", TEST_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_scatter_reduce_bwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n topk_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n hidden_states = torch.randn(\n (seq_length * topk_hidden[0], topk_hidden[1]), device=\"cuda\", requires_grad=True\n )\n logits = torch.randn(seq_length * topk_hidden[0], device=\"cuda\")\n idxs = logits.argsort()\n topk_weight = torch.randn((seq_length, topk_hidden[0]), device=\"cuda\")\n grads = torch.randn((seq_length, topk_hidden[1]), device=\"cuda\")\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, scatter_reduce, **kwargs)\n fwd_inputs = [hidden_states, idxs, topk_weight]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n )","source_hash":"36771f2fe91ff8589f613c8cabb7d8f5e444e852f5cd76f1fbe0344cebaecc55","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scatter_reduce.test_scatter_reduce_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_scatter_reduce.test_scatter_reduce_fwd_baseline_benchmark#L42-L65","kind":"function","name":"test_scatter_reduce_fwd_baseline_benchmark","path":"benchmarks/python/test_scatter_reduce.py","language":"python","start_line":42,"end_line":65,"context_start_line":22,"context_end_line":85,"code":"\nSEQ_LENGTHS = [\n 1024,\n 2048,\n 3072,\n 4096,\n 8192,\n 12288,\n 16384,\n 20480,\n 24576,\n 28672,\n 32768,\n]\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"topk_hidden\", TEST_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_scatter_reduce_fwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n topk_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n hidden_states = torch.randn(\n (seq_length * topk_hidden[0], topk_hidden[1]), device=\"cuda\", requires_grad=True\n )\n logits = torch.randn(seq_length * topk_hidden[0], device=\"cuda\")\n idxs = logits.argsort()\n topk_weight = torch.randn((seq_length, topk_hidden[0]), device=\"cuda\")\n\n benchmark_fn = with_executor(executor, scatter_reduce, **kwargs)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [hidden_states, idxs, topk_weight],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"topk_hidden\", TEST_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_scatter_reduce_bwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n topk_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n hidden_states = torch.randn(\n (seq_length * topk_hidden[0], topk_hidden[1]), device=\"cuda\", requires_grad=True\n )","source_hash":"36771f2fe91ff8589f613c8cabb7d8f5e444e852f5cd76f1fbe0344cebaecc55","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scatter_reduce.test_scatter_reduce_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_scatter_reduce.test_scatter_reduce_bwd_baseline_benchmark#L72-L100","kind":"function","name":"test_scatter_reduce_bwd_baseline_benchmark","path":"benchmarks/python/test_scatter_reduce.py","language":"python","start_line":72,"end_line":100,"context_start_line":52,"context_end_line":100,"code":"\n hidden_states = torch.randn(\n (seq_length * topk_hidden[0], topk_hidden[1]), device=\"cuda\", requires_grad=True\n )\n logits = torch.randn(seq_length * topk_hidden[0], device=\"cuda\")\n idxs = logits.argsort()\n topk_weight = torch.randn((seq_length, topk_hidden[0]), device=\"cuda\")\n\n benchmark_fn = with_executor(executor, scatter_reduce, **kwargs)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [hidden_states, idxs, topk_weight],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"topk_hidden\", TEST_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_scatter_reduce_bwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n topk_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n hidden_states = torch.randn(\n (seq_length * topk_hidden[0], topk_hidden[1]), device=\"cuda\", requires_grad=True\n )\n logits = torch.randn(seq_length * topk_hidden[0], device=\"cuda\")\n idxs = logits.argsort()\n topk_weight = torch.randn((seq_length, topk_hidden[0]), device=\"cuda\")\n grads = torch.randn((seq_length, topk_hidden[1]), device=\"cuda\")\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, scatter_reduce, **kwargs)\n fwd_inputs = [hidden_states, idxs, topk_weight]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n )","source_hash":"36771f2fe91ff8589f613c8cabb7d8f5e444e852f5cd76f1fbe0344cebaecc55","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat","uri":"program://Fuser/module/benchmarks.python.test_cat#L1-L530","kind":"module","name":"benchmarks.python.test_cat","path":"benchmarks/python/test_cat.py","language":"python","start_line":1,"end_line":530,"context_start_line":1,"context_end_line":530,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom .core import run_benchmark, with_executor\n\n# These tests are sourced from automation added into thunder.\n#\n# To recreate:\n# * Use the tfogal/benchmarking-dumps branch in thunder.\n# * Pass nv_store_fusion_inputs=True to your thunderfx call\n# * Disable the torch.compile executor in the thunderfx call, which ensures\n# that all fusions go to nvFuser.\n# * After running the network of interest, invoke thunder.tests.dump.traces()\n# This particular file is aimed at concatenation operations, so it is an\n# agglomeration of cases that included `torch.cat` in the fusion.\n\n\ndef cat_qwen2_fwd_11(t17353, t17351, cos_2, sin_2, query_states_1, key_states_1):\n # t17353: \"cuda:0 bf16[2048, 512]\"\n # t17351: \"cuda:0 bf16[1, 2048, 512]\"\n # cos_2: \"cuda:0 bf16[1, 2048, 128]\"\n # sin_2: \"cuda:0 bf16[1, 2048, 128]\"\n # query_states_1: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # key_states_1: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t0 = torch.reshape(t17353, (1, 2048, 512)) # t0: \"cuda:0 bf16[1, 2048, 512]\"\n t1 = torch.Tensor.to(t0, torch.float32, copy=True) # t1: \"cuda:0 f32[1, 2048, 512]\"\n # t1 = prims.convert_element_type(t0, dtypes.float32) # t1: \"cuda:0 f32[1, 2048, 512]\"\n t2 = torch.mul(t1, 2.0) # t2: \"cuda:0 f32[1, 2048, 512]\"\n t3 = torch.Tensor.to(\n t17351, torch.float32, copy=True\n ) # t3: \"cuda:0 f32[1, 2048, 512]\"\n # t3 = prims.convert_element_type(t17351, dtypes.float32) # t3: \"cuda:0 f32[1, 2048, 512]\"\n t4 = torch.add(t3, t2) # t4: \"cuda:0 f32[1, 2048, 512]\"\n t5 = torch.Tensor.to(\n t4, torch.bfloat16, copy=True\n ) # t5: \"cuda:0 bf16[1, 2048, 512]\"\n # t5 = prims.convert_element_type(t4, dtypes.bfloat16) # t5: \"cuda:0 bf16[1, 2048, 512]\"\n t6 = torch.reshape(t5, (1, 2048, 4, 128)) # t6: \"cuda:0 bf16[1, 2048, 4, 128]\"\n t7 = torch.permute(t6, (0, 2, 1, 3)) # t7: \"cuda:0 bf16[1, 4, 2048, 128]\"\n # t7 = prims.transpose(t6, (0, 2, 1, 3)) # t7: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t8 = torch.unsqueeze(cos_2, 1) # t8: \"cuda:0 bf16[1, 1, 2048, 128]\"\n # t8 = prims.broadcast_in_dim(cos_2, [1, 1, 2048, 128], [0, 2, 3]) # t8: \"cuda:0 bf16[1, 1, 2048, 128]\"\n t9 = torch.Tensor.expand(\n t8, [1, 1, 2048, 128]\n ) # t9: \"cuda:0 bf16[1, 1, 2048, 128]\"\n # t9 = prims.broadcast_in_dim(t8, (1, 1, 2048, 128), (0, 1, 2, 3)) # t9: \"cuda:0 bf16[1, 1, 2048, 128]\"\n\n t10 = torch.unsqueeze(sin_2, 1) # t10: \"cuda:0 bf16[1, 1, 2048, 128]\"\n # t10 = prims.broadcast_in_dim(sin_2, [1, 1, 2048, 128], [0, 2, 3]) # t10: \"cuda:0 bf16[1, 1, 2048, 128]\"\n t11 = torch.Tensor.expand(\n t10, [1, 1, 2048, 128]\n ) # t11: \"cuda:0 bf16[1, 1, 2048, 128]\"\n # t11 = prims.broadcast_in_dim(t10, (1, 1, 2048, 128), (0, 1, 2, 3)) # t11: \"cuda:0 bf16[1, 1, 2048, 128]\"\n t12 = torch.Tensor.expand(\n t9, (1, 28, 2048, 128)\n ) # t12: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t12 = prims.broadcast_in_dim(t9, (1, 28, 2048, 128), (0, 1, 2, 3)) # t12: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t13 = torch.Tensor.to(\n query_states_1, torch.float32, copy=True\n ) # t13: \"cuda:0 f32[1, 28, 2048, 128]\"\n # t13 = prims.convert_element_type(query_states_1, dtypes.float32) # t13: \"cuda:0 f32[1, 28, 2048, 128]\"\n t14 = torch.Tensor.to(\n t12, torch.float32, copy=True\n ) # t14: \"cuda:0 f32[1, 28, 2048, 128]\"\n # t14 = prims.convert_element_type(t12, dtypes.float32) # t14: \"cuda:0 f32[1, 28, 2048, 128]\"\n t15 = torch.mul(t13, t14) # t15: \"cuda:0 f32[1, 28, 2048, 128]\"\n t16 = query_states_1[0:1, 0:28, 0:2048, 0:64]\n t17 = query_states_1[0:1, 0:28, 0:2048, 64:128]\n # t16 = torch.slice(query_states_1, [0, 0, 0, 0], [1, 28, 2048, 64], [1, 1, 1, 1]) # t16: \"cuda:0 bf16[1, 28, 2048, 64]\"\n # t17 = torch.slice(query_states_1, [0, 0, 0, 64], [1, 28, 2048, 128], [1, 1, 1, 1]) # t17: \"cuda:0 bf16[1, 28, 2048, 64]\"\n t18 = torch.Tensor.to(\n t17, torch.float32, copy=True\n ) # t18: \"cuda:0 f32[1, 28, 2048, 64]\"\n # t18 = prims.convert_element_type(t17, dtypes.float32) # t18: \"cuda:0 f32[1, 28, 2048, 64]\"\n t19 = torch.neg(t18) # t19: \"cuda:0 f32[1, 28, 2048, 64]\"\n t20 = torch.Tensor.to(\n t19, torch.bfloat16, copy=True\n ) # t20: \"cuda:0 bf16[1, 28, 2048, 64]\"\n # t20 = prims.convert_element_type(t19, dtypes.bfloat16) # t20: \"cuda:0 bf16[1, 28, 2048, 64]\"\n t21 = torch.cat([t20, t16], -1) # t21: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t22 = torch.Tensor.expand(\n t11, (1, 28, 2048, 128)\n ) # t22: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t22 = prims.broadcast_in_dim(t11, (1, 28, 2048, 128), (0, 1, 2, 3)) # t22: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t23 = torch.Tensor.to(\n t21, torch.float32, copy=True\n ) # t23: \"cuda:0 f32[1, 28, 2048, 128]\"\n # t23 = prims.convert_element_type(t21, dtypes.float32) # t23: \"cuda:0 f32[1, 28, 2048, 128]\"\n t24 = torch.Tensor.to(\n t22, torch.float32, copy=True\n ) # t24: \"cuda:0 f32[1, 28, 2048, 128]\"\n # t24 = prims.convert_element_type(t22, dtypes.float32) # t24: \"cuda:0 f32[1, 28, 2048, 128]\"\n t25 = torch.mul(t23, t24) # t25: \"cuda:0 f32[1, 28, 2048, 128]\"\n t26 = torch.add(t15, t25) # t26: \"cuda:0 f32[1, 28, 2048, 128]\"\n t27 = torch.Tensor.to(\n t26, torch.bfloat16, copy=True\n ) # t27: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t27 = prims.convert_element_type(t26, dtypes.bfloat16) # t27: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t28 = torch.Tensor.expand(\n t9, (1, 4, 2048, 128)\n ) # t28: \"cuda:0 bf16[1, 4, 2048, 128]\"\n # t28 = prims.broadcast_in_dim(t9, (1, 4, 2048, 128), (0, 1, 2, 3)) # t28: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t29 = torch.Tensor.to(\n key_states_1, torch.float32, copy=True\n ) # t29: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t29 = prims.convert_element_type(key_states_1, dtypes.float32) # t29: \"cuda:0 f32[1, 4, 2048, 128]\"\n t30 = torch.Tensor.to(\n t28, torch.float32, copy=True\n ) # t30: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t30 = prims.convert_element_type(t28, dtypes.float32) # t30: \"cuda:0 f32[1, 4, 2048, 128]\"\n t31 = torch.mul(t29, t30) # t31: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t32 = torch.slice(key_states_1, [0, 0, 0, 0], [1, 4, 2048, 64], [1, 1, 1, 1]) # t32: \"cuda:0 bf16[1, 4, 2048, 64]\"\n # t33 = torch.slice(key_states_1, [0, 0, 0, 64], [1, 4, 2048, 128], [1, 1, 1, 1]) # t33: \"cuda:0 bf16[1, 4, 2048, 64]\"\n t32 = key_states_1[0:1, 0:4, 0:2048, 0:64]\n t33 = key_states_1[0:1, 0:4, 0:2048, 64:128]\n t34 = torch.Tensor.to(\n t33, torch.float32, copy=True\n ) # t34: \"cuda:0 f32[1, 4, 2048, 64]\"\n # t34 = prims.convert_element_type(t33, dtypes.float32) # t34: \"cuda:0 f32[1, 4, 2048, 64]\"\n t35 = torch.neg(t34) # t35: \"cuda:0 f32[1, 4, 2048, 64]\"\n t36 = torch.Tensor.to(\n t35, torch.bfloat16, copy=True\n ) # t36: \"cuda:0 bf16[1, 4, 2048, 64]\"\n # t36 = prims.convert_element_type(t35, dtypes.bfloat16) # t36: \"cuda:0 bf16[1, 4, 2048, 64]\"\n t37 = torch.cat([t36, t32], -1) # t37: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t38 = torch.Tensor.expand(\n t11, (1, 4, 2048, 128)\n ) # t38: \"cuda:0 bf16[1, 4, 2048, 128]\"\n # t38 = prims.broadcast_in_dim(t11, (1, 4, 2048, 128), (0, 1, 2, 3)) # t38: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t39 = torch.Tensor.to(\n t37, torch.float32, copy=True\n ) # t39: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t39 = prims.convert_element_type(t37, dtypes.float32) # t39: \"cuda:0 f32[1, 4, 2048, 128]\"\n t40 = torch.Tensor.to(\n t38, torch.float32, copy=True\n ) # t40: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t40 = prims.convert_element_type(t38, dtypes.float32) # t40: \"cuda:0 f32[1, 4, 2048, 128]\"\n t41 = torch.mul(t39, t40) # t41: \"cuda:0 f32[1, 4, 2048, 128]\"\n t42 = torch.add(t31, t41) # t42: \"cuda:0 f32[1, 4, 2048, 128]\"\n t43 = torch.Tensor.to(\n t42, torch.bfloat16, copy=True\n ) # t43: \"cuda:0 bf16[1, 4, 2048, 128]\"\n # t43 = prims.convert_element_type(t42, dtypes.bfloat16) # t43: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t44 = torch.unsqueeze(t43, 2) # t44: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n # t44 = prims.broadcast_in_dim(t43, [1, 4, 1, 2048, 128], [0, 1, 3, 4]) # t44: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n t45 = torch.Tensor.expand(\n t44, [1, 4, 1, 2048, 128]\n ) # t45: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n # t45 = prims.broadcast_in_dim(t44, (1, 4, 1, 2048, 128), (0, 1, 2, 3, 4)) # t45: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n t46 = torch.Tensor.expand(\n t45, (1, 4, 7, 2048, 128)\n ) # t46: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n # t46 = prims.broadcast_in_dim(t45, (1, 4, 7, 2048, 128), (0, 1, 2, 3, 4)) # t46: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n t47 = torch.reshape(t46, (1, 28, 2048, 128)) # t47: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t48 = torch.unsqueeze(t7, 2) # t48: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n # t48 = prims.broadcast_in_dim(t7, [1, 4, 1, 2048, 128], [0, 1, 3, 4]) # t48: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n t49 = torch.Tensor.expand(\n t48, [1, 4, 1, 2048, 128]\n ) # t49: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n # t49 = prims.broadcast_in_dim(t48, (1, 4, 1, 2048, 128), (0, 1, 2, 3, 4)) # t49: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n t50 = torch.Tensor.expand(\n t49, (1, 4, 7, 2048, 128)\n ) # t50: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n # t50 = prims.broadcast_in_dim(t49, (1, 4, 7, 2048, 128), (0, 1, 2, 3, 4)) # t50: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n t51 = torch.reshape(t50, (1, 28, 2048, 128)) # t51: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t52 = torch_stride_order_prim_impl(t27, (3, 2, 1, 0)) # t52: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t53 = torch_stride_order_prim_impl(t47, (3, 2, 1, 0)) # t53: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t54 = torch_stride_order_prim_impl(t51, (3, 2, 1, 0)) # t54: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t52 = torch.as_strided(t27, (1, 28, 2048, 128), (7340032, 7340032, 262144, 128))\n t53 = torch.as_strided(t47, (1, 28, 2048, 128), (7340032, 7340032, 262144, 128))\n t54 = torch.as_strided(t51, (1, 28, 2048, 128), (7340032, 7340032, 262144, 128))\n return [t7, t43, t52, t53, t54]\n\n\n# Unfortunately Thunder does not support 'torch.as_strided' yet; until it\n# does, we use this manual nvFuser definition.\ndef cat_qwen2_fwd_11_fusion(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2048, 512],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 2048, 512],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T3 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T4 = fd.define_tensor(\n shape=[1, 28, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T5 = fd.define_tensor(\n shape=[1, 4, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T10 = fd.ops.reshape(T0, new_shape=[1, 2048, 512])\n T11 = fd.ops.cast(T10, dtype=DataType.Float)\n S12 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T13 = fd.ops.mul(T11, S12)\n T14 = fd.ops.cast(T1, dtype=DataType.Float)\n T15 = fd.ops.add(T14, T13)\n T16 = fd.ops.cast(T15, dtype=DataType.BFloat16)\n T22 = fd.ops.reshape(T16, new_shape=[1, 2048, 4, 128])\n T23 = fd.ops.permute(T22, dims=[0, 2, 1, 3])\n T29 = fd.ops.broadcast_in_dim(T2, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3])\n T35 = fd.ops.broadcast_in_dim(T3, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3])\n T41 = fd.ops.broadcast_in_dim(\n T29, shape=[1, 28, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T42 = fd.ops.cast(T4, dtype=DataType.Float)\n T43 = fd.ops.cast(T41, dtype=DataType.Float)\n T44 = fd.ops.mul(T42, T43)\n T60 = fd.ops.slice(\n T4,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 28, 2048, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T76 = fd.ops.slice(\n T4,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 28, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T77 = fd.ops.cast(T76, dtype=DataType.Float)\n T78 = fd.ops.neg(T77)\n T79 = fd.ops.cast(T78, dtype=DataType.BFloat16)\n T80 = fd.ops.cat([T79, T60], dim=-1, manual_padding=0)\n T86 = fd.ops.broadcast_in_dim(\n T35, shape=[1, 28, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T87 = fd.ops.cast(T80, dtype=DataType.Float)\n T88 = fd.ops.cast(T86, dtype=DataType.Float)\n T89 = fd.ops.mul(T87, T88)\n T90 = fd.ops.add(T44, T89)\n T91 = fd.ops.cast(T90, dtype=DataType.BFloat16)\n T97 = fd.ops.broadcast_in_dim(\n T29, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T98 = fd.ops.cast(T5, dtype=DataType.Float)\n T99 = fd.ops.cast(T97, dtype=DataType.Float)\n T100 = fd.ops.mul(T98, T99)\n T116 = fd.ops.slice(\n T5,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 4, 2048, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T132 = fd.ops.slice(\n T5,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 4, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T133 = fd.ops.cast(T132, dtype=DataType.Float)\n T134 = fd.ops.neg(T133)\n T135 = fd.ops.cast(T134, dtype=DataType.BFloat16)\n T136 = fd.ops.cat([T135, T116], dim=-1, manual_padding=0)\n T142 = fd.ops.broadcast_in_dim(\n T35, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T143 = fd.ops.cast(T136, dtype=DataType.Float)\n T144 = fd.ops.cast(T142, dtype=DataType.Float)\n T145 = fd.ops.mul(T143, T144)\n T146 = fd.ops.add(T100, T145)\n T147 = fd.ops.cast(T146, dtype=DataType.BFloat16)\n T154 = fd.ops.broadcast_in_dim(\n T147, shape=[1, 4, 1, 2048, 128], broadcast_dims=[0, 1, 3, 4]\n )\n T161 = fd.ops.broadcast_in_dim(\n T154, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T167 = fd.ops.reshape(T161, new_shape=[1, 28, 2048, 128])\n T174 = fd.ops.broadcast_in_dim(\n T23, shape=[1, 4, 1, 2048, 128], broadcast_dims=[0, 1, 3, 4]\n )\n T181 = fd.ops.broadcast_in_dim(\n T174, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T187 = fd.ops.reshape(T181, new_shape=[1, 28, 2048, 128])\n T188 = fd.ops.stride_order(T91, stride_order=[3, 2, 1, 0])\n T189 = fd.ops.stride_order(T167, stride_order=[3, 2, 1, 0])\n T190 = fd.ops.stride_order(T187, stride_order=[3, 2, 1, 0])\n fd.add_output(T23)\n fd.add_output(T147)\n fd.add_output(T188)\n fd.add_output(T189)\n fd.add_output(T190)\n\n\ndef get_cat_qwen2_inputs() -> list[torch.Tensor]:\n inputs = [\n torch.randn(\n size=(2048, 512), dtype=torch.bfloat16, device=\"cuda\", requires_grad=False\n ).as_strided((2048, 512), (512, 1)),\n torch.randn(\n size=(1, 2048, 512),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 2048, 512), (1048576, 512, 1)),\n torch.randn(\n size=(1, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 2048, 128), (262144, 1, 2048)),\n torch.randn(\n size=(1, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 2048, 128), (262144, 1, 2048)),\n torch.randn(\n size=(1, 28, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 28, 2048, 128), (7340032, 128, 3584, 1)),\n torch.randn(\n size=(1, 4, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 4, 2048, 128), (1048576, 128, 512, 1)),\n ]\n return inputs\n\n\ndef test_cat_qwen2_fwd_11_nvf_benchmark(\n benchmark, disable_validation: bool, disable_benchmarking: bool\n):\n with FusionDefinition() as fd:\n cat_qwen2_fwd_11_fusion(fd)\n\n inputs = get_cat_qwen2_inputs()\n\n def benchmark_fn(inputs):\n return fd.execute(inputs)\n\n if not disable_validation:\n # torch.compile required; works around an issue in eager mode.\n tc = torch.compile(cat_qwen2_fwd_11)\n reference = tc(*inputs)\n # Temporarily disabled: leads to an illegal memory access.\n if False:\n fd.validate(inputs, reference)\n if not disable_benchmarking:\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n# Qwen2 fusion that involves concatenation. Note that there are no Mistral-Nemo\n# benchmarks in this file, because they were all equivalent to this fusion. The\n# fusion below appears repeatedly in both networks.\n#\n# The numbers are arbitrary; this was the 11th fusion in the forward pass.\n#\n# We don't use a \"thunder\" executor here because thunder cannot accept the\n# torch.as_strided call yet. There's a separate benchmark for thunder for now.\n@pytest.mark.parametrize(\"executor\", [\"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_qwen2_fwd_11_baseline_benchmark(benchmark, executor: str) -> None:\n inputs = get_cat_qwen2_inputs()\n\n def benchmark_fn(inputs):\n return cat_qwen2_fwd_11(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", [\"thunder\", \"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_phi3_1_baseline_benchmark(\n benchmark, executor: str, disable_validation: bool\n) -> None:\n def to_be_compiled(t14):\n # t14: \"cuda:0 f32[1, 48, 2048]\"\n t0 = torch.permute(t14, (0, 2, 1)) # t0: \"cuda:0 f32[1, 2048, 48]\"\n # t0 = prims.transpose(t14, (0, 2, 1)) # t0: \"cuda:0 f32[1, 2048, 48]\"\n t1 = torch.cat([t0, t0], -1) # t1: \"cuda:0 f32[1, 2048, 96]\"\n t2 = torch.cos(t1) # t2: \"cuda:0 f32[1, 2048, 96]\"\n t3 = torch.sin(t1) # t3: \"cuda:0 f32[1, 2048, 96]\"\n t4 = torch.mul(t2, 1.1902380714238083) # t4: \"cuda:0 f32[1, 2048, 96]\"\n t5 = torch.mul(t3, 1.1902380714238083) # t5: \"cuda:0 f32[1, 2048, 96]\"\n t6 = torch.Tensor.to(\n t4, torch.bfloat16, copy=True\n ) # t6: \"cuda:0 bf16[1, 2048, 96]\"\n # t6 = prims.convert_element_type(t4, dtypes.bfloat16) # t6: \"cuda:0 bf16[1, 2048, 96]\"\n t7 = torch.Tensor.to(\n t5, torch.bfloat16, copy=True\n ) # t7: \"cuda:0 bf16[1, 2048, 96]\"\n # t7 = prims.convert_element_type(t5, dtypes.bfloat16) # t7: \"cuda:0 bf16[1, 2048, 96]\"\n return [t6, t7]\n\n inputs = [\n torch.randn(\n size=(1, 48, 2048),\n dtype=torch.float32,\n device=\"cuda\",\n requires_grad=False,\n ),\n ]\n\n def benchmark_fn(inputs):\n return to_be_compiled(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n if not disable_validation and executor == \"thunder\":\n # The FusionDefinition can be pulled from thunder, but `with_executor`\n # hides thunder from us so we need to manually run things to pull the\n # FusionDefinition ourself.\n import thunder\n\n reference_outputs = to_be\n# ... truncated ...","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":true} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.cat_qwen2_fwd_11","uri":"program://Fuser/function/benchmarks.python.test_cat.cat_qwen2_fwd_11#L21-L175","kind":"function","name":"cat_qwen2_fwd_11","path":"benchmarks/python/test_cat.py","language":"python","start_line":21,"end_line":175,"context_start_line":1,"context_end_line":195,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom .core import run_benchmark, with_executor\n\n# These tests are sourced from automation added into thunder.\n#\n# To recreate:\n# * Use the tfogal/benchmarking-dumps branch in thunder.\n# * Pass nv_store_fusion_inputs=True to your thunderfx call\n# * Disable the torch.compile executor in the thunderfx call, which ensures\n# that all fusions go to nvFuser.\n# * After running the network of interest, invoke thunder.tests.dump.traces()\n# This particular file is aimed at concatenation operations, so it is an\n# agglomeration of cases that included `torch.cat` in the fusion.\n\n\ndef cat_qwen2_fwd_11(t17353, t17351, cos_2, sin_2, query_states_1, key_states_1):\n # t17353: \"cuda:0 bf16[2048, 512]\"\n # t17351: \"cuda:0 bf16[1, 2048, 512]\"\n # cos_2: \"cuda:0 bf16[1, 2048, 128]\"\n # sin_2: \"cuda:0 bf16[1, 2048, 128]\"\n # query_states_1: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # key_states_1: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t0 = torch.reshape(t17353, (1, 2048, 512)) # t0: \"cuda:0 bf16[1, 2048, 512]\"\n t1 = torch.Tensor.to(t0, torch.float32, copy=True) # t1: \"cuda:0 f32[1, 2048, 512]\"\n # t1 = prims.convert_element_type(t0, dtypes.float32) # t1: \"cuda:0 f32[1, 2048, 512]\"\n t2 = torch.mul(t1, 2.0) # t2: \"cuda:0 f32[1, 2048, 512]\"\n t3 = torch.Tensor.to(\n t17351, torch.float32, copy=True\n ) # t3: \"cuda:0 f32[1, 2048, 512]\"\n # t3 = prims.convert_element_type(t17351, dtypes.float32) # t3: \"cuda:0 f32[1, 2048, 512]\"\n t4 = torch.add(t3, t2) # t4: \"cuda:0 f32[1, 2048, 512]\"\n t5 = torch.Tensor.to(\n t4, torch.bfloat16, copy=True\n ) # t5: \"cuda:0 bf16[1, 2048, 512]\"\n # t5 = prims.convert_element_type(t4, dtypes.bfloat16) # t5: \"cuda:0 bf16[1, 2048, 512]\"\n t6 = torch.reshape(t5, (1, 2048, 4, 128)) # t6: \"cuda:0 bf16[1, 2048, 4, 128]\"\n t7 = torch.permute(t6, (0, 2, 1, 3)) # t7: \"cuda:0 bf16[1, 4, 2048, 128]\"\n # t7 = prims.transpose(t6, (0, 2, 1, 3)) # t7: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t8 = torch.unsqueeze(cos_2, 1) # t8: \"cuda:0 bf16[1, 1, 2048, 128]\"\n # t8 = prims.broadcast_in_dim(cos_2, [1, 1, 2048, 128], [0, 2, 3]) # t8: \"cuda:0 bf16[1, 1, 2048, 128]\"\n t9 = torch.Tensor.expand(\n t8, [1, 1, 2048, 128]\n ) # t9: \"cuda:0 bf16[1, 1, 2048, 128]\"\n # t9 = prims.broadcast_in_dim(t8, (1, 1, 2048, 128), (0, 1, 2, 3)) # t9: \"cuda:0 bf16[1, 1, 2048, 128]\"\n\n t10 = torch.unsqueeze(sin_2, 1) # t10: \"cuda:0 bf16[1, 1, 2048, 128]\"\n # t10 = prims.broadcast_in_dim(sin_2, [1, 1, 2048, 128], [0, 2, 3]) # t10: \"cuda:0 bf16[1, 1, 2048, 128]\"\n t11 = torch.Tensor.expand(\n t10, [1, 1, 2048, 128]\n ) # t11: \"cuda:0 bf16[1, 1, 2048, 128]\"\n # t11 = prims.broadcast_in_dim(t10, (1, 1, 2048, 128), (0, 1, 2, 3)) # t11: \"cuda:0 bf16[1, 1, 2048, 128]\"\n t12 = torch.Tensor.expand(\n t9, (1, 28, 2048, 128)\n ) # t12: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t12 = prims.broadcast_in_dim(t9, (1, 28, 2048, 128), (0, 1, 2, 3)) # t12: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t13 = torch.Tensor.to(\n query_states_1, torch.float32, copy=True\n ) # t13: \"cuda:0 f32[1, 28, 2048, 128]\"\n # t13 = prims.convert_element_type(query_states_1, dtypes.float32) # t13: \"cuda:0 f32[1, 28, 2048, 128]\"\n t14 = torch.Tensor.to(\n t12, torch.float32, copy=True\n ) # t14: \"cuda:0 f32[1, 28, 2048, 128]\"\n # t14 = prims.convert_element_type(t12, dtypes.float32) # t14: \"cuda:0 f32[1, 28, 2048, 128]\"\n t15 = torch.mul(t13, t14) # t15: \"cuda:0 f32[1, 28, 2048, 128]\"\n t16 = query_states_1[0:1, 0:28, 0:2048, 0:64]\n t17 = query_states_1[0:1, 0:28, 0:2048, 64:128]\n # t16 = torch.slice(query_states_1, [0, 0, 0, 0], [1, 28, 2048, 64], [1, 1, 1, 1]) # t16: \"cuda:0 bf16[1, 28, 2048, 64]\"\n # t17 = torch.slice(query_states_1, [0, 0, 0, 64], [1, 28, 2048, 128], [1, 1, 1, 1]) # t17: \"cuda:0 bf16[1, 28, 2048, 64]\"\n t18 = torch.Tensor.to(\n t17, torch.float32, copy=True\n ) # t18: \"cuda:0 f32[1, 28, 2048, 64]\"\n # t18 = prims.convert_element_type(t17, dtypes.float32) # t18: \"cuda:0 f32[1, 28, 2048, 64]\"\n t19 = torch.neg(t18) # t19: \"cuda:0 f32[1, 28, 2048, 64]\"\n t20 = torch.Tensor.to(\n t19, torch.bfloat16, copy=True\n ) # t20: \"cuda:0 bf16[1, 28, 2048, 64]\"\n # t20 = prims.convert_element_type(t19, dtypes.bfloat16) # t20: \"cuda:0 bf16[1, 28, 2048, 64]\"\n t21 = torch.cat([t20, t16], -1) # t21: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t22 = torch.Tensor.expand(\n t11, (1, 28, 2048, 128)\n ) # t22: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t22 = prims.broadcast_in_dim(t11, (1, 28, 2048, 128), (0, 1, 2, 3)) # t22: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t23 = torch.Tensor.to(\n t21, torch.float32, copy=True\n ) # t23: \"cuda:0 f32[1, 28, 2048, 128]\"\n # t23 = prims.convert_element_type(t21, dtypes.float32) # t23: \"cuda:0 f32[1, 28, 2048, 128]\"\n t24 = torch.Tensor.to(\n t22, torch.float32, copy=True\n ) # t24: \"cuda:0 f32[1, 28, 2048, 128]\"\n # t24 = prims.convert_element_type(t22, dtypes.float32) # t24: \"cuda:0 f32[1, 28, 2048, 128]\"\n t25 = torch.mul(t23, t24) # t25: \"cuda:0 f32[1, 28, 2048, 128]\"\n t26 = torch.add(t15, t25) # t26: \"cuda:0 f32[1, 28, 2048, 128]\"\n t27 = torch.Tensor.to(\n t26, torch.bfloat16, copy=True\n ) # t27: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t27 = prims.convert_element_type(t26, dtypes.bfloat16) # t27: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t28 = torch.Tensor.expand(\n t9, (1, 4, 2048, 128)\n ) # t28: \"cuda:0 bf16[1, 4, 2048, 128]\"\n # t28 = prims.broadcast_in_dim(t9, (1, 4, 2048, 128), (0, 1, 2, 3)) # t28: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t29 = torch.Tensor.to(\n key_states_1, torch.float32, copy=True\n ) # t29: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t29 = prims.convert_element_type(key_states_1, dtypes.float32) # t29: \"cuda:0 f32[1, 4, 2048, 128]\"\n t30 = torch.Tensor.to(\n t28, torch.float32, copy=True\n ) # t30: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t30 = prims.convert_element_type(t28, dtypes.float32) # t30: \"cuda:0 f32[1, 4, 2048, 128]\"\n t31 = torch.mul(t29, t30) # t31: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t32 = torch.slice(key_states_1, [0, 0, 0, 0], [1, 4, 2048, 64], [1, 1, 1, 1]) # t32: \"cuda:0 bf16[1, 4, 2048, 64]\"\n # t33 = torch.slice(key_states_1, [0, 0, 0, 64], [1, 4, 2048, 128], [1, 1, 1, 1]) # t33: \"cuda:0 bf16[1, 4, 2048, 64]\"\n t32 = key_states_1[0:1, 0:4, 0:2048, 0:64]\n t33 = key_states_1[0:1, 0:4, 0:2048, 64:128]\n t34 = torch.Tensor.to(\n t33, torch.float32, copy=True\n ) # t34: \"cuda:0 f32[1, 4, 2048, 64]\"\n # t34 = prims.convert_element_type(t33, dtypes.float32) # t34: \"cuda:0 f32[1, 4, 2048, 64]\"\n t35 = torch.neg(t34) # t35: \"cuda:0 f32[1, 4, 2048, 64]\"\n t36 = torch.Tensor.to(\n t35, torch.bfloat16, copy=True\n ) # t36: \"cuda:0 bf16[1, 4, 2048, 64]\"\n # t36 = prims.convert_element_type(t35, dtypes.bfloat16) # t36: \"cuda:0 bf16[1, 4, 2048, 64]\"\n t37 = torch.cat([t36, t32], -1) # t37: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t38 = torch.Tensor.expand(\n t11, (1, 4, 2048, 128)\n ) # t38: \"cuda:0 bf16[1, 4, 2048, 128]\"\n # t38 = prims.broadcast_in_dim(t11, (1, 4, 2048, 128), (0, 1, 2, 3)) # t38: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t39 = torch.Tensor.to(\n t37, torch.float32, copy=True\n ) # t39: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t39 = prims.convert_element_type(t37, dtypes.float32) # t39: \"cuda:0 f32[1, 4, 2048, 128]\"\n t40 = torch.Tensor.to(\n t38, torch.float32, copy=True\n ) # t40: \"cuda:0 f32[1, 4, 2048, 128]\"\n # t40 = prims.convert_element_type(t38, dtypes.float32) # t40: \"cuda:0 f32[1, 4, 2048, 128]\"\n t41 = torch.mul(t39, t40) # t41: \"cuda:0 f32[1, 4, 2048, 128]\"\n t42 = torch.add(t31, t41) # t42: \"cuda:0 f32[1, 4, 2048, 128]\"\n t43 = torch.Tensor.to(\n t42, torch.bfloat16, copy=True\n ) # t43: \"cuda:0 bf16[1, 4, 2048, 128]\"\n # t43 = prims.convert_element_type(t42, dtypes.bfloat16) # t43: \"cuda:0 bf16[1, 4, 2048, 128]\"\n t44 = torch.unsqueeze(t43, 2) # t44: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n # t44 = prims.broadcast_in_dim(t43, [1, 4, 1, 2048, 128], [0, 1, 3, 4]) # t44: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n t45 = torch.Tensor.expand(\n t44, [1, 4, 1, 2048, 128]\n ) # t45: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n # t45 = prims.broadcast_in_dim(t44, (1, 4, 1, 2048, 128), (0, 1, 2, 3, 4)) # t45: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n t46 = torch.Tensor.expand(\n t45, (1, 4, 7, 2048, 128)\n ) # t46: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n # t46 = prims.broadcast_in_dim(t45, (1, 4, 7, 2048, 128), (0, 1, 2, 3, 4)) # t46: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n t47 = torch.reshape(t46, (1, 28, 2048, 128)) # t47: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t48 = torch.unsqueeze(t7, 2) # t48: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n # t48 = prims.broadcast_in_dim(t7, [1, 4, 1, 2048, 128], [0, 1, 3, 4]) # t48: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n t49 = torch.Tensor.expand(\n t48, [1, 4, 1, 2048, 128]\n ) # t49: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n # t49 = prims.broadcast_in_dim(t48, (1, 4, 1, 2048, 128), (0, 1, 2, 3, 4)) # t49: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n t50 = torch.Tensor.expand(\n t49, (1, 4, 7, 2048, 128)\n ) # t50: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n # t50 = prims.broadcast_in_dim(t49, (1, 4, 7, 2048, 128), (0, 1, 2, 3, 4)) # t50: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n t51 = torch.reshape(t50, (1, 28, 2048, 128)) # t51: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t52 = torch_stride_order_prim_impl(t27, (3, 2, 1, 0)) # t52: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t53 = torch_stride_order_prim_impl(t47, (3, 2, 1, 0)) # t53: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t54 = torch_stride_order_prim_impl(t51, (3, 2, 1, 0)) # t54: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t52 = torch.as_strided(t27, (1, 28, 2048, 128), (7340032, 7340032, 262144, 128))\n t53 = torch.as_strided(t47, (1, 28, 2048, 128), (7340032, 7340032, 262144, 128))\n t54 = torch.as_strided(t51, (1, 28, 2048, 128), (7340032, 7340032, 262144, 128))\n return [t7, t43, t52, t53, t54]\n\n\n# Unfortunately Thunder does not support 'torch.as_strided' yet; until it\n# does, we use this manual nvFuser definition.\ndef cat_qwen2_fwd_11_fusion(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2048, 512],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 2048, 512],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.define_tensor(","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.cat_qwen2_fwd_11_fusion","uri":"program://Fuser/function/benchmarks.python.test_cat.cat_qwen2_fwd_11_fusion#L180-L319","kind":"function","name":"cat_qwen2_fwd_11_fusion","path":"benchmarks/python/test_cat.py","language":"python","start_line":180,"end_line":319,"context_start_line":160,"context_end_line":339,"code":" t49 = torch.Tensor.expand(\n t48, [1, 4, 1, 2048, 128]\n ) # t49: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n # t49 = prims.broadcast_in_dim(t48, (1, 4, 1, 2048, 128), (0, 1, 2, 3, 4)) # t49: \"cuda:0 bf16[1, 4, 1, 2048, 128]\"\n t50 = torch.Tensor.expand(\n t49, (1, 4, 7, 2048, 128)\n ) # t50: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n # t50 = prims.broadcast_in_dim(t49, (1, 4, 7, 2048, 128), (0, 1, 2, 3, 4)) # t50: \"cuda:0 bf16[1, 4, 7, 2048, 128]\"\n t51 = torch.reshape(t50, (1, 28, 2048, 128)) # t51: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t52 = torch_stride_order_prim_impl(t27, (3, 2, 1, 0)) # t52: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t53 = torch_stride_order_prim_impl(t47, (3, 2, 1, 0)) # t53: \"cuda:0 bf16[1, 28, 2048, 128]\"\n # t54 = torch_stride_order_prim_impl(t51, (3, 2, 1, 0)) # t54: \"cuda:0 bf16[1, 28, 2048, 128]\"\n t52 = torch.as_strided(t27, (1, 28, 2048, 128), (7340032, 7340032, 262144, 128))\n t53 = torch.as_strided(t47, (1, 28, 2048, 128), (7340032, 7340032, 262144, 128))\n t54 = torch.as_strided(t51, (1, 28, 2048, 128), (7340032, 7340032, 262144, 128))\n return [t7, t43, t52, t53, t54]\n\n\n# Unfortunately Thunder does not support 'torch.as_strided' yet; until it\n# does, we use this manual nvFuser definition.\ndef cat_qwen2_fwd_11_fusion(fd: FusionDefinition) -> None:\n T0 = fd.define_tensor(\n shape=[2048, 512],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[1, 2048, 512],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T2 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T3 = fd.define_tensor(\n shape=[1, 2048, 128],\n contiguity=[None, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[2, 0, 1],\n )\n T4 = fd.define_tensor(\n shape=[1, 28, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T5 = fd.define_tensor(\n shape=[1, 4, 2048, 128],\n contiguity=[None, True, True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[3, 1, 2, 0],\n )\n T10 = fd.ops.reshape(T0, new_shape=[1, 2048, 512])\n T11 = fd.ops.cast(T10, dtype=DataType.Float)\n S12 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T13 = fd.ops.mul(T11, S12)\n T14 = fd.ops.cast(T1, dtype=DataType.Float)\n T15 = fd.ops.add(T14, T13)\n T16 = fd.ops.cast(T15, dtype=DataType.BFloat16)\n T22 = fd.ops.reshape(T16, new_shape=[1, 2048, 4, 128])\n T23 = fd.ops.permute(T22, dims=[0, 2, 1, 3])\n T29 = fd.ops.broadcast_in_dim(T2, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3])\n T35 = fd.ops.broadcast_in_dim(T3, shape=[1, 1, 2048, 128], broadcast_dims=[0, 2, 3])\n T41 = fd.ops.broadcast_in_dim(\n T29, shape=[1, 28, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T42 = fd.ops.cast(T4, dtype=DataType.Float)\n T43 = fd.ops.cast(T41, dtype=DataType.Float)\n T44 = fd.ops.mul(T42, T43)\n T60 = fd.ops.slice(\n T4,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 28, 2048, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T76 = fd.ops.slice(\n T4,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 28, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T77 = fd.ops.cast(T76, dtype=DataType.Float)\n T78 = fd.ops.neg(T77)\n T79 = fd.ops.cast(T78, dtype=DataType.BFloat16)\n T80 = fd.ops.cat([T79, T60], dim=-1, manual_padding=0)\n T86 = fd.ops.broadcast_in_dim(\n T35, shape=[1, 28, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T87 = fd.ops.cast(T80, dtype=DataType.Float)\n T88 = fd.ops.cast(T86, dtype=DataType.Float)\n T89 = fd.ops.mul(T87, T88)\n T90 = fd.ops.add(T44, T89)\n T91 = fd.ops.cast(T90, dtype=DataType.BFloat16)\n T97 = fd.ops.broadcast_in_dim(\n T29, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T98 = fd.ops.cast(T5, dtype=DataType.Float)\n T99 = fd.ops.cast(T97, dtype=DataType.Float)\n T100 = fd.ops.mul(T98, T99)\n T116 = fd.ops.slice(\n T5,\n start_indices=[0, 0, 0, 0],\n end_indices=[1, 4, 2048, 64],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T132 = fd.ops.slice(\n T5,\n start_indices=[0, 0, 0, 64],\n end_indices=[1, 4, 2048, 128],\n strides=[1, 1, 1, 1],\n manual_normalization=0,\n )\n T133 = fd.ops.cast(T132, dtype=DataType.Float)\n T134 = fd.ops.neg(T133)\n T135 = fd.ops.cast(T134, dtype=DataType.BFloat16)\n T136 = fd.ops.cat([T135, T116], dim=-1, manual_padding=0)\n T142 = fd.ops.broadcast_in_dim(\n T35, shape=[1, 4, 2048, 128], broadcast_dims=[0, 1, 2, 3]\n )\n T143 = fd.ops.cast(T136, dtype=DataType.Float)\n T144 = fd.ops.cast(T142, dtype=DataType.Float)\n T145 = fd.ops.mul(T143, T144)\n T146 = fd.ops.add(T100, T145)\n T147 = fd.ops.cast(T146, dtype=DataType.BFloat16)\n T154 = fd.ops.broadcast_in_dim(\n T147, shape=[1, 4, 1, 2048, 128], broadcast_dims=[0, 1, 3, 4]\n )\n T161 = fd.ops.broadcast_in_dim(\n T154, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T167 = fd.ops.reshape(T161, new_shape=[1, 28, 2048, 128])\n T174 = fd.ops.broadcast_in_dim(\n T23, shape=[1, 4, 1, 2048, 128], broadcast_dims=[0, 1, 3, 4]\n )\n T181 = fd.ops.broadcast_in_dim(\n T174, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T187 = fd.ops.reshape(T181, new_shape=[1, 28, 2048, 128])\n T188 = fd.ops.stride_order(T91, stride_order=[3, 2, 1, 0])\n T189 = fd.ops.stride_order(T167, stride_order=[3, 2, 1, 0])\n T190 = fd.ops.stride_order(T187, stride_order=[3, 2, 1, 0])\n fd.add_output(T23)\n fd.add_output(T147)\n fd.add_output(T188)\n fd.add_output(T189)\n fd.add_output(T190)\n\n\ndef get_cat_qwen2_inputs() -> list[torch.Tensor]:\n inputs = [\n torch.randn(\n size=(2048, 512), dtype=torch.bfloat16, device=\"cuda\", requires_grad=False\n ).as_strided((2048, 512), (512, 1)),\n torch.randn(\n size=(1, 2048, 512),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 2048, 512), (1048576, 512, 1)),\n torch.randn(\n size=(1, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 2048, 128), (262144, 1, 2048)),\n torch.randn(","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.get_cat_qwen2_inputs","uri":"program://Fuser/function/benchmarks.python.test_cat.get_cat_qwen2_inputs#L322-L358","kind":"function","name":"get_cat_qwen2_inputs","path":"benchmarks/python/test_cat.py","language":"python","start_line":322,"end_line":358,"context_start_line":302,"context_end_line":378,"code":" T154, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T167 = fd.ops.reshape(T161, new_shape=[1, 28, 2048, 128])\n T174 = fd.ops.broadcast_in_dim(\n T23, shape=[1, 4, 1, 2048, 128], broadcast_dims=[0, 1, 3, 4]\n )\n T181 = fd.ops.broadcast_in_dim(\n T174, shape=[1, 4, 7, 2048, 128], broadcast_dims=[0, 1, 2, 3, 4]\n )\n T187 = fd.ops.reshape(T181, new_shape=[1, 28, 2048, 128])\n T188 = fd.ops.stride_order(T91, stride_order=[3, 2, 1, 0])\n T189 = fd.ops.stride_order(T167, stride_order=[3, 2, 1, 0])\n T190 = fd.ops.stride_order(T187, stride_order=[3, 2, 1, 0])\n fd.add_output(T23)\n fd.add_output(T147)\n fd.add_output(T188)\n fd.add_output(T189)\n fd.add_output(T190)\n\n\ndef get_cat_qwen2_inputs() -> list[torch.Tensor]:\n inputs = [\n torch.randn(\n size=(2048, 512), dtype=torch.bfloat16, device=\"cuda\", requires_grad=False\n ).as_strided((2048, 512), (512, 1)),\n torch.randn(\n size=(1, 2048, 512),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 2048, 512), (1048576, 512, 1)),\n torch.randn(\n size=(1, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 2048, 128), (262144, 1, 2048)),\n torch.randn(\n size=(1, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 2048, 128), (262144, 1, 2048)),\n torch.randn(\n size=(1, 28, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 28, 2048, 128), (7340032, 128, 3584, 1)),\n torch.randn(\n size=(1, 4, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 4, 2048, 128), (1048576, 128, 512, 1)),\n ]\n return inputs\n\n\ndef test_cat_qwen2_fwd_11_nvf_benchmark(\n benchmark, disable_validation: bool, disable_benchmarking: bool\n):\n with FusionDefinition() as fd:\n cat_qwen2_fwd_11_fusion(fd)\n\n inputs = get_cat_qwen2_inputs()\n\n def benchmark_fn(inputs):\n return fd.execute(inputs)\n\n if not disable_validation:\n # torch.compile required; works around an issue in eager mode.\n tc = torch.compile(cat_qwen2_fwd_11)\n reference = tc(*inputs)\n # Temporarily disabled: leads to an illegal memory access.\n if False:\n fd.validate(inputs, reference)","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.test_cat_qwen2_fwd_11_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_cat.test_cat_qwen2_fwd_11_nvf_benchmark#L361-L380","kind":"function","name":"test_cat_qwen2_fwd_11_nvf_benchmark","path":"benchmarks/python/test_cat.py","language":"python","start_line":361,"end_line":380,"context_start_line":341,"context_end_line":400,"code":" dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 2048, 128), (262144, 1, 2048)),\n torch.randn(\n size=(1, 28, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 28, 2048, 128), (7340032, 128, 3584, 1)),\n torch.randn(\n size=(1, 4, 2048, 128),\n dtype=torch.bfloat16,\n device=\"cuda\",\n requires_grad=False,\n ).as_strided((1, 4, 2048, 128), (1048576, 128, 512, 1)),\n ]\n return inputs\n\n\ndef test_cat_qwen2_fwd_11_nvf_benchmark(\n benchmark, disable_validation: bool, disable_benchmarking: bool\n):\n with FusionDefinition() as fd:\n cat_qwen2_fwd_11_fusion(fd)\n\n inputs = get_cat_qwen2_inputs()\n\n def benchmark_fn(inputs):\n return fd.execute(inputs)\n\n if not disable_validation:\n # torch.compile required; works around an issue in eager mode.\n tc = torch.compile(cat_qwen2_fwd_11)\n reference = tc(*inputs)\n # Temporarily disabled: leads to an illegal memory access.\n if False:\n fd.validate(inputs, reference)\n if not disable_benchmarking:\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n# Qwen2 fusion that involves concatenation. Note that there are no Mistral-Nemo\n# benchmarks in this file, because they were all equivalent to this fusion. The\n# fusion below appears repeatedly in both networks.\n#\n# The numbers are arbitrary; this was the 11th fusion in the forward pass.\n#\n# We don't use a \"thunder\" executor here because thunder cannot accept the\n# torch.as_strided call yet. There's a separate benchmark for thunder for now.\n@pytest.mark.parametrize(\"executor\", [\"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_qwen2_fwd_11_baseline_benchmark(benchmark, executor: str) -> None:\n inputs = get_cat_qwen2_inputs()\n\n def benchmark_fn(inputs):\n return cat_qwen2_fwd_11(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.test_cat_qwen2_fwd_11_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_cat.test_cat_qwen2_fwd_11_baseline_benchmark#L393-L401","kind":"function","name":"test_cat_qwen2_fwd_11_baseline_benchmark","path":"benchmarks/python/test_cat.py","language":"python","start_line":393,"end_line":401,"context_start_line":373,"context_end_line":421,"code":" # torch.compile required; works around an issue in eager mode.\n tc = torch.compile(cat_qwen2_fwd_11)\n reference = tc(*inputs)\n # Temporarily disabled: leads to an illegal memory access.\n if False:\n fd.validate(inputs, reference)\n if not disable_benchmarking:\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n# Qwen2 fusion that involves concatenation. Note that there are no Mistral-Nemo\n# benchmarks in this file, because they were all equivalent to this fusion. The\n# fusion below appears repeatedly in both networks.\n#\n# The numbers are arbitrary; this was the 11th fusion in the forward pass.\n#\n# We don't use a \"thunder\" executor here because thunder cannot accept the\n# torch.as_strided call yet. There's a separate benchmark for thunder for now.\n@pytest.mark.parametrize(\"executor\", [\"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_qwen2_fwd_11_baseline_benchmark(benchmark, executor: str) -> None:\n inputs = get_cat_qwen2_inputs()\n\n def benchmark_fn(inputs):\n return cat_qwen2_fwd_11(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", [\"thunder\", \"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_phi3_1_baseline_benchmark(\n benchmark, executor: str, disable_validation: bool\n) -> None:\n def to_be_compiled(t14):\n # t14: \"cuda:0 f32[1, 48, 2048]\"\n t0 = torch.permute(t14, (0, 2, 1)) # t0: \"cuda:0 f32[1, 2048, 48]\"\n # t0 = prims.transpose(t14, (0, 2, 1)) # t0: \"cuda:0 f32[1, 2048, 48]\"\n t1 = torch.cat([t0, t0], -1) # t1: \"cuda:0 f32[1, 2048, 96]\"\n t2 = torch.cos(t1) # t2: \"cuda:0 f32[1, 2048, 96]\"\n t3 = torch.sin(t1) # t3: \"cuda:0 f32[1, 2048, 96]\"\n t4 = torch.mul(t2, 1.1902380714238083) # t4: \"cuda:0 f32[1, 2048, 96]\"\n t5 = torch.mul(t3, 1.1902380714238083) # t5: \"cuda:0 f32[1, 2048, 96]\"\n t6 = torch.Tensor.to(\n t4, torch.bfloat16, copy=True\n ) # t6: \"cuda:0 bf16[1, 2048, 96]\"\n # t6 = prims.convert_element_type(t4, dtypes.bfloat16) # t6: \"cuda:0 bf16[1, 2048, 96]\"","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.test_cat_phi3_1_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_cat.test_cat_phi3_1_baseline_benchmark#L406-L461","kind":"function","name":"test_cat_phi3_1_baseline_benchmark","path":"benchmarks/python/test_cat.py","language":"python","start_line":406,"end_line":461,"context_start_line":386,"context_end_line":481,"code":"#\n# The numbers are arbitrary; this was the 11th fusion in the forward pass.\n#\n# We don't use a \"thunder\" executor here because thunder cannot accept the\n# torch.as_strided call yet. There's a separate benchmark for thunder for now.\n@pytest.mark.parametrize(\"executor\", [\"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_qwen2_fwd_11_baseline_benchmark(benchmark, executor: str) -> None:\n inputs = get_cat_qwen2_inputs()\n\n def benchmark_fn(inputs):\n return cat_qwen2_fwd_11(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", [\"thunder\", \"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_phi3_1_baseline_benchmark(\n benchmark, executor: str, disable_validation: bool\n) -> None:\n def to_be_compiled(t14):\n # t14: \"cuda:0 f32[1, 48, 2048]\"\n t0 = torch.permute(t14, (0, 2, 1)) # t0: \"cuda:0 f32[1, 2048, 48]\"\n # t0 = prims.transpose(t14, (0, 2, 1)) # t0: \"cuda:0 f32[1, 2048, 48]\"\n t1 = torch.cat([t0, t0], -1) # t1: \"cuda:0 f32[1, 2048, 96]\"\n t2 = torch.cos(t1) # t2: \"cuda:0 f32[1, 2048, 96]\"\n t3 = torch.sin(t1) # t3: \"cuda:0 f32[1, 2048, 96]\"\n t4 = torch.mul(t2, 1.1902380714238083) # t4: \"cuda:0 f32[1, 2048, 96]\"\n t5 = torch.mul(t3, 1.1902380714238083) # t5: \"cuda:0 f32[1, 2048, 96]\"\n t6 = torch.Tensor.to(\n t4, torch.bfloat16, copy=True\n ) # t6: \"cuda:0 bf16[1, 2048, 96]\"\n # t6 = prims.convert_element_type(t4, dtypes.bfloat16) # t6: \"cuda:0 bf16[1, 2048, 96]\"\n t7 = torch.Tensor.to(\n t5, torch.bfloat16, copy=True\n ) # t7: \"cuda:0 bf16[1, 2048, 96]\"\n # t7 = prims.convert_element_type(t5, dtypes.bfloat16) # t7: \"cuda:0 bf16[1, 2048, 96]\"\n return [t6, t7]\n\n inputs = [\n torch.randn(\n size=(1, 48, 2048),\n dtype=torch.float32,\n device=\"cuda\",\n requires_grad=False,\n ),\n ]\n\n def benchmark_fn(inputs):\n return to_be_compiled(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n if not disable_validation and executor == \"thunder\":\n # The FusionDefinition can be pulled from thunder, but `with_executor`\n # hides thunder from us so we need to manually run things to pull the\n # FusionDefinition ourself.\n import thunder\n\n reference_outputs = to_be_compiled(*inputs)\n from thunder.executors.nvfuserex import nvfuserex\n\n tmp = thunder.jit(to_be_compiled, executors=[nvfuserex])\n tmp(*inputs)\n traces: [thunder.core.trace.TraceCtx] = thunder.last_traces(tmp)\n assert traces is not None\n trace: thunder.core.trace.TraceCtx = traces[-1]\n assert (\n \"nvFusion1\" not in trace.python_ctx()\n ), \"thunder split the fusion, so the validation no longer fits.\"\n fusion: FusionDefinition = trace.python_ctx()[\"nvFusion0\"].last_used\n fusion.validate(inputs, reference_outputs)\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n# Nanogpt has no concat operations, but because it has split operations concat\n# ops appear in the backward pass. The kernel shown below appears multiple\n# times in the backward pass. The '6' is arbitrary: this is the 6th fusion\n# generated by the network.\n@pytest.mark.parametrize(\"executor\", [\"thunder\", \"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_nanogpt_bwd_6_baseline_benchmark(\n benchmark, executor: str, disable_validation: bool\n) -> None:\n def nanogpt_bwd_fusion_6_torch(bw_t3476: torch.Tensor, bw_t3475, bw_t3474):\n # bw_t3476: \"cuda:0 f32[4, 6, 128, 64]\"\n # bw_t3475: \"cuda:0 f32[4, 6, 64, 128]\"\n # bw_t3474: \"cuda:0 f32[4, 6, 64, 128]\"\n t0 = torch.mul(0.29730177875068026, bw_t3476) # t0: \"cuda:0 f32[4, 6, 128, 64]\"\n t1 = torch.permute(t0, (0, 1, 3, 2)) # t1: \"cuda:0 f32[4, 6, 64, 128]\"\n # t1 = prims.transpose(t0, (0, 1, 3, 2)) # t1: \"cuda:0 f32[4, 6, 64, 128]\"\n t2 = torch.mul(0.29730177875068026, bw_t3475) # t2: \"cuda:0 f32[4, 6, 64, 128]\"\n t3 = torch.permute(bw_t3474, (0, 2, 1, 3)) # t3: \"cuda:0 f32[4, 64, 6, 128]\"","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.test_cat_nanogpt_bwd_6_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_cat.test_cat_nanogpt_bwd_6_baseline_benchmark#L470-L530","kind":"function","name":"test_cat_nanogpt_bwd_6_baseline_benchmark","path":"benchmarks/python/test_cat.py","language":"python","start_line":470,"end_line":530,"context_start_line":450,"context_end_line":530,"code":"\n tmp = thunder.jit(to_be_compiled, executors=[nvfuserex])\n tmp(*inputs)\n traces: [thunder.core.trace.TraceCtx] = thunder.last_traces(tmp)\n assert traces is not None\n trace: thunder.core.trace.TraceCtx = traces[-1]\n assert (\n \"nvFusion1\" not in trace.python_ctx()\n ), \"thunder split the fusion, so the validation no longer fits.\"\n fusion: FusionDefinition = trace.python_ctx()[\"nvFusion0\"].last_used\n fusion.validate(inputs, reference_outputs)\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n# Nanogpt has no concat operations, but because it has split operations concat\n# ops appear in the backward pass. The kernel shown below appears multiple\n# times in the backward pass. The '6' is arbitrary: this is the 6th fusion\n# generated by the network.\n@pytest.mark.parametrize(\"executor\", [\"thunder\", \"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_nanogpt_bwd_6_baseline_benchmark(\n benchmark, executor: str, disable_validation: bool\n) -> None:\n def nanogpt_bwd_fusion_6_torch(bw_t3476: torch.Tensor, bw_t3475, bw_t3474):\n # bw_t3476: \"cuda:0 f32[4, 6, 128, 64]\"\n # bw_t3475: \"cuda:0 f32[4, 6, 64, 128]\"\n # bw_t3474: \"cuda:0 f32[4, 6, 64, 128]\"\n t0 = torch.mul(0.29730177875068026, bw_t3476) # t0: \"cuda:0 f32[4, 6, 128, 64]\"\n t1 = torch.permute(t0, (0, 1, 3, 2)) # t1: \"cuda:0 f32[4, 6, 64, 128]\"\n # t1 = prims.transpose(t0, (0, 1, 3, 2)) # t1: \"cuda:0 f32[4, 6, 64, 128]\"\n t2 = torch.mul(0.29730177875068026, bw_t3475) # t2: \"cuda:0 f32[4, 6, 64, 128]\"\n t3 = torch.permute(bw_t3474, (0, 2, 1, 3)) # t3: \"cuda:0 f32[4, 64, 6, 128]\"\n # t3 = prims.transpose(bw_t3474, (0, 2, 1, 3)) # t3: \"cuda:0 f32[4, 64, 6, 128]\"\n t4 = torch.reshape(t3, (4, 64, 768)) # t4: \"cuda:0 f32[4, 64, 768]\"\n t5 = torch.permute(t2, (0, 2, 1, 3)) # t5: \"cuda:0 f32[4, 64, 6, 128]\"\n # t5 = prims.transpose(t2, (0, 2, 1, 3)) # t5: \"cuda:0 f32[4, 64, 6, 128]\"\n t6 = torch.reshape(t5, (4, 64, 768)) # t6: \"cuda:0 f32[4, 64, 768]\"\n t7 = torch.permute(t1, (0, 2, 1, 3)) # t7: \"cuda:0 f32[4, 64, 6, 128]\"\n # t7 = prims.transpose(t1, (0, 2, 1, 3)) # t7: \"cuda:0 f32[4, 64, 6, 128]\"\n t8 = torch.reshape(t7, (4, 64, 768)) # t8: \"cuda:0 f32[4, 64, 768]\"\n t9 = torch.cat([t6, t8, t4], 2) # t9: \"cuda:0 f32[4, 64, 2304]\"\n t10 = torch.reshape(t9, (256, 2304)) # t10: \"cuda:0 f32[256, 2304]\"\n return [t9, t10]\n\n inputs = [\n torch.testing.make_tensor(\n (4, 6, 128, 64), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (4, 6, 64, 128), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (4, 6, 64, 128), dtype=torch.float32, device=\"cuda:0\"\n ),\n ]\n\n def benchmark_fn(inputs):\n return nanogpt_bwd_fusion_6_torch(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n if not disable_validation and executor == \"thunder\":\n # The FusionDefinition can be pulled from thunder, but `with_executor`\n # hides thunder from us so we need to manually run things to pull the\n # FusionDefinition ourself.\n import thunder\n\n reference_outputs = nanogpt_bwd_fusion_6_torch(*inputs)\n from thunder.executors.nvfuserex import nvfuserex\n\n tmp = thunder.jit(nanogpt_bwd_fusion_6_torch, executors=[nvfuserex])\n tmp(*inputs)\n traces: [thunder.core.trace.TraceCtx] = thunder.last_traces(tmp)\n assert traces is not None\n trace: thunder.core.trace.TraceCtx = traces[-1]\n assert (\n \"nvFusion1\" not in trace.python_ctx()\n ), \"thunder split the fusion, so the validation no longer fits.\"\n fusion: FusionDefinition = trace.python_ctx()[\"nvFusion0\"].last_used\n fusion.validate(inputs, reference_outputs)\n run_benchmark(benchmark, benchmark_fn, inputs)","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.benchmark_fn","uri":"program://Fuser/function/benchmarks.python.test_cat.benchmark_fn#L506-L507","kind":"function","name":"benchmark_fn","path":"benchmarks/python/test_cat.py","language":"python","start_line":506,"end_line":507,"context_start_line":486,"context_end_line":527,"code":" t6 = torch.reshape(t5, (4, 64, 768)) # t6: \"cuda:0 f32[4, 64, 768]\"\n t7 = torch.permute(t1, (0, 2, 1, 3)) # t7: \"cuda:0 f32[4, 64, 6, 128]\"\n # t7 = prims.transpose(t1, (0, 2, 1, 3)) # t7: \"cuda:0 f32[4, 64, 6, 128]\"\n t8 = torch.reshape(t7, (4, 64, 768)) # t8: \"cuda:0 f32[4, 64, 768]\"\n t9 = torch.cat([t6, t8, t4], 2) # t9: \"cuda:0 f32[4, 64, 2304]\"\n t10 = torch.reshape(t9, (256, 2304)) # t10: \"cuda:0 f32[256, 2304]\"\n return [t9, t10]\n\n inputs = [\n torch.testing.make_tensor(\n (4, 6, 128, 64), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (4, 6, 64, 128), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (4, 6, 64, 128), dtype=torch.float32, device=\"cuda:0\"\n ),\n ]\n\n def benchmark_fn(inputs):\n return nanogpt_bwd_fusion_6_torch(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n if not disable_validation and executor == \"thunder\":\n # The FusionDefinition can be pulled from thunder, but `with_executor`\n # hides thunder from us so we need to manually run things to pull the\n # FusionDefinition ourself.\n import thunder\n\n reference_outputs = nanogpt_bwd_fusion_6_torch(*inputs)\n from thunder.executors.nvfuserex import nvfuserex\n\n tmp = thunder.jit(nanogpt_bwd_fusion_6_torch, executors=[nvfuserex])\n tmp(*inputs)\n traces: [thunder.core.trace.TraceCtx] = thunder.last_traces(tmp)\n assert traces is not None\n trace: thunder.core.trace.TraceCtx = traces[-1]\n assert (\n \"nvFusion1\" not in trace.python_ctx()\n ), \"thunder split the fusion, so the validation no longer fits.\"","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.to_be_compiled","uri":"program://Fuser/function/benchmarks.python.test_cat.to_be_compiled#L409-L426","kind":"function","name":"to_be_compiled","path":"benchmarks/python/test_cat.py","language":"python","start_line":409,"end_line":426,"context_start_line":389,"context_end_line":446,"code":"# We don't use a \"thunder\" executor here because thunder cannot accept the\n# torch.as_strided call yet. There's a separate benchmark for thunder for now.\n@pytest.mark.parametrize(\"executor\", [\"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_qwen2_fwd_11_baseline_benchmark(benchmark, executor: str) -> None:\n inputs = get_cat_qwen2_inputs()\n\n def benchmark_fn(inputs):\n return cat_qwen2_fwd_11(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", [\"thunder\", \"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_phi3_1_baseline_benchmark(\n benchmark, executor: str, disable_validation: bool\n) -> None:\n def to_be_compiled(t14):\n # t14: \"cuda:0 f32[1, 48, 2048]\"\n t0 = torch.permute(t14, (0, 2, 1)) # t0: \"cuda:0 f32[1, 2048, 48]\"\n # t0 = prims.transpose(t14, (0, 2, 1)) # t0: \"cuda:0 f32[1, 2048, 48]\"\n t1 = torch.cat([t0, t0], -1) # t1: \"cuda:0 f32[1, 2048, 96]\"\n t2 = torch.cos(t1) # t2: \"cuda:0 f32[1, 2048, 96]\"\n t3 = torch.sin(t1) # t3: \"cuda:0 f32[1, 2048, 96]\"\n t4 = torch.mul(t2, 1.1902380714238083) # t4: \"cuda:0 f32[1, 2048, 96]\"\n t5 = torch.mul(t3, 1.1902380714238083) # t5: \"cuda:0 f32[1, 2048, 96]\"\n t6 = torch.Tensor.to(\n t4, torch.bfloat16, copy=True\n ) # t6: \"cuda:0 bf16[1, 2048, 96]\"\n # t6 = prims.convert_element_type(t4, dtypes.bfloat16) # t6: \"cuda:0 bf16[1, 2048, 96]\"\n t7 = torch.Tensor.to(\n t5, torch.bfloat16, copy=True\n ) # t7: \"cuda:0 bf16[1, 2048, 96]\"\n # t7 = prims.convert_element_type(t5, dtypes.bfloat16) # t7: \"cuda:0 bf16[1, 2048, 96]\"\n return [t6, t7]\n\n inputs = [\n torch.randn(\n size=(1, 48, 2048),\n dtype=torch.float32,\n device=\"cuda\",\n requires_grad=False,\n ),\n ]\n\n def benchmark_fn(inputs):\n return to_be_compiled(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n if not disable_validation and executor == \"thunder\":\n # The FusionDefinition can be pulled from thunder, but `with_executor`\n # hides thunder from us so we need to manually run things to pull the\n # FusionDefinition ourself.\n import thunder","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cat.nanogpt_bwd_fusion_6_torch","uri":"program://Fuser/function/benchmarks.python.test_cat.nanogpt_bwd_fusion_6_torch#L473-L492","kind":"function","name":"nanogpt_bwd_fusion_6_torch","path":"benchmarks/python/test_cat.py","language":"python","start_line":473,"end_line":492,"context_start_line":453,"context_end_line":512,"code":" traces: [thunder.core.trace.TraceCtx] = thunder.last_traces(tmp)\n assert traces is not None\n trace: thunder.core.trace.TraceCtx = traces[-1]\n assert (\n \"nvFusion1\" not in trace.python_ctx()\n ), \"thunder split the fusion, so the validation no longer fits.\"\n fusion: FusionDefinition = trace.python_ctx()[\"nvFusion0\"].last_used\n fusion.validate(inputs, reference_outputs)\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n# Nanogpt has no concat operations, but because it has split operations concat\n# ops appear in the backward pass. The kernel shown below appears multiple\n# times in the backward pass. The '6' is arbitrary: this is the 6th fusion\n# generated by the network.\n@pytest.mark.parametrize(\"executor\", [\"thunder\", \"torchcompile\"])\n@pytest.mark.resize\ndef test_cat_nanogpt_bwd_6_baseline_benchmark(\n benchmark, executor: str, disable_validation: bool\n) -> None:\n def nanogpt_bwd_fusion_6_torch(bw_t3476: torch.Tensor, bw_t3475, bw_t3474):\n # bw_t3476: \"cuda:0 f32[4, 6, 128, 64]\"\n # bw_t3475: \"cuda:0 f32[4, 6, 64, 128]\"\n # bw_t3474: \"cuda:0 f32[4, 6, 64, 128]\"\n t0 = torch.mul(0.29730177875068026, bw_t3476) # t0: \"cuda:0 f32[4, 6, 128, 64]\"\n t1 = torch.permute(t0, (0, 1, 3, 2)) # t1: \"cuda:0 f32[4, 6, 64, 128]\"\n # t1 = prims.transpose(t0, (0, 1, 3, 2)) # t1: \"cuda:0 f32[4, 6, 64, 128]\"\n t2 = torch.mul(0.29730177875068026, bw_t3475) # t2: \"cuda:0 f32[4, 6, 64, 128]\"\n t3 = torch.permute(bw_t3474, (0, 2, 1, 3)) # t3: \"cuda:0 f32[4, 64, 6, 128]\"\n # t3 = prims.transpose(bw_t3474, (0, 2, 1, 3)) # t3: \"cuda:0 f32[4, 64, 6, 128]\"\n t4 = torch.reshape(t3, (4, 64, 768)) # t4: \"cuda:0 f32[4, 64, 768]\"\n t5 = torch.permute(t2, (0, 2, 1, 3)) # t5: \"cuda:0 f32[4, 64, 6, 128]\"\n # t5 = prims.transpose(t2, (0, 2, 1, 3)) # t5: \"cuda:0 f32[4, 64, 6, 128]\"\n t6 = torch.reshape(t5, (4, 64, 768)) # t6: \"cuda:0 f32[4, 64, 768]\"\n t7 = torch.permute(t1, (0, 2, 1, 3)) # t7: \"cuda:0 f32[4, 64, 6, 128]\"\n # t7 = prims.transpose(t1, (0, 2, 1, 3)) # t7: \"cuda:0 f32[4, 64, 6, 128]\"\n t8 = torch.reshape(t7, (4, 64, 768)) # t8: \"cuda:0 f32[4, 64, 768]\"\n t9 = torch.cat([t6, t8, t4], 2) # t9: \"cuda:0 f32[4, 64, 2304]\"\n t10 = torch.reshape(t9, (256, 2304)) # t10: \"cuda:0 f32[256, 2304]\"\n return [t9, t10]\n\n inputs = [\n torch.testing.make_tensor(\n (4, 6, 128, 64), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (4, 6, 64, 128), dtype=torch.float32, device=\"cuda:0\"\n ),\n torch.testing.make_tensor(\n (4, 6, 64, 128), dtype=torch.float32, device=\"cuda:0\"\n ),\n ]\n\n def benchmark_fn(inputs):\n return nanogpt_bwd_fusion_6_torch(*inputs)\n\n benchmark_fn = with_executor(executor, benchmark_fn)\n\n if not disable_validation and executor == \"thunder\":\n # The FusionDefinition can be pulled from thunder, but `with_executor`","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops","uri":"program://Fuser/module/benchmarks.python.rope_ops#L1-L911","kind":"module","name":"benchmarks.python.rope_ops","path":"benchmarks/python/rope_ops.py","language":"python","start_line":1,"end_line":911,"context_start_line":1,"context_end_line":911,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\n\nfrom torch import nn\n\nfrom typing import Tuple\nfrom functools import partial\n\nfrom .model_configs import configs\n\nSEQ_LENGTHS = (\n 1024,\n 2048,\n 4096,\n 8192,\n 12288,\n 16384,\n 20480,\n 24576,\n 28672,\n 32768,\n)\n\n\ndef apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:\n head_size = x.size(-1)\n x1 = x[..., : head_size // 2] # (B, nh, T, hs/2)\n x2 = x[..., head_size // 2 :] # (B, nh, T, hs/2)\n rotated = torch.cat((-x2, x1), dim=-1) # (B, nh, T, hs)\n if cos.dim() > 1:\n # batch dimensions must align\n # sin/cos are (B, T, hs) so we unsqeeze -3 for nh\n # we count from back because all of apply_rope does\n cos = cos.unsqueeze(-3)\n sin = sin.unsqueeze(-3)\n\n roped = (x * cos) + (rotated * sin)\n return roped.to(dtype=x.dtype)\n\n\ndef llama_hf(seq_length, *, config_str):\n class LitGPTRope(torch.nn.Module):\n def __init__(self, config):\n super(LitGPTRope, self).__init__()\n self.config = config\n\n def forward(self, qkv, cos, sin):\n B, T, _ = qkv.size()\n # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n q_per_kv = self.config.n_head // self.config.n_query_groups\n total_qkv = q_per_kv + 2 # each group has 1+ queries, 1 key, and 1 value\n qkv = qkv.view(\n B, T, self.config.n_query_groups, total_qkv, self.config.head_size\n )\n qkv = qkv.permute(0, 2, 3, 1, 4) # (B, n_query_groups, total_qkv, T, hs)\n\n # split batched computation into three\n q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)\n\n # maybe repeat k and v if for the non multi-head attention cases\n # training: flash attention requires it\n # inference: multi-query would require a full kv cache so avoid it to limit its memory usage\n # if self.config.n_query_groups != self.config.n_head and (input_pos is None or self.config.n_query_groups != 1):\n if self.config.n_query_groups != self.config.n_head and (\n self.config.n_query_groups != 1\n ):\n k = k.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n v = v.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n\n q = q.reshape(B, -1, T, self.config.head_size) # (B, nh_q, T, hs)\n k = k.reshape(B, -1, T, self.config.head_size) # (B, nh_k, T, hs)\n v = v.reshape(B, -1, T, self.config.head_size) # (B, nh_v, T, hs)\n\n q_roped = apply_rope(q[..., : self.config.rope_n_elem], cos, sin)\n k_roped = apply_rope(k[..., : self.config.rope_n_elem], cos, sin)\n q = torch.cat((q_roped, q[..., self.config.rope_n_elem :]), dim=-1)\n k = torch.cat((k_roped, k[..., self.config.rope_n_elem :]), dim=-1)\n return q, k\n\n cfg = configs[config_str]()\n # overwrite seq_length\n cfg.seq_length = seq_length\n\n def inputs():\n qkv = torch.randn(\n cfg.batches,\n cfg.seq_length,\n cfg.head_size * (cfg.n_head + 2 * cfg.n_query_groups),\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n cos = torch.randn(\n cfg.seq_length,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n sin = torch.randn(\n cfg.seq_length,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return qkv, cos, sin\n\n def grads():\n grad = torch.randn(\n cfg.batches,\n cfg.n_head,\n cfg.seq_length,\n cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of q.grad + k.grad\n n_elements += 2 * cfg.batches * cfg.n_head * cfg.seq_length * cfg.head_size\n # adding size of cos, sin\n n_elements += 2 * cfg.seq_length * cfg.rope_n_elem\n # adding size of qkv.grad\n n_elements += (\n cfg.batches\n * cfg.seq_length\n * cfg.head_size\n * (cfg.n_head + 2 * cfg.n_query_groups)\n )\n # scale by dtype size\n return n_elements * torch.bfloat16.itemsize\n\n return LitGPTRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_qwen2(seq_length):\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n\n def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n\n Args:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n Returns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.\n \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n class Qwen2Rope(nn.Module):\n from transformers.models.qwen2 import Qwen2Config\n\n def __init__(self, config: Qwen2Config):\n super().__init__()\n self.config = config\n\n self.hidden_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = self.hidden_size // self.num_heads\n self.num_key_value_heads = config.num_key_value_heads\n self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n self.max_position_embeddings = config.max_position_embeddings\n self.rope_theta = config.rope_theta\n self.is_causal = True\n self.attention_dropout = config.attention_dropout\n\n if (self.head_dim * self.num_heads) != self.hidden_size:\n raise ValueError(\n f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n f\" and `num_heads`: {self.num_heads}).\"\n )\n\n def forward(\n self,\n query_in_states: torch.Tensor,\n key_in_states: torch.Tensor,\n value_in_states: torch.Tensor,\n cos: torch.Tensor,\n sin: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n past_key_value = None\n bsz, q_len, _ = query_in_states.size()\n\n query_states = query_in_states.view(\n bsz, q_len, self.num_heads, self.head_dim\n ).transpose(1, 2)\n key_states = key_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n value_states = value_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n\n query_states, key_states = apply_rotary_pos_emb(\n query_states, key_states, cos, sin\n )\n\n if past_key_value is not None:\n assert False\n\n key_states = repeat_kv(key_states, self.num_key_value_groups)\n value_states = repeat_kv(value_states, self.num_key_value_groups)\n return query_states, key_states, value_states\n\n cfg = configs[\"hf_qwen2\"]()\n # overwrite seq_length\n cfg.seq_len = seq_length\n head_dim = cfg.hidden_size // cfg.num_attention_heads\n\n def inputs():\n q = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_attention_heads * head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n k = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_key_value_heads * head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n v = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_key_value_heads * head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n cos = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n sin = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n return q, k, v, cos, sin\n\n def grads():\n grad = torch.randn(\n cfg.batch_size,\n cfg.num_attention_heads,\n cfg.seq_len,\n head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of query_states.grad + key_states.grad + value_states.grad\n n_elements += (\n 3 * cfg.batch_size * cfg.num_attention_heads * cfg.seq_len * head_dim\n )\n # adding size of query_states + key_states\n n_elements += (\n 2 * cfg.batch_size * cfg.num_attention_heads * cfg.seq_len * head_dim\n )\n # adding size of cos, sin\n n_elements += 2 * cfg.batch_size * cfg.seq_len * head_dim\n # adding size of q.grad\n n_elements += cfg.batch_size * cfg.seq_len * cfg.num_attention_heads * head_dim\n # adding size of k.grad, v.grad\n n_elements += (\n 2 * cfg.batch_size * cfg.seq_len * cfg.num_key_value_heads * head_dim\n )\n # adding size of cos.grad, sin.grad\n n_elements += 2 * cfg.batch_size * cfg.seq_len * head_dim\n # scale by dtype size\n return n_elements * torch.bfloat16.itemsize\n\n return Qwen2Rope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_phi3(seq_length):\n class Phi3RotaryEmbedding(nn.Module):\n def __init__(\n self, dim, max_position_embeddings=2048, base=10000.0, device=None\n ):\n super().__init__()\n\n self.dim = dim\n self.max_position_embddings = max_position_embeddings\n self.base = base\n\n inv_freq = 1.0 / (\n self.base\n ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim)\n )\n self.register_buffer(\"inv_freq\", tensor=inv_freq, persistent=False)\n\n @torch.no_grad()\n def forward(self, x, position_ids, seq_len=None):\n # x: [bs, num_attention_heads, seq_len, head_size]\n self.inv_freq.to(x.device)\n inv_freq_expanded = (\n self.inv_freq[None, :, None]\n .float()\n .expand(position_ids.shape[0], -1, 1)\n )\n position_ids_expanded = position_ids[:, None, :].float()\n # Force float32 since bfloat16 loses precision on long contexts\n # See https://github.com/huggingface/transformers/pull/29285\n device_type = x.device.type\n device_type = (\n device_type\n if isinstance(device_type, str) and device_type != \"mps\"\n else \"cpu\"\n )\n with torch.autocast(device_type=device_type, enabled=False):\n freqs = (\n inv_freq_expanded.float() @ position_ids_expanded.float()\n ).transpose(1, 2)\n emb = torch.cat((freqs, freqs), dim=-1)\n cos = emb.cos()\n sin = emb.sin()\n return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n\n def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n\n Args:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n Returns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.\n \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n class HfPhi3Rope(nn.Module):\n \"\"\"Multi-headed attention from 'Attention Is All You Need' paper\"\"\"\n\n from transformers.models.phi3 import Phi3Config\n\n def __init__(self, config: Phi3Config):\n super().__init__()\n self.config = config\n\n self.hidden_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = self.hidden_size // self.num_heads\n self.num_key_value_heads = config.num_key_value_heads\n self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n self.max_position_embeddings = config.max_position_embeddings\n self.original_max_position_embeddings = (\n config.original_max_position_embeddings\n )\n self.rope_theta = config.rope_theta\n self.rope_scaling = config.rope_scaling\n self.is_causal = True\n\n if (self.head_dim * self.num_heads) != self.hidden_size:\n raise ValueError(\n f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n f\" and `num_heads`: {self.num_heads}).\"\n )\n\n self.rotary_emb = Phi3RotaryEmbedding(\n self.head_dim,\n max_position_embeddings=self.max_position_embeddings,\n base=self.rope_theta,\n )\n\n def forward(\n self, qkv: torch.Tensor, position_ids: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n past_key_value = None\n bsz, q_len, _ = qkv.size()\n\n query_pos = self.num_heads * self.head_dim\n query_states = qkv[..., :query_pos]\n key_states = qkv[\n ..., query_pos : query_pos + self.num_key_value_heads * self.head_dim\n ]\n value_states = qkv[\n ..., query_pos + self.num_key_value_heads * self.head_dim :\n ]\n\n query_states = query_states.view(\n bsz, q_len, self.num_heads, self.head_dim\n ).transpose(1, 2)\n key_states = key_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n value_states = value_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n\n kv_seq_len = key_states.shape[-2]\n if past_key_value is not None:\n assert False\n cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)\n\n query_states, key_states = apply_rotary_pos_emb(\n query_states, key_states, cos, sin, position_ids\n )\n\n if past_key_value is not None:\n assert False\n\n key_states = repeat_kv(key_states, self.num_key_value_groups)\n value_states = repeat_kv(value_states, self.num_key_value_groups)\n\n return query_states, key_states, value_states\n\n cfg = configs[\"hf_phi3\"]()\n # overwrite seq_length\n cfg.seq_len = seq_length\n head_dim = cfg.hidden_size // cfg.num_attention_heads\n\n def inputs():\n qkv = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n# ... truncated ...","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":true} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.apply_rope","uri":"program://Fuser/function/benchmarks.python.rope_ops.apply_rope#L27-L40","kind":"function","name":"apply_rope","path":"benchmarks/python/rope_ops.py","language":"python","start_line":27,"end_line":40,"context_start_line":7,"context_end_line":60,"code":"\nfrom typing import Tuple\nfrom functools import partial\n\nfrom .model_configs import configs\n\nSEQ_LENGTHS = (\n 1024,\n 2048,\n 4096,\n 8192,\n 12288,\n 16384,\n 20480,\n 24576,\n 28672,\n 32768,\n)\n\n\ndef apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:\n head_size = x.size(-1)\n x1 = x[..., : head_size // 2] # (B, nh, T, hs/2)\n x2 = x[..., head_size // 2 :] # (B, nh, T, hs/2)\n rotated = torch.cat((-x2, x1), dim=-1) # (B, nh, T, hs)\n if cos.dim() > 1:\n # batch dimensions must align\n # sin/cos are (B, T, hs) so we unsqeeze -3 for nh\n # we count from back because all of apply_rope does\n cos = cos.unsqueeze(-3)\n sin = sin.unsqueeze(-3)\n\n roped = (x * cos) + (rotated * sin)\n return roped.to(dtype=x.dtype)\n\n\ndef llama_hf(seq_length, *, config_str):\n class LitGPTRope(torch.nn.Module):\n def __init__(self, config):\n super(LitGPTRope, self).__init__()\n self.config = config\n\n def forward(self, qkv, cos, sin):\n B, T, _ = qkv.size()\n # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n q_per_kv = self.config.n_head // self.config.n_query_groups\n total_qkv = q_per_kv + 2 # each group has 1+ queries, 1 key, and 1 value\n qkv = qkv.view(\n B, T, self.config.n_query_groups, total_qkv, self.config.head_size\n )\n qkv = qkv.permute(0, 2, 3, 1, 4) # (B, n_query_groups, total_qkv, T, hs)\n\n # split batched computation into three\n q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.llama_hf","uri":"program://Fuser/function/benchmarks.python.rope_ops.llama_hf#L43-L144","kind":"function","name":"llama_hf","path":"benchmarks/python/rope_ops.py","language":"python","start_line":43,"end_line":144,"context_start_line":23,"context_end_line":164,"code":" 32768,\n)\n\n\ndef apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:\n head_size = x.size(-1)\n x1 = x[..., : head_size // 2] # (B, nh, T, hs/2)\n x2 = x[..., head_size // 2 :] # (B, nh, T, hs/2)\n rotated = torch.cat((-x2, x1), dim=-1) # (B, nh, T, hs)\n if cos.dim() > 1:\n # batch dimensions must align\n # sin/cos are (B, T, hs) so we unsqeeze -3 for nh\n # we count from back because all of apply_rope does\n cos = cos.unsqueeze(-3)\n sin = sin.unsqueeze(-3)\n\n roped = (x * cos) + (rotated * sin)\n return roped.to(dtype=x.dtype)\n\n\ndef llama_hf(seq_length, *, config_str):\n class LitGPTRope(torch.nn.Module):\n def __init__(self, config):\n super(LitGPTRope, self).__init__()\n self.config = config\n\n def forward(self, qkv, cos, sin):\n B, T, _ = qkv.size()\n # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n q_per_kv = self.config.n_head // self.config.n_query_groups\n total_qkv = q_per_kv + 2 # each group has 1+ queries, 1 key, and 1 value\n qkv = qkv.view(\n B, T, self.config.n_query_groups, total_qkv, self.config.head_size\n )\n qkv = qkv.permute(0, 2, 3, 1, 4) # (B, n_query_groups, total_qkv, T, hs)\n\n # split batched computation into three\n q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)\n\n # maybe repeat k and v if for the non multi-head attention cases\n # training: flash attention requires it\n # inference: multi-query would require a full kv cache so avoid it to limit its memory usage\n # if self.config.n_query_groups != self.config.n_head and (input_pos is None or self.config.n_query_groups != 1):\n if self.config.n_query_groups != self.config.n_head and (\n self.config.n_query_groups != 1\n ):\n k = k.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n v = v.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n\n q = q.reshape(B, -1, T, self.config.head_size) # (B, nh_q, T, hs)\n k = k.reshape(B, -1, T, self.config.head_size) # (B, nh_k, T, hs)\n v = v.reshape(B, -1, T, self.config.head_size) # (B, nh_v, T, hs)\n\n q_roped = apply_rope(q[..., : self.config.rope_n_elem], cos, sin)\n k_roped = apply_rope(k[..., : self.config.rope_n_elem], cos, sin)\n q = torch.cat((q_roped, q[..., self.config.rope_n_elem :]), dim=-1)\n k = torch.cat((k_roped, k[..., self.config.rope_n_elem :]), dim=-1)\n return q, k\n\n cfg = configs[config_str]()\n # overwrite seq_length\n cfg.seq_length = seq_length\n\n def inputs():\n qkv = torch.randn(\n cfg.batches,\n cfg.seq_length,\n cfg.head_size * (cfg.n_head + 2 * cfg.n_query_groups),\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n cos = torch.randn(\n cfg.seq_length,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n sin = torch.randn(\n cfg.seq_length,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return qkv, cos, sin\n\n def grads():\n grad = torch.randn(\n cfg.batches,\n cfg.n_head,\n cfg.seq_length,\n cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of q.grad + k.grad\n n_elements += 2 * cfg.batches * cfg.n_head * cfg.seq_length * cfg.head_size\n # adding size of cos, sin\n n_elements += 2 * cfg.seq_length * cfg.rope_n_elem\n # adding size of qkv.grad\n n_elements += (\n cfg.batches\n * cfg.seq_length\n * cfg.head_size\n * (cfg.n_head + 2 * cfg.n_query_groups)\n )\n # scale by dtype size\n return n_elements * torch.bfloat16.itemsize\n\n return LitGPTRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_qwen2(seq_length):\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n\n def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n\n Args:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.hf_qwen2","uri":"program://Fuser/function/benchmarks.python.rope_ops.hf_qwen2#L147-L332","kind":"function","name":"hf_qwen2","path":"benchmarks/python/rope_ops.py","language":"python","start_line":147,"end_line":332,"context_start_line":127,"context_end_line":352,"code":" # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of q.grad + k.grad\n n_elements += 2 * cfg.batches * cfg.n_head * cfg.seq_length * cfg.head_size\n # adding size of cos, sin\n n_elements += 2 * cfg.seq_length * cfg.rope_n_elem\n # adding size of qkv.grad\n n_elements += (\n cfg.batches\n * cfg.seq_length\n * cfg.head_size\n * (cfg.n_head + 2 * cfg.n_query_groups)\n )\n # scale by dtype size\n return n_elements * torch.bfloat16.itemsize\n\n return LitGPTRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_qwen2(seq_length):\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n\n def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n\n Args:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n Returns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.\n \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n class Qwen2Rope(nn.Module):\n from transformers.models.qwen2 import Qwen2Config\n\n def __init__(self, config: Qwen2Config):\n super().__init__()\n self.config = config\n\n self.hidden_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = self.hidden_size // self.num_heads\n self.num_key_value_heads = config.num_key_value_heads\n self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n self.max_position_embeddings = config.max_position_embeddings\n self.rope_theta = config.rope_theta\n self.is_causal = True\n self.attention_dropout = config.attention_dropout\n\n if (self.head_dim * self.num_heads) != self.hidden_size:\n raise ValueError(\n f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n f\" and `num_heads`: {self.num_heads}).\"\n )\n\n def forward(\n self,\n query_in_states: torch.Tensor,\n key_in_states: torch.Tensor,\n value_in_states: torch.Tensor,\n cos: torch.Tensor,\n sin: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n past_key_value = None\n bsz, q_len, _ = query_in_states.size()\n\n query_states = query_in_states.view(\n bsz, q_len, self.num_heads, self.head_dim\n ).transpose(1, 2)\n key_states = key_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n value_states = value_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n\n query_states, key_states = apply_rotary_pos_emb(\n query_states, key_states, cos, sin\n )\n\n if past_key_value is not None:\n assert False\n\n key_states = repeat_kv(key_states, self.num_key_value_groups)\n value_states = repeat_kv(value_states, self.num_key_value_groups)\n return query_states, key_states, value_states\n\n cfg = configs[\"hf_qwen2\"]()\n # overwrite seq_length\n cfg.seq_len = seq_length\n head_dim = cfg.hidden_size // cfg.num_attention_heads\n\n def inputs():\n q = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_attention_heads * head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n k = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_key_value_heads * head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n v = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_key_value_heads * head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n cos = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n sin = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n return q, k, v, cos, sin\n\n def grads():\n grad = torch.randn(\n cfg.batch_size,\n cfg.num_attention_heads,\n cfg.seq_len,\n head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of query_states.grad + key_states.grad + value_states.grad\n n_elements += (\n 3 * cfg.batch_size * cfg.num_attention_heads * cfg.seq_len * head_dim\n )\n # adding size of query_states + key_states\n n_elements += (\n 2 * cfg.batch_size * cfg.num_attention_heads * cfg.seq_len * head_dim\n )\n # adding size of cos, sin\n n_elements += 2 * cfg.batch_size * cfg.seq_len * head_dim\n # adding size of q.grad\n n_elements += cfg.batch_size * cfg.seq_len * cfg.num_attention_heads * head_dim\n # adding size of k.grad, v.grad\n n_elements += (\n 2 * cfg.batch_size * cfg.seq_len * cfg.num_key_value_heads * head_dim\n )\n # adding size of cos.grad, sin.grad\n n_elements += 2 * cfg.batch_size * cfg.seq_len * head_dim\n # scale by dtype size\n return n_elements * torch.bfloat16.itemsize\n\n return Qwen2Rope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_phi3(seq_length):\n class Phi3RotaryEmbedding(nn.Module):\n def __init__(\n self, dim, max_position_embeddings=2048, base=10000.0, device=None\n ):\n super().__init__()\n\n self.dim = dim\n self.max_position_embddings = max_position_embeddings\n self.base = base\n\n inv_freq = 1.0 / (\n self.base\n ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim)\n )\n self.register_buffer(\"inv_freq\", tensor=inv_freq, persistent=False)\n\n @torch.no_grad()","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.hf_phi3","uri":"program://Fuser/function/benchmarks.python.rope_ops.hf_phi3#L335-L554","kind":"function","name":"hf_phi3","path":"benchmarks/python/rope_ops.py","language":"python","start_line":335,"end_line":554,"context_start_line":315,"context_end_line":574,"code":" # adding size of query_states + key_states\n n_elements += (\n 2 * cfg.batch_size * cfg.num_attention_heads * cfg.seq_len * head_dim\n )\n # adding size of cos, sin\n n_elements += 2 * cfg.batch_size * cfg.seq_len * head_dim\n # adding size of q.grad\n n_elements += cfg.batch_size * cfg.seq_len * cfg.num_attention_heads * head_dim\n # adding size of k.grad, v.grad\n n_elements += (\n 2 * cfg.batch_size * cfg.seq_len * cfg.num_key_value_heads * head_dim\n )\n # adding size of cos.grad, sin.grad\n n_elements += 2 * cfg.batch_size * cfg.seq_len * head_dim\n # scale by dtype size\n return n_elements * torch.bfloat16.itemsize\n\n return Qwen2Rope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_phi3(seq_length):\n class Phi3RotaryEmbedding(nn.Module):\n def __init__(\n self, dim, max_position_embeddings=2048, base=10000.0, device=None\n ):\n super().__init__()\n\n self.dim = dim\n self.max_position_embddings = max_position_embeddings\n self.base = base\n\n inv_freq = 1.0 / (\n self.base\n ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim)\n )\n self.register_buffer(\"inv_freq\", tensor=inv_freq, persistent=False)\n\n @torch.no_grad()\n def forward(self, x, position_ids, seq_len=None):\n # x: [bs, num_attention_heads, seq_len, head_size]\n self.inv_freq.to(x.device)\n inv_freq_expanded = (\n self.inv_freq[None, :, None]\n .float()\n .expand(position_ids.shape[0], -1, 1)\n )\n position_ids_expanded = position_ids[:, None, :].float()\n # Force float32 since bfloat16 loses precision on long contexts\n # See https://github.com/huggingface/transformers/pull/29285\n device_type = x.device.type\n device_type = (\n device_type\n if isinstance(device_type, str) and device_type != \"mps\"\n else \"cpu\"\n )\n with torch.autocast(device_type=device_type, enabled=False):\n freqs = (\n inv_freq_expanded.float() @ position_ids_expanded.float()\n ).transpose(1, 2)\n emb = torch.cat((freqs, freqs), dim=-1)\n cos = emb.cos()\n sin = emb.sin()\n return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n\n def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n\n Args:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n Returns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.\n \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n class HfPhi3Rope(nn.Module):\n \"\"\"Multi-headed attention from 'Attention Is All You Need' paper\"\"\"\n\n from transformers.models.phi3 import Phi3Config\n\n def __init__(self, config: Phi3Config):\n super().__init__()\n self.config = config\n\n self.hidden_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = self.hidden_size // self.num_heads\n self.num_key_value_heads = config.num_key_value_heads\n self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n self.max_position_embeddings = config.max_position_embeddings\n self.original_max_position_embeddings = (\n config.original_max_position_embeddings\n )\n self.rope_theta = config.rope_theta\n self.rope_scaling = config.rope_scaling\n self.is_causal = True\n\n if (self.head_dim * self.num_heads) != self.hidden_size:\n raise ValueError(\n f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n f\" and `num_heads`: {self.num_heads}).\"\n )\n\n self.rotary_emb = Phi3RotaryEmbedding(\n self.head_dim,\n max_position_embeddings=self.max_position_embeddings,\n base=self.rope_theta,\n )\n\n def forward(\n self, qkv: torch.Tensor, position_ids: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n past_key_value = None\n bsz, q_len, _ = qkv.size()\n\n query_pos = self.num_heads * self.head_dim\n query_states = qkv[..., :query_pos]\n key_states = qkv[\n ..., query_pos : query_pos + self.num_key_value_heads * self.head_dim\n ]\n value_states = qkv[\n ..., query_pos + self.num_key_value_heads * self.head_dim :\n ]\n\n query_states = query_states.view(\n bsz, q_len, self.num_heads, self.head_dim\n ).transpose(1, 2)\n key_states = key_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n value_states = value_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n\n kv_seq_len = key_states.shape[-2]\n if past_key_value is not None:\n assert False\n cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)\n\n query_states, key_states = apply_rotary_pos_emb(\n query_states, key_states, cos, sin, position_ids\n )\n\n if past_key_value is not None:\n assert False\n\n key_states = repeat_kv(key_states, self.num_key_value_groups)\n value_states = repeat_kv(value_states, self.num_key_value_groups)\n\n return query_states, key_states, value_states\n\n cfg = configs[\"hf_phi3\"]()\n # overwrite seq_length\n cfg.seq_len = seq_length\n head_dim = cfg.hidden_size // cfg.num_attention_heads\n\n def inputs():\n qkv = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_attention_heads * head_dim\n + 2 * (cfg.num_key_value_heads * head_dim),\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n position_ids = torch.arange(0, cfg.seq_len, device=\"cuda\").unsqueeze(0)\n return qkv, position_ids\n\n def grads():\n grad = torch.randn(\n cfg.batch_size,\n cfg.num_attention_heads,\n cfg.seq_len,\n head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of query_states.grad + key_states.grad + value_states.grad\n n_elements += (\n 3 * cfg.batch_size * cfg.num_attention_heads * cfg.seq_len * head_dim\n )\n # adding size of qkv.grad\n n_elements += (\n cfg.batch_size\n * cfg.seq_len\n * (\n cfg.num_attention_heads * head_dim\n + 2 * (cfg.num_key_value_heads * head_dim)\n )\n )\n # matmul output size\n n_elements_matmul_out = head_dim / 2 * cfg.seq_len\n # totoal io sizes\n return (\n n_elements * torch.bfloat16.itemsize\n + n_elements_matmul_out * torch.float32.itemsize\n )\n\n return HfPhi3Rope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_mistral_nemo(seq_length):\n class MistralRotaryEmbedding(nn.Module):\n def __init__(\n self, dim, max_position_embeddings=2048, base=10000.0, device=None\n ):\n super().__init__()\n\n self.dim = dim\n self.max_position_embeddings = max_position_embeddings\n self.base = base\n inv_freq = 1.0 / (\n self.base\n ** (\n torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device)\n / self.dim\n )\n )\n self.register_buffer(\"inv_freq\", inv_freq, persistent=False)","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.hf_mistral_nemo","uri":"program://Fuser/function/benchmarks.python.rope_ops.hf_mistral_nemo#L557-L772","kind":"function","name":"hf_mistral_nemo","path":"benchmarks/python/rope_ops.py","language":"python","start_line":557,"end_line":772,"context_start_line":537,"context_end_line":792,"code":" # adding size of qkv.grad\n n_elements += (\n cfg.batch_size\n * cfg.seq_len\n * (\n cfg.num_attention_heads * head_dim\n + 2 * (cfg.num_key_value_heads * head_dim)\n )\n )\n # matmul output size\n n_elements_matmul_out = head_dim / 2 * cfg.seq_len\n # totoal io sizes\n return (\n n_elements * torch.bfloat16.itemsize\n + n_elements_matmul_out * torch.float32.itemsize\n )\n\n return HfPhi3Rope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_mistral_nemo(seq_length):\n class MistralRotaryEmbedding(nn.Module):\n def __init__(\n self, dim, max_position_embeddings=2048, base=10000.0, device=None\n ):\n super().__init__()\n\n self.dim = dim\n self.max_position_embeddings = max_position_embeddings\n self.base = base\n inv_freq = 1.0 / (\n self.base\n ** (\n torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device)\n / self.dim\n )\n )\n self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n\n @torch.no_grad()\n # copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding.forward\n # TODO(joao): add me back asap :)\n def forward(self, x, position_ids):\n # x: [bs, num_attention_heads, seq_len, head_size]\n inv_freq_expanded = (\n self.inv_freq[None, :, None]\n .float()\n .expand(position_ids.shape[0], -1, 1)\n )\n position_ids_expanded = position_ids[:, None, :].float()\n # Force float32 since bfloat16 loses precision on long contexts\n # See https://github.com/huggingface/transformers/pull/29285\n device_type = x.device.type\n device_type = (\n device_type\n if isinstance(device_type, str) and device_type != \"mps\"\n else \"cpu\"\n )\n with torch.autocast(device_type=device_type, enabled=False):\n freqs = (\n inv_freq_expanded.float() @ position_ids_expanded.float()\n ).transpose(1, 2)\n emb = torch.cat((freqs, freqs), dim=-1)\n cos = emb.cos()\n sin = emb.sin()\n return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)\n\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n\n def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n\n Args:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n Returns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.\n \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n class MistralNemoRope(nn.Module):\n from transformers.models.mistral import MistralConfig\n\n def __init__(self, config: MistralConfig):\n super().__init__()\n self.config = config\n\n self.attention_dropout = config.attention_dropout\n self.hidden_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = config.head_dim\n self.num_key_value_heads = config.num_key_value_heads\n self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n self.max_position_embeddings = config.max_position_embeddings\n self.rope_theta = config.rope_theta\n self.is_causal = True\n\n self.rotary_emb = MistralRotaryEmbedding(\n self.head_dim,\n max_position_embeddings=self.max_position_embeddings,\n base=self.rope_theta,\n )\n\n def forward(\n self,\n query_in_states: torch.Tensor,\n key_in_states: torch.Tensor,\n value_in_states: torch.Tensor,\n position_ids: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n past_key_value = None\n bsz, q_len, _ = query_in_states.size()\n\n query_states = query_in_states.view(\n bsz, q_len, self.num_heads, self.head_dim\n ).transpose(1, 2)\n key_states = key_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n value_states = value_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n\n cos, sin = self.rotary_emb(value_states, position_ids)\n query_states, key_states = apply_rotary_pos_emb(\n query_states, key_states, cos, sin\n )\n\n if past_key_value is not None:\n assert False\n\n key_states = repeat_kv(key_states, self.num_key_value_groups)\n value_states = repeat_kv(value_states, self.num_key_value_groups)\n return query_states, key_states, value_states\n\n cfg = configs[\"hf_mistral_nemo\"]()\n # overwrite seq_length\n cfg.seq_len = seq_length\n head_dim = cfg.hidden_size // cfg.num_attention_heads\n\n def inputs():\n q = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_attention_heads * cfg.head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n k = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_key_value_heads * cfg.head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n v = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_key_value_heads * cfg.head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n position_ids = torch.arange(0, cfg.seq_len, device=\"cuda\").unsqueeze(0)\n return q, k, v, position_ids\n\n def grads():\n grad = torch.randn(\n cfg.batch_size,\n cfg.num_attention_heads,\n cfg.seq_len,\n cfg.head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of query_states.grad + key_states.grad + value_states.grad\n n_elements += (\n 3 * cfg.batch_size * cfg.num_attention_heads * cfg.seq_len * cfg.head_dim\n )\n # adding size of q.grad\n n_elements += (\n cfg.batch_size * cfg.seq_len * cfg.num_attention_heads * cfg.head_dim\n )\n # adding size of k.grad, v.grad\n n_elements += (\n 2 * cfg.batch_size * cfg.seq_len * cfg.num_key_value_heads * cfg.head_dim\n )\n # matmul output size\n n_elements_matmul_out = head_dim / 2 * cfg.seq_len\n # totoal io sizes\n return (\n n_elements * torch.bfloat16.itemsize\n + n_elements_matmul_out * torch.float32.itemsize\n )\n\n return MistralNemoRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef Litgpt(seq_length, model_name):\n class LitgptRope(torch.nn.Module):\n def __init__(self, config) -> None:\n from litgpt.model import apply_rope\n\n self.fused_apply_rotary_pos_emb_cached = None\n\n super().__init__()\n self.config = config\n self.apply_rope = apply_rope\n\n def forward(\n self,\n qkv: torch.Tensor,\n cos: torch.Tensor,\n sin: torch.Tensor,\n ) -> torch.Tensor:\n B, T, _ = qkv.shape # batch size, sequence length","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.Litgpt","uri":"program://Fuser/function/benchmarks.python.rope_ops.Litgpt#L775-L889","kind":"function","name":"Litgpt","path":"benchmarks/python/rope_ops.py","language":"python","start_line":775,"end_line":889,"context_start_line":755,"context_end_line":909,"code":" )\n # adding size of q.grad\n n_elements += (\n cfg.batch_size * cfg.seq_len * cfg.num_attention_heads * cfg.head_dim\n )\n # adding size of k.grad, v.grad\n n_elements += (\n 2 * cfg.batch_size * cfg.seq_len * cfg.num_key_value_heads * cfg.head_dim\n )\n # matmul output size\n n_elements_matmul_out = head_dim / 2 * cfg.seq_len\n # totoal io sizes\n return (\n n_elements * torch.bfloat16.itemsize\n + n_elements_matmul_out * torch.float32.itemsize\n )\n\n return MistralNemoRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef Litgpt(seq_length, model_name):\n class LitgptRope(torch.nn.Module):\n def __init__(self, config) -> None:\n from litgpt.model import apply_rope\n\n self.fused_apply_rotary_pos_emb_cached = None\n\n super().__init__()\n self.config = config\n self.apply_rope = apply_rope\n\n def forward(\n self,\n qkv: torch.Tensor,\n cos: torch.Tensor,\n sin: torch.Tensor,\n ) -> torch.Tensor:\n B, T, _ = qkv.shape # batch size, sequence length\n\n # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n q_per_kv = self.config.n_head // self.config.n_query_groups\n total_qkv = q_per_kv + 2 # each group has 1+ queries, 1 key, and 1 value\n qkv = qkv.view(\n B, T, self.config.n_query_groups, total_qkv, self.config.head_size\n )\n qkv = qkv.permute(0, 2, 3, 1, 4) # (B, n_query_groups, total_qkv, T, hs)\n\n # split batched computation into three\n q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)\n\n # maybe repeat k and v if for the non multi-head attention cases\n # training: flash attention requires it\n # inference: multi-query would require a full kv cache so avoid it to limit its memory usage\n if (\n self.config.n_query_groups != self.config.n_head\n and self.config.n_query_groups != 1\n ):\n k = k.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n v = v.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n\n q = q.reshape(B, -1, T, self.config.head_size) # (B, nh_q, T, hs)\n k = k.reshape(B, -1, T, self.config.head_size) # (B, nh_k, T, hs)\n v = v.reshape(B, -1, T, self.config.head_size) # (B, nh_v, T, hs)\n\n q_roped = self.apply_rope(q[..., : self.config.rope_n_elem], cos, sin)\n k_roped = self.apply_rope(k[..., : self.config.rope_n_elem], cos, sin)\n q = torch.cat((q_roped, q[..., self.config.rope_n_elem :]), dim=-1)\n k = torch.cat((k_roped, k[..., self.config.rope_n_elem :]), dim=-1)\n return q, k, v\n\n cfg = configs[\"litgpt\"](model_name)\n # overwrite seq_length\n cfg.seq_len = seq_length\n\n def inputs():\n qkv = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n (cfg.n_head + 2 * cfg.n_query_groups) * cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n cos = torch.randn(\n 1,\n cfg.seq_len,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n sin = torch.randn(\n 1,\n cfg.seq_len,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return qkv, cos, sin\n\n def grads():\n grad = torch.randn(\n cfg.batch_size,\n cfg.n_head,\n cfg.seq_len,\n cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of qkv.grad\n n_elements += (\n cfg.batch_size\n * cfg.seq_len\n * (cfg.n_head + 2 * cfg.n_query_groups)\n * cfg.head_size\n )\n # adding size of sin, cos (saved from forward)\n n_elements += 2 * cfg.seq_len * cfg.rope_n_elem\n # adding size of q, k, v (saved from forward)\n n_elements += 3 * cfg.batch_size * cfg.seq_len * cfg.n_head * cfg.head_size\n # totoal io sizes\n return n_elements * torch.bfloat16.itemsize\n\n return LitgptRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\n# The setup returns a function that would setup benchmark by returning:\n# fwd_model, inputs_fn, grads_fn, iobytes_fn\nrope_setup = {\n \"llama_2_7b_hf\": partial(llama_hf, config_str=\"llama_2_7b_hf\"),\n \"llama_3_8B\": partial(llama_hf, config_str=\"llama_3_8B\"),\n \"hf_qwen2\": hf_qwen2,\n \"hf_phi3\": hf_phi3,\n \"hf_mistral_nemo\": hf_mistral_nemo,\n \"litgpt-gemma-2-9b\": partial(Litgpt, model_name=\"google/gemma-2-9b-it\"),\n \"litgpt-mistral-7b\": partial(\n Litgpt, model_name=\"mistralai/Mistral-7B-Instruct-v0.3\"\n ),\n \"litgpt-meta-llama-3-8B\": partial(\n Litgpt, model_name=\"meta-llama/Meta-Llama-3-8B-Instruct\"\n ),\n \"litgpt-phi3.5-mini\": partial(\n Litgpt,\n model_name=\"microsoft/Phi-3.5-mini-instruct\",","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.LitGPTRope","uri":"program://Fuser/class/benchmarks.python.rope_ops.LitGPTRope#L44-L84","kind":"class","name":"LitGPTRope","path":"benchmarks/python/rope_ops.py","language":"python","start_line":44,"end_line":84,"context_start_line":24,"context_end_line":104,"code":")\n\n\ndef apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:\n head_size = x.size(-1)\n x1 = x[..., : head_size // 2] # (B, nh, T, hs/2)\n x2 = x[..., head_size // 2 :] # (B, nh, T, hs/2)\n rotated = torch.cat((-x2, x1), dim=-1) # (B, nh, T, hs)\n if cos.dim() > 1:\n # batch dimensions must align\n # sin/cos are (B, T, hs) so we unsqeeze -3 for nh\n # we count from back because all of apply_rope does\n cos = cos.unsqueeze(-3)\n sin = sin.unsqueeze(-3)\n\n roped = (x * cos) + (rotated * sin)\n return roped.to(dtype=x.dtype)\n\n\ndef llama_hf(seq_length, *, config_str):\n class LitGPTRope(torch.nn.Module):\n def __init__(self, config):\n super(LitGPTRope, self).__init__()\n self.config = config\n\n def forward(self, qkv, cos, sin):\n B, T, _ = qkv.size()\n # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n q_per_kv = self.config.n_head // self.config.n_query_groups\n total_qkv = q_per_kv + 2 # each group has 1+ queries, 1 key, and 1 value\n qkv = qkv.view(\n B, T, self.config.n_query_groups, total_qkv, self.config.head_size\n )\n qkv = qkv.permute(0, 2, 3, 1, 4) # (B, n_query_groups, total_qkv, T, hs)\n\n # split batched computation into three\n q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)\n\n # maybe repeat k and v if for the non multi-head attention cases\n # training: flash attention requires it\n # inference: multi-query would require a full kv cache so avoid it to limit its memory usage\n # if self.config.n_query_groups != self.config.n_head and (input_pos is None or self.config.n_query_groups != 1):\n if self.config.n_query_groups != self.config.n_head and (\n self.config.n_query_groups != 1\n ):\n k = k.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n v = v.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n\n q = q.reshape(B, -1, T, self.config.head_size) # (B, nh_q, T, hs)\n k = k.reshape(B, -1, T, self.config.head_size) # (B, nh_k, T, hs)\n v = v.reshape(B, -1, T, self.config.head_size) # (B, nh_v, T, hs)\n\n q_roped = apply_rope(q[..., : self.config.rope_n_elem], cos, sin)\n k_roped = apply_rope(k[..., : self.config.rope_n_elem], cos, sin)\n q = torch.cat((q_roped, q[..., self.config.rope_n_elem :]), dim=-1)\n k = torch.cat((k_roped, k[..., self.config.rope_n_elem :]), dim=-1)\n return q, k\n\n cfg = configs[config_str]()\n # overwrite seq_length\n cfg.seq_length = seq_length\n\n def inputs():\n qkv = torch.randn(\n cfg.batches,\n cfg.seq_length,\n cfg.head_size * (cfg.n_head + 2 * cfg.n_query_groups),\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n cos = torch.randn(\n cfg.seq_length,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.inputs","uri":"program://Fuser/function/benchmarks.python.rope_ops.inputs#L833-L858","kind":"function","name":"inputs","path":"benchmarks/python/rope_ops.py","language":"python","start_line":833,"end_line":858,"context_start_line":813,"context_end_line":878,"code":" B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n v = v.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n\n q = q.reshape(B, -1, T, self.config.head_size) # (B, nh_q, T, hs)\n k = k.reshape(B, -1, T, self.config.head_size) # (B, nh_k, T, hs)\n v = v.reshape(B, -1, T, self.config.head_size) # (B, nh_v, T, hs)\n\n q_roped = self.apply_rope(q[..., : self.config.rope_n_elem], cos, sin)\n k_roped = self.apply_rope(k[..., : self.config.rope_n_elem], cos, sin)\n q = torch.cat((q_roped, q[..., self.config.rope_n_elem :]), dim=-1)\n k = torch.cat((k_roped, k[..., self.config.rope_n_elem :]), dim=-1)\n return q, k, v\n\n cfg = configs[\"litgpt\"](model_name)\n # overwrite seq_length\n cfg.seq_len = seq_length\n\n def inputs():\n qkv = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n (cfg.n_head + 2 * cfg.n_query_groups) * cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n cos = torch.randn(\n 1,\n cfg.seq_len,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n sin = torch.randn(\n 1,\n cfg.seq_len,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return qkv, cos, sin\n\n def grads():\n grad = torch.randn(\n cfg.batch_size,\n cfg.n_head,\n cfg.seq_len,\n cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of qkv.grad\n n_elements += (\n cfg.batch_size\n * cfg.seq_len","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.grads","uri":"program://Fuser/function/benchmarks.python.rope_ops.grads#L860-L870","kind":"function","name":"grads","path":"benchmarks/python/rope_ops.py","language":"python","start_line":860,"end_line":870,"context_start_line":840,"context_end_line":890,"code":" requires_grad=True,\n )\n cos = torch.randn(\n 1,\n cfg.seq_len,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n sin = torch.randn(\n 1,\n cfg.seq_len,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return qkv, cos, sin\n\n def grads():\n grad = torch.randn(\n cfg.batch_size,\n cfg.n_head,\n cfg.seq_len,\n cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of qkv.grad\n n_elements += (\n cfg.batch_size\n * cfg.seq_len\n * (cfg.n_head + 2 * cfg.n_query_groups)\n * cfg.head_size\n )\n # adding size of sin, cos (saved from forward)\n n_elements += 2 * cfg.seq_len * cfg.rope_n_elem\n # adding size of q, k, v (saved from forward)\n n_elements += 3 * cfg.batch_size * cfg.seq_len * cfg.n_head * cfg.head_size\n # totoal io sizes\n return n_elements * torch.bfloat16.itemsize\n\n return LitgptRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.iobytes","uri":"program://Fuser/function/benchmarks.python.rope_ops.iobytes#L873-L887","kind":"function","name":"iobytes","path":"benchmarks/python/rope_ops.py","language":"python","start_line":873,"end_line":887,"context_start_line":853,"context_end_line":907,"code":" cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return qkv, cos, sin\n\n def grads():\n grad = torch.randn(\n cfg.batch_size,\n cfg.n_head,\n cfg.seq_len,\n cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n )\n return grad\n\n # Manual IOBytes computes the total bandwidth for thunder backward trace.\n def iobytes():\n n_elements = 0\n # adding size of qkv.grad\n n_elements += (\n cfg.batch_size\n * cfg.seq_len\n * (cfg.n_head + 2 * cfg.n_query_groups)\n * cfg.head_size\n )\n # adding size of sin, cos (saved from forward)\n n_elements += 2 * cfg.seq_len * cfg.rope_n_elem\n # adding size of q, k, v (saved from forward)\n n_elements += 3 * cfg.batch_size * cfg.seq_len * cfg.n_head * cfg.head_size\n # totoal io sizes\n return n_elements * torch.bfloat16.itemsize\n\n return LitgptRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\n# The setup returns a function that would setup benchmark by returning:\n# fwd_model, inputs_fn, grads_fn, iobytes_fn\nrope_setup = {\n \"llama_2_7b_hf\": partial(llama_hf, config_str=\"llama_2_7b_hf\"),\n \"llama_3_8B\": partial(llama_hf, config_str=\"llama_3_8B\"),\n \"hf_qwen2\": hf_qwen2,\n \"hf_phi3\": hf_phi3,\n \"hf_mistral_nemo\": hf_mistral_nemo,\n \"litgpt-gemma-2-9b\": partial(Litgpt, model_name=\"google/gemma-2-9b-it\"),\n \"litgpt-mistral-7b\": partial(\n Litgpt, model_name=\"mistralai/Mistral-7B-Instruct-v0.3\"\n ),\n \"litgpt-meta-llama-3-8B\": partial(\n Litgpt, model_name=\"meta-llama/Meta-Llama-3-8B-Instruct\"\n ),\n \"litgpt-phi3.5-mini\": partial(","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.rotate_half","uri":"program://Fuser/function/benchmarks.python.rope_ops.rotate_half#L604-L608","kind":"function","name":"rotate_half","path":"benchmarks/python/rope_ops.py","language":"python","start_line":604,"end_line":608,"context_start_line":584,"context_end_line":628,"code":" .expand(position_ids.shape[0], -1, 1)\n )\n position_ids_expanded = position_ids[:, None, :].float()\n # Force float32 since bfloat16 loses precision on long contexts\n # See https://github.com/huggingface/transformers/pull/29285\n device_type = x.device.type\n device_type = (\n device_type\n if isinstance(device_type, str) and device_type != \"mps\"\n else \"cpu\"\n )\n with torch.autocast(device_type=device_type, enabled=False):\n freqs = (\n inv_freq_expanded.float() @ position_ids_expanded.float()\n ).transpose(1, 2)\n emb = torch.cat((freqs, freqs), dim=-1)\n cos = emb.cos()\n sin = emb.sin()\n return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)\n\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n\n def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n\n Args:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n Returns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.apply_rotary_pos_emb","uri":"program://Fuser/function/benchmarks.python.rope_ops.apply_rotary_pos_emb#L610-L634","kind":"function","name":"apply_rotary_pos_emb","path":"benchmarks/python/rope_ops.py","language":"python","start_line":610,"end_line":634,"context_start_line":590,"context_end_line":654,"code":" device_type = (\n device_type\n if isinstance(device_type, str) and device_type != \"mps\"\n else \"cpu\"\n )\n with torch.autocast(device_type=device_type, enabled=False):\n freqs = (\n inv_freq_expanded.float() @ position_ids_expanded.float()\n ).transpose(1, 2)\n emb = torch.cat((freqs, freqs), dim=-1)\n cos = emb.cos()\n sin = emb.sin()\n return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)\n\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n\n def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n\n Args:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n Returns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.\n \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n class MistralNemoRope(nn.Module):\n from transformers.models.mistral import MistralConfig\n\n def __init__(self, config: MistralConfig):\n super().__init__()\n self.config = config","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.repeat_kv","uri":"program://Fuser/function/benchmarks.python.rope_ops.repeat_kv#L636-L647","kind":"function","name":"repeat_kv","path":"benchmarks/python/rope_ops.py","language":"python","start_line":636,"end_line":647,"context_start_line":616,"context_end_line":667,"code":" cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n Returns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.\n \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n class MistralNemoRope(nn.Module):\n from transformers.models.mistral import MistralConfig\n\n def __init__(self, config: MistralConfig):\n super().__init__()\n self.config = config\n\n self.attention_dropout = config.attention_dropout\n self.hidden_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = config.head_dim\n self.num_key_value_heads = config.num_key_value_heads\n self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n self.max_position_embeddings = config.max_position_embeddings\n self.rope_theta = config.rope_theta\n self.is_causal = True\n\n self.rotary_emb = MistralRotaryEmbedding(\n self.head_dim,","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.Qwen2Rope","uri":"program://Fuser/class/benchmarks.python.rope_ops.Qwen2Rope#L193-L246","kind":"class","name":"Qwen2Rope","path":"benchmarks/python/rope_ops.py","language":"python","start_line":193,"end_line":246,"context_start_line":173,"context_end_line":266,"code":" \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n class Qwen2Rope(nn.Module):\n from transformers.models.qwen2 import Qwen2Config\n\n def __init__(self, config: Qwen2Config):\n super().__init__()\n self.config = config\n\n self.hidden_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = self.hidden_size // self.num_heads\n self.num_key_value_heads = config.num_key_value_heads\n self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n self.max_position_embeddings = config.max_position_embeddings\n self.rope_theta = config.rope_theta\n self.is_causal = True\n self.attention_dropout = config.attention_dropout\n\n if (self.head_dim * self.num_heads) != self.hidden_size:\n raise ValueError(\n f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n f\" and `num_heads`: {self.num_heads}).\"\n )\n\n def forward(\n self,\n query_in_states: torch.Tensor,\n key_in_states: torch.Tensor,\n value_in_states: torch.Tensor,\n cos: torch.Tensor,\n sin: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n past_key_value = None\n bsz, q_len, _ = query_in_states.size()\n\n query_states = query_in_states.view(\n bsz, q_len, self.num_heads, self.head_dim\n ).transpose(1, 2)\n key_states = key_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n value_states = value_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n\n query_states, key_states = apply_rotary_pos_emb(\n query_states, key_states, cos, sin\n )\n\n if past_key_value is not None:\n assert False\n\n key_states = repeat_kv(key_states, self.num_key_value_groups)\n value_states = repeat_kv(value_states, self.num_key_value_groups)\n return query_states, key_states, value_states\n\n cfg = configs[\"hf_qwen2\"]()\n # overwrite seq_length\n cfg.seq_len = seq_length\n head_dim = cfg.hidden_size // cfg.num_attention_heads\n\n def inputs():\n q = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_attention_heads * head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n k = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_key_value_heads * head_dim,\n device=\"cuda\",","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.Phi3RotaryEmbedding","uri":"program://Fuser/class/benchmarks.python.rope_ops.Phi3RotaryEmbedding#L336-L377","kind":"class","name":"Phi3RotaryEmbedding","path":"benchmarks/python/rope_ops.py","language":"python","start_line":336,"end_line":377,"context_start_line":316,"context_end_line":397,"code":" n_elements += (\n 2 * cfg.batch_size * cfg.num_attention_heads * cfg.seq_len * head_dim\n )\n # adding size of cos, sin\n n_elements += 2 * cfg.batch_size * cfg.seq_len * head_dim\n # adding size of q.grad\n n_elements += cfg.batch_size * cfg.seq_len * cfg.num_attention_heads * head_dim\n # adding size of k.grad, v.grad\n n_elements += (\n 2 * cfg.batch_size * cfg.seq_len * cfg.num_key_value_heads * head_dim\n )\n # adding size of cos.grad, sin.grad\n n_elements += 2 * cfg.batch_size * cfg.seq_len * head_dim\n # scale by dtype size\n return n_elements * torch.bfloat16.itemsize\n\n return Qwen2Rope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_phi3(seq_length):\n class Phi3RotaryEmbedding(nn.Module):\n def __init__(\n self, dim, max_position_embeddings=2048, base=10000.0, device=None\n ):\n super().__init__()\n\n self.dim = dim\n self.max_position_embddings = max_position_embeddings\n self.base = base\n\n inv_freq = 1.0 / (\n self.base\n ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim)\n )\n self.register_buffer(\"inv_freq\", tensor=inv_freq, persistent=False)\n\n @torch.no_grad()\n def forward(self, x, position_ids, seq_len=None):\n # x: [bs, num_attention_heads, seq_len, head_size]\n self.inv_freq.to(x.device)\n inv_freq_expanded = (\n self.inv_freq[None, :, None]\n .float()\n .expand(position_ids.shape[0], -1, 1)\n )\n position_ids_expanded = position_ids[:, None, :].float()\n # Force float32 since bfloat16 loses precision on long contexts\n # See https://github.com/huggingface/transformers/pull/29285\n device_type = x.device.type\n device_type = (\n device_type\n if isinstance(device_type, str) and device_type != \"mps\"\n else \"cpu\"\n )\n with torch.autocast(device_type=device_type, enabled=False):\n freqs = (\n inv_freq_expanded.float() @ position_ids_expanded.float()\n ).transpose(1, 2)\n emb = torch.cat((freqs, freqs), dim=-1)\n cos = emb.cos()\n sin = emb.sin()\n return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.HfPhi3Rope","uri":"program://Fuser/class/benchmarks.python.rope_ops.HfPhi3Rope#L424-L498","kind":"class","name":"HfPhi3Rope","path":"benchmarks/python/rope_ops.py","language":"python","start_line":424,"end_line":498,"context_start_line":404,"context_end_line":518,"code":" cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n Returns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.\n \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n class HfPhi3Rope(nn.Module):\n \"\"\"Multi-headed attention from 'Attention Is All You Need' paper\"\"\"\n\n from transformers.models.phi3 import Phi3Config\n\n def __init__(self, config: Phi3Config):\n super().__init__()\n self.config = config\n\n self.hidden_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = self.hidden_size // self.num_heads\n self.num_key_value_heads = config.num_key_value_heads\n self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n self.max_position_embeddings = config.max_position_embeddings\n self.original_max_position_embeddings = (\n config.original_max_position_embeddings\n )\n self.rope_theta = config.rope_theta\n self.rope_scaling = config.rope_scaling\n self.is_causal = True\n\n if (self.head_dim * self.num_heads) != self.hidden_size:\n raise ValueError(\n f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n f\" and `num_heads`: {self.num_heads}).\"\n )\n\n self.rotary_emb = Phi3RotaryEmbedding(\n self.head_dim,\n max_position_embeddings=self.max_position_embeddings,\n base=self.rope_theta,\n )\n\n def forward(\n self, qkv: torch.Tensor, position_ids: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n past_key_value = None\n bsz, q_len, _ = qkv.size()\n\n query_pos = self.num_heads * self.head_dim\n query_states = qkv[..., :query_pos]\n key_states = qkv[\n ..., query_pos : query_pos + self.num_key_value_heads * self.head_dim\n ]\n value_states = qkv[\n ..., query_pos + self.num_key_value_heads * self.head_dim :\n ]\n\n query_states = query_states.view(\n bsz, q_len, self.num_heads, self.head_dim\n ).transpose(1, 2)\n key_states = key_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n value_states = value_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n\n kv_seq_len = key_states.shape[-2]\n if past_key_value is not None:\n assert False\n cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)\n\n query_states, key_states = apply_rotary_pos_emb(\n query_states, key_states, cos, sin, position_ids\n )\n\n if past_key_value is not None:\n assert False\n\n key_states = repeat_kv(key_states, self.num_key_value_groups)\n value_states = repeat_kv(value_states, self.num_key_value_groups)\n\n return query_states, key_states, value_states\n\n cfg = configs[\"hf_phi3\"]()\n # overwrite seq_length\n cfg.seq_len = seq_length\n head_dim = cfg.hidden_size // cfg.num_attention_heads\n\n def inputs():\n qkv = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_attention_heads * head_dim\n + 2 * (cfg.num_key_value_heads * head_dim),\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n position_ids = torch.arange(0, cfg.seq_len, device=\"cuda\").unsqueeze(0)\n return qkv, position_ids\n\n def grads():","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.MistralRotaryEmbedding","uri":"program://Fuser/class/benchmarks.python.rope_ops.MistralRotaryEmbedding#L558-L602","kind":"class","name":"MistralRotaryEmbedding","path":"benchmarks/python/rope_ops.py","language":"python","start_line":558,"end_line":602,"context_start_line":538,"context_end_line":622,"code":" n_elements += (\n cfg.batch_size\n * cfg.seq_len\n * (\n cfg.num_attention_heads * head_dim\n + 2 * (cfg.num_key_value_heads * head_dim)\n )\n )\n # matmul output size\n n_elements_matmul_out = head_dim / 2 * cfg.seq_len\n # totoal io sizes\n return (\n n_elements * torch.bfloat16.itemsize\n + n_elements_matmul_out * torch.float32.itemsize\n )\n\n return HfPhi3Rope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef hf_mistral_nemo(seq_length):\n class MistralRotaryEmbedding(nn.Module):\n def __init__(\n self, dim, max_position_embeddings=2048, base=10000.0, device=None\n ):\n super().__init__()\n\n self.dim = dim\n self.max_position_embeddings = max_position_embeddings\n self.base = base\n inv_freq = 1.0 / (\n self.base\n ** (\n torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device)\n / self.dim\n )\n )\n self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n\n @torch.no_grad()\n # copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding.forward\n # TODO(joao): add me back asap :)\n def forward(self, x, position_ids):\n # x: [bs, num_attention_heads, seq_len, head_size]\n inv_freq_expanded = (\n self.inv_freq[None, :, None]\n .float()\n .expand(position_ids.shape[0], -1, 1)\n )\n position_ids_expanded = position_ids[:, None, :].float()\n # Force float32 since bfloat16 loses precision on long contexts\n # See https://github.com/huggingface/transformers/pull/29285\n device_type = x.device.type\n device_type = (\n device_type\n if isinstance(device_type, str) and device_type != \"mps\"\n else \"cpu\"\n )\n with torch.autocast(device_type=device_type, enabled=False):\n freqs = (\n inv_freq_expanded.float() @ position_ids_expanded.float()\n ).transpose(1, 2)\n emb = torch.cat((freqs, freqs), dim=-1)\n cos = emb.cos()\n sin = emb.sin()\n return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)\n\n def rotate_half(x):\n \"\"\"Rotates half the hidden dims of the input.\"\"\"\n x1 = x[..., : x.shape[-1] // 2]\n x2 = x[..., x.shape[-1] // 2 :]\n return torch.cat((-x2, x1), dim=-1)\n\n def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n \"\"\"Applies Rotary Position Embedding to the query and key tensors.\n\n Args:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.MistralNemoRope","uri":"program://Fuser/class/benchmarks.python.rope_ops.MistralNemoRope#L649-L702","kind":"class","name":"MistralNemoRope","path":"benchmarks/python/rope_ops.py","language":"python","start_line":649,"end_line":702,"context_start_line":629,"context_end_line":722,"code":" \"\"\"\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos) + (rotate_half(k) * sin)\n return q_embed, k_embed\n\n def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n \"\"\"\n This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,\n num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)\n \"\"\"\n batch, num_key_value_heads, slen, head_dim = hidden_states.shape\n if n_rep == 1:\n return hidden_states\n hidden_states = hidden_states[:, :, None, :, :].expand(\n batch, num_key_value_heads, n_rep, slen, head_dim\n )\n return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)\n\n class MistralNemoRope(nn.Module):\n from transformers.models.mistral import MistralConfig\n\n def __init__(self, config: MistralConfig):\n super().__init__()\n self.config = config\n\n self.attention_dropout = config.attention_dropout\n self.hidden_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = config.head_dim\n self.num_key_value_heads = config.num_key_value_heads\n self.num_key_value_groups = self.num_heads // self.num_key_value_heads\n self.max_position_embeddings = config.max_position_embeddings\n self.rope_theta = config.rope_theta\n self.is_causal = True\n\n self.rotary_emb = MistralRotaryEmbedding(\n self.head_dim,\n max_position_embeddings=self.max_position_embeddings,\n base=self.rope_theta,\n )\n\n def forward(\n self,\n query_in_states: torch.Tensor,\n key_in_states: torch.Tensor,\n value_in_states: torch.Tensor,\n position_ids: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n past_key_value = None\n bsz, q_len, _ = query_in_states.size()\n\n query_states = query_in_states.view(\n bsz, q_len, self.num_heads, self.head_dim\n ).transpose(1, 2)\n key_states = key_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n value_states = value_in_states.view(\n bsz, q_len, self.num_key_value_heads, self.head_dim\n ).transpose(1, 2)\n\n cos, sin = self.rotary_emb(value_states, position_ids)\n query_states, key_states = apply_rotary_pos_emb(\n query_states, key_states, cos, sin\n )\n\n if past_key_value is not None:\n assert False\n\n key_states = repeat_kv(key_states, self.num_key_value_groups)\n value_states = repeat_kv(value_states, self.num_key_value_groups)\n return query_states, key_states, value_states\n\n cfg = configs[\"hf_mistral_nemo\"]()\n # overwrite seq_length\n cfg.seq_len = seq_length\n head_dim = cfg.hidden_size // cfg.num_attention_heads\n\n def inputs():\n q = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_attention_heads * cfg.head_dim,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n k = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n cfg.num_key_value_heads * cfg.head_dim,\n device=\"cuda\",","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.LitgptRope","uri":"program://Fuser/class/benchmarks.python.rope_ops.LitgptRope#L776-L827","kind":"class","name":"LitgptRope","path":"benchmarks/python/rope_ops.py","language":"python","start_line":776,"end_line":827,"context_start_line":756,"context_end_line":847,"code":" # adding size of q.grad\n n_elements += (\n cfg.batch_size * cfg.seq_len * cfg.num_attention_heads * cfg.head_dim\n )\n # adding size of k.grad, v.grad\n n_elements += (\n 2 * cfg.batch_size * cfg.seq_len * cfg.num_key_value_heads * cfg.head_dim\n )\n # matmul output size\n n_elements_matmul_out = head_dim / 2 * cfg.seq_len\n # totoal io sizes\n return (\n n_elements * torch.bfloat16.itemsize\n + n_elements_matmul_out * torch.float32.itemsize\n )\n\n return MistralNemoRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef Litgpt(seq_length, model_name):\n class LitgptRope(torch.nn.Module):\n def __init__(self, config) -> None:\n from litgpt.model import apply_rope\n\n self.fused_apply_rotary_pos_emb_cached = None\n\n super().__init__()\n self.config = config\n self.apply_rope = apply_rope\n\n def forward(\n self,\n qkv: torch.Tensor,\n cos: torch.Tensor,\n sin: torch.Tensor,\n ) -> torch.Tensor:\n B, T, _ = qkv.shape # batch size, sequence length\n\n # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n q_per_kv = self.config.n_head // self.config.n_query_groups\n total_qkv = q_per_kv + 2 # each group has 1+ queries, 1 key, and 1 value\n qkv = qkv.view(\n B, T, self.config.n_query_groups, total_qkv, self.config.head_size\n )\n qkv = qkv.permute(0, 2, 3, 1, 4) # (B, n_query_groups, total_qkv, T, hs)\n\n # split batched computation into three\n q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)\n\n # maybe repeat k and v if for the non multi-head attention cases\n # training: flash attention requires it\n # inference: multi-query would require a full kv cache so avoid it to limit its memory usage\n if (\n self.config.n_query_groups != self.config.n_head\n and self.config.n_query_groups != 1\n ):\n k = k.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n v = v.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n\n q = q.reshape(B, -1, T, self.config.head_size) # (B, nh_q, T, hs)\n k = k.reshape(B, -1, T, self.config.head_size) # (B, nh_k, T, hs)\n v = v.reshape(B, -1, T, self.config.head_size) # (B, nh_v, T, hs)\n\n q_roped = self.apply_rope(q[..., : self.config.rope_n_elem], cos, sin)\n k_roped = self.apply_rope(k[..., : self.config.rope_n_elem], cos, sin)\n q = torch.cat((q_roped, q[..., self.config.rope_n_elem :]), dim=-1)\n k = torch.cat((k_roped, k[..., self.config.rope_n_elem :]), dim=-1)\n return q, k, v\n\n cfg = configs[\"litgpt\"](model_name)\n # overwrite seq_length\n cfg.seq_len = seq_length\n\n def inputs():\n qkv = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n (cfg.n_head + 2 * cfg.n_query_groups) * cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n cos = torch.randn(\n 1,\n cfg.seq_len,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.__init__","uri":"program://Fuser/function/benchmarks.python.rope_ops.__init__#L777-L784","kind":"function","name":"__init__","path":"benchmarks/python/rope_ops.py","language":"python","start_line":777,"end_line":784,"context_start_line":757,"context_end_line":804,"code":" n_elements += (\n cfg.batch_size * cfg.seq_len * cfg.num_attention_heads * cfg.head_dim\n )\n # adding size of k.grad, v.grad\n n_elements += (\n 2 * cfg.batch_size * cfg.seq_len * cfg.num_key_value_heads * cfg.head_dim\n )\n # matmul output size\n n_elements_matmul_out = head_dim / 2 * cfg.seq_len\n # totoal io sizes\n return (\n n_elements * torch.bfloat16.itemsize\n + n_elements_matmul_out * torch.float32.itemsize\n )\n\n return MistralNemoRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef Litgpt(seq_length, model_name):\n class LitgptRope(torch.nn.Module):\n def __init__(self, config) -> None:\n from litgpt.model import apply_rope\n\n self.fused_apply_rotary_pos_emb_cached = None\n\n super().__init__()\n self.config = config\n self.apply_rope = apply_rope\n\n def forward(\n self,\n qkv: torch.Tensor,\n cos: torch.Tensor,\n sin: torch.Tensor,\n ) -> torch.Tensor:\n B, T, _ = qkv.shape # batch size, sequence length\n\n # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n q_per_kv = self.config.n_head // self.config.n_query_groups\n total_qkv = q_per_kv + 2 # each group has 1+ queries, 1 key, and 1 value\n qkv = qkv.view(\n B, T, self.config.n_query_groups, total_qkv, self.config.head_size\n )\n qkv = qkv.permute(0, 2, 3, 1, 4) # (B, n_query_groups, total_qkv, T, hs)\n\n # split batched computation into three\n q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)\n","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.rope_ops.forward","uri":"program://Fuser/function/benchmarks.python.rope_ops.forward#L786-L827","kind":"function","name":"forward","path":"benchmarks/python/rope_ops.py","language":"python","start_line":786,"end_line":827,"context_start_line":766,"context_end_line":847,"code":" # totoal io sizes\n return (\n n_elements * torch.bfloat16.itemsize\n + n_elements_matmul_out * torch.float32.itemsize\n )\n\n return MistralNemoRope(cfg).cuda().bfloat16(), inputs, grads, iobytes\n\n\ndef Litgpt(seq_length, model_name):\n class LitgptRope(torch.nn.Module):\n def __init__(self, config) -> None:\n from litgpt.model import apply_rope\n\n self.fused_apply_rotary_pos_emb_cached = None\n\n super().__init__()\n self.config = config\n self.apply_rope = apply_rope\n\n def forward(\n self,\n qkv: torch.Tensor,\n cos: torch.Tensor,\n sin: torch.Tensor,\n ) -> torch.Tensor:\n B, T, _ = qkv.shape # batch size, sequence length\n\n # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)\n q_per_kv = self.config.n_head // self.config.n_query_groups\n total_qkv = q_per_kv + 2 # each group has 1+ queries, 1 key, and 1 value\n qkv = qkv.view(\n B, T, self.config.n_query_groups, total_qkv, self.config.head_size\n )\n qkv = qkv.permute(0, 2, 3, 1, 4) # (B, n_query_groups, total_qkv, T, hs)\n\n # split batched computation into three\n q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)\n\n # maybe repeat k and v if for the non multi-head attention cases\n # training: flash attention requires it\n # inference: multi-query would require a full kv cache so avoid it to limit its memory usage\n if (\n self.config.n_query_groups != self.config.n_head\n and self.config.n_query_groups != 1\n ):\n k = k.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n v = v.expand(\n B, self.config.n_query_groups, q_per_kv, T, self.config.head_size\n )\n\n q = q.reshape(B, -1, T, self.config.head_size) # (B, nh_q, T, hs)\n k = k.reshape(B, -1, T, self.config.head_size) # (B, nh_k, T, hs)\n v = v.reshape(B, -1, T, self.config.head_size) # (B, nh_v, T, hs)\n\n q_roped = self.apply_rope(q[..., : self.config.rope_n_elem], cos, sin)\n k_roped = self.apply_rope(k[..., : self.config.rope_n_elem], cos, sin)\n q = torch.cat((q_roped, q[..., self.config.rope_n_elem :]), dim=-1)\n k = torch.cat((k_roped, k[..., self.config.rope_n_elem :]), dim=-1)\n return q, k, v\n\n cfg = configs[\"litgpt\"](model_name)\n # overwrite seq_length\n cfg.seq_len = seq_length\n\n def inputs():\n qkv = torch.randn(\n cfg.batch_size,\n cfg.seq_len,\n (cfg.n_head + 2 * cfg.n_query_groups) * cfg.head_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n cos = torch.randn(\n 1,\n cfg.seq_len,\n cfg.rope_n_elem,\n device=\"cuda\",\n dtype=torch.bfloat16,","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_broadcast_add_fwd","uri":"program://Fuser/module/benchmarks.python.test_broadcast_add_fwd#L1-L124","kind":"module","name":"benchmarks.python.test_broadcast_add_fwd","path":"benchmarks/python/test_broadcast_add_fwd.py","language":"python","start_line":1,"end_line":124,"context_start_line":1,"context_end_line":124,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef bcast_add_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n bcast_axis: int,\n contiguous: bool,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False, stride_order=[0]\n )\n stride_order = [0, 1] if not contiguous else [1, 0]\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n stride_order=stride_order,\n )\n\n bcast_shape = [T1.size(0), T1.size(1)]\n bcast_shape[bcast_axis] = 1\n\n # For outer broadcast, if the fn is x + bias, then Thunder only produces one bcast op.\n # The use of unsqueeze generates 2 broadcast ops.\n T2 = fd.ops.broadcast_in_dim(T0, shape=bcast_shape, broadcast_dims=[1 - bcast_axis])\n T3 = fd.ops.broadcast_in_dim(T2, shape=T1.shape(), broadcast_dims=[0, 1])\n\n if dtype in PROMOTE_DTYPES:\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T3 = fd.ops.cast(T3, dtype=DataType.Float)\n\n T4 = fd.ops.add(T1, T3)\n if dtype in PROMOTE_DTYPES:\n T4 = fd.ops.cast(T4, dtype=dtype)\n fd.add_output(T4)\n\n\ndef bcast_add_fwd_fn(inputs: list): # bias, x, bcast_dim\n bias, x, bcast_axis = inputs\n return x + bias.unsqueeze(bcast_axis)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"bcast_axis\", [0, 1], ids=[\"outer\", \"inner\"])\n@pytest.mark.parametrize(\n \"contiguous\", [True, False], ids=[\"contiguous\", \"non-contiguous\"]\n)\n@pytest.mark.pointwise\ndef test_bcast_add_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n bcast_axis: int,\n contiguous: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n bias = torch.randn(size[1 - bcast_axis], dtype=dtype, device=\"cuda\")\n\n input_shape = size if contiguous else (size[1], size[0])\n x = torch.randn(input_shape, dtype=dtype, device=\"cuda\")\n if not contiguous:\n x = x.t()\n assert x.is_contiguous() == contiguous\n with FusionDefinition() as fd:\n bcast_add_fusion(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n bcast_axis=bcast_axis,\n contiguous=contiguous,\n )\n\n if not disable_validation:\n eager_output = bcast_add_fwd_fn([bias, x, bcast_axis])\n fd.validate([bias, x], [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [bias, x])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"bcast_axis\", [0, 1], ids=[\"outer\", \"inner\"])\n@pytest.mark.parametrize(\n \"contiguous\", [True, False], ids=[\"contiguous\", \"non-contiguous\"]\n)\n@pytest.mark.pointwise\ndef test_bcast_add_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n bcast_axis: int,\n contiguous: bool,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n bias = torch.randn(size[1 - bcast_axis], dtype=dtype, device=\"cuda\")\n input_shape = size if contiguous else (size[1], size[0])\n x = torch.randn(input_shape, dtype=dtype, device=\"cuda\")\n if not contiguous:\n x = x.t()\n assert x.is_contiguous() == contiguous\n\n benchmark_fn = with_executor(executor, bcast_add_fwd_fn)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(\n benchmark,\n benchmark_fn,\n [bias, x, bcast_axis],\n )","source_hash":"024d8923c046ef2468d1c9c6e1937abf3816fb2874e5542f303bed3345fb670d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_broadcast_add_fwd.bcast_add_fusion","uri":"program://Fuser/function/benchmarks.python.test_broadcast_add_fwd.bcast_add_fusion#L12-L45","kind":"function","name":"bcast_add_fusion","path":"benchmarks/python/test_broadcast_add_fwd.py","language":"python","start_line":12,"end_line":45,"context_start_line":1,"context_end_line":65,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef bcast_add_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n bcast_axis: int,\n contiguous: bool,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False, stride_order=[0]\n )\n stride_order = [0, 1] if not contiguous else [1, 0]\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n stride_order=stride_order,\n )\n\n bcast_shape = [T1.size(0), T1.size(1)]\n bcast_shape[bcast_axis] = 1\n\n # For outer broadcast, if the fn is x + bias, then Thunder only produces one bcast op.\n # The use of unsqueeze generates 2 broadcast ops.\n T2 = fd.ops.broadcast_in_dim(T0, shape=bcast_shape, broadcast_dims=[1 - bcast_axis])\n T3 = fd.ops.broadcast_in_dim(T2, shape=T1.shape(), broadcast_dims=[0, 1])\n\n if dtype in PROMOTE_DTYPES:\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T3 = fd.ops.cast(T3, dtype=DataType.Float)\n\n T4 = fd.ops.add(T1, T3)\n if dtype in PROMOTE_DTYPES:\n T4 = fd.ops.cast(T4, dtype=dtype)\n fd.add_output(T4)\n\n\ndef bcast_add_fwd_fn(inputs: list): # bias, x, bcast_dim\n bias, x, bcast_axis = inputs\n return x + bias.unsqueeze(bcast_axis)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"bcast_axis\", [0, 1], ids=[\"outer\", \"inner\"])\n@pytest.mark.parametrize(\n \"contiguous\", [True, False], ids=[\"contiguous\", \"non-contiguous\"]\n)\n@pytest.mark.pointwise\ndef test_bcast_add_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n bcast_axis: int,\n contiguous: bool,","source_hash":"024d8923c046ef2468d1c9c6e1937abf3816fb2874e5542f303bed3345fb670d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_broadcast_add_fwd.bcast_add_fwd_fn","uri":"program://Fuser/function/benchmarks.python.test_broadcast_add_fwd.bcast_add_fwd_fn#L48-L50","kind":"function","name":"bcast_add_fwd_fn","path":"benchmarks/python/test_broadcast_add_fwd.py","language":"python","start_line":48,"end_line":50,"context_start_line":28,"context_end_line":70,"code":" )\n\n bcast_shape = [T1.size(0), T1.size(1)]\n bcast_shape[bcast_axis] = 1\n\n # For outer broadcast, if the fn is x + bias, then Thunder only produces one bcast op.\n # The use of unsqueeze generates 2 broadcast ops.\n T2 = fd.ops.broadcast_in_dim(T0, shape=bcast_shape, broadcast_dims=[1 - bcast_axis])\n T3 = fd.ops.broadcast_in_dim(T2, shape=T1.shape(), broadcast_dims=[0, 1])\n\n if dtype in PROMOTE_DTYPES:\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T3 = fd.ops.cast(T3, dtype=DataType.Float)\n\n T4 = fd.ops.add(T1, T3)\n if dtype in PROMOTE_DTYPES:\n T4 = fd.ops.cast(T4, dtype=dtype)\n fd.add_output(T4)\n\n\ndef bcast_add_fwd_fn(inputs: list): # bias, x, bcast_dim\n bias, x, bcast_axis = inputs\n return x + bias.unsqueeze(bcast_axis)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"bcast_axis\", [0, 1], ids=[\"outer\", \"inner\"])\n@pytest.mark.parametrize(\n \"contiguous\", [True, False], ids=[\"contiguous\", \"non-contiguous\"]\n)\n@pytest.mark.pointwise\ndef test_bcast_add_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n bcast_axis: int,\n contiguous: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n bias = torch.randn(size[1 - bcast_axis], dtype=dtype, device=\"cuda\")\n","source_hash":"024d8923c046ef2468d1c9c6e1937abf3816fb2874e5542f303bed3345fb670d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_broadcast_add_fwd.test_bcast_add_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_broadcast_add_fwd.test_bcast_add_nvf_benchmark#L60-L89","kind":"function","name":"test_bcast_add_nvf_benchmark","path":"benchmarks/python/test_broadcast_add_fwd.py","language":"python","start_line":60,"end_line":89,"context_start_line":40,"context_end_line":109,"code":" T3 = fd.ops.cast(T3, dtype=DataType.Float)\n\n T4 = fd.ops.add(T1, T3)\n if dtype in PROMOTE_DTYPES:\n T4 = fd.ops.cast(T4, dtype=dtype)\n fd.add_output(T4)\n\n\ndef bcast_add_fwd_fn(inputs: list): # bias, x, bcast_dim\n bias, x, bcast_axis = inputs\n return x + bias.unsqueeze(bcast_axis)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"bcast_axis\", [0, 1], ids=[\"outer\", \"inner\"])\n@pytest.mark.parametrize(\n \"contiguous\", [True, False], ids=[\"contiguous\", \"non-contiguous\"]\n)\n@pytest.mark.pointwise\ndef test_bcast_add_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n bcast_axis: int,\n contiguous: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n bias = torch.randn(size[1 - bcast_axis], dtype=dtype, device=\"cuda\")\n\n input_shape = size if contiguous else (size[1], size[0])\n x = torch.randn(input_shape, dtype=dtype, device=\"cuda\")\n if not contiguous:\n x = x.t()\n assert x.is_contiguous() == contiguous\n with FusionDefinition() as fd:\n bcast_add_fusion(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n bcast_axis=bcast_axis,\n contiguous=contiguous,\n )\n\n if not disable_validation:\n eager_output = bcast_add_fwd_fn([bias, x, bcast_axis])\n fd.validate([bias, x], [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [bias, x])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"bcast_axis\", [0, 1], ids=[\"outer\", \"inner\"])\n@pytest.mark.parametrize(\n \"contiguous\", [True, False], ids=[\"contiguous\", \"non-contiguous\"]\n)\n@pytest.mark.pointwise\ndef test_bcast_add_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n bcast_axis: int,\n contiguous: bool,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()","source_hash":"024d8923c046ef2468d1c9c6e1937abf3816fb2874e5542f303bed3345fb670d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_broadcast_add_fwd.test_bcast_add_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_broadcast_add_fwd.test_bcast_add_baseline_benchmark#L100-L124","kind":"function","name":"test_bcast_add_baseline_benchmark","path":"benchmarks/python/test_broadcast_add_fwd.py","language":"python","start_line":100,"end_line":124,"context_start_line":80,"context_end_line":124,"code":" bcast_axis=bcast_axis,\n contiguous=contiguous,\n )\n\n if not disable_validation:\n eager_output = bcast_add_fwd_fn([bias, x, bcast_axis])\n fd.validate([bias, x], [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [bias, x])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"bcast_axis\", [0, 1], ids=[\"outer\", \"inner\"])\n@pytest.mark.parametrize(\n \"contiguous\", [True, False], ids=[\"contiguous\", \"non-contiguous\"]\n)\n@pytest.mark.pointwise\ndef test_bcast_add_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n bcast_axis: int,\n contiguous: bool,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n bias = torch.randn(size[1 - bcast_axis], dtype=dtype, device=\"cuda\")\n input_shape = size if contiguous else (size[1], size[0])\n x = torch.randn(input_shape, dtype=dtype, device=\"cuda\")\n if not contiguous:\n x = x.t()\n assert x.is_contiguous() == contiguous\n\n benchmark_fn = with_executor(executor, bcast_add_fwd_fn)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(\n benchmark,\n benchmark_fn,\n [bias, x, bcast_axis],\n )","source_hash":"024d8923c046ef2468d1c9c6e1937abf3816fb2874e5542f303bed3345fb670d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark","uri":"program://Fuser/module/benchmarks.python.layers_for_inference_benchmark#L1-L641","kind":"module","name":"benchmarks.python.layers_for_inference_benchmark","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":1,"end_line":641,"context_start_line":1,"context_end_line":641,"code":"# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD 3-Clause license found in the\n# LICENSE file in the root directory of this source tree.\n#\n# NOTE: `down_size`, and `pack_uint4` are copied from PyTorch's test code.\n#\n# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# NOTE: `pytorch_nvfp4_quantize` and `linear_to_swizzled_128_4` are copied from NVIDIA's Fuser's test code.\n#\n# Pulled from the lightning-thunder repo. Reference:\n# https://github.com/Lightning-AI/lightning-thunder/blob/4d3a3c3a7481efdc6a23cdeea99c3ffd31af5e78/thunder/benchmarks/layers_for_inference_benchmark.py\n\n# fmt: off\n\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING\nimport math\n\nfrom looseversion import LooseVersion\nimport torch\nimport torch.nn as nn\nfrom torch.testing._internal.common_quantized import _f32_to_floatx_unpacked\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Replicate\n\nif TYPE_CHECKING:\n from transformers.models.llama4.modeling_llama4 import Llama4TextMoe\n\n\n__all__ = [\n \"GroupedLinear\",\n \"GroupedSwiGLU\",\n \"Llama4MoE\",\n \"NVFP4InferenceGroupedLinear\",\n \"NVFP4InferenceGroupedSwiGLU\",\n \"nvfuser_f16a_nvfp4weight_scaled_grouped_mm\",\n]\n\n\n# Ref: https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L972-L974\ndef down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n\n# Ref: https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L977-L982\ndef pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n\n# Ref: Based on `_bfloat16_to_float4_e2m1fn_x2` of https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L985-L990\ndef to_fp4(x: torch.Tensor) -> torch.Tensor:\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L8-L10\nFLOAT4_E2M1_MAX = 6.0\nFLOAT8_E4M3_EPS = torch.finfo(torch.float8_e4m3fn).tiny\nFLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L125-L148\ndef pytorch_nvfp4_quantize(a, a_global_scale):\n BLOCK_SIZE = 16\n assert a.size(-1) % BLOCK_SIZE == 0, (\n \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n )\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n\n # Find absolute maximum along blockwise dimension\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n block_scale_fp32 = (max_abs / FLOAT4_E2M1_MAX).float()\n\n scaled_block_scale_fp32 = block_scale_fp32 * a_global_scale\n scaled_block_scale_fp8 = torch.clamp(\n scaled_block_scale_fp32,\n min=FLOAT8_E4M3_EPS,\n max=FLOAT8_E4M3_MAX,\n ).to(torch.float8_e4m3fn)\n scaled_block_scale_fp8_fp32 = scaled_block_scale_fp8.to(torch.float)\n total_scale = scaled_block_scale_fp8_fp32 / a_global_scale\n a_scaled = a_fp32 / total_scale.unsqueeze(-1)\n a_scaled = torch.clamp(a_scaled, -FLOAT4_E2M1_MAX, FLOAT4_E2M1_MAX)\n a_scaled = a_scaled.view(original_shape)\n return to_fp4(a_scaled), scaled_block_scale_fp8\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L63-L82\n# apply swizzled on block scaling factor:\n# 1. apply padding to [mn_t * 128 , k_t * 4]\n# 2. apply swizzle\ndef linear_to_swizzled_128_4(a_sf_linear: torch.Tensor):\n mn, sf_k = a_sf_linear.shape\n m_tiles = (mn + 128 - 1) // 128\n mn_padded = m_tiles * 128\n k_tiles = (sf_k + 4 - 1) // 4\n k_padded = k_tiles * 4\n if mn_padded != mn or k_padded != sf_k:\n a_sf_padded = torch.empty(mn_padded, k_padded, dtype=a_sf_linear.dtype, device=a_sf_linear.device)\n a_sf_padded[0:mn, 0:sf_k] = a_sf_linear\n else:\n a_sf_padded = a_sf_linear\n # details about layout requirement on block-wise scaling factor\n # https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#scale-factor-layouts\n tmp = torch.reshape(a_sf_padded, (m_tiles, 4, 32, k_tiles, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, k_padded)[:mn, :sf_k]\n\n\n@torch.inference_mode()\ndef quantize_linear_weight_to_nvfp4(\n weight: torch.Tensor | nn.Parameter,\n) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:\n \"\"\"Quantize weight to nvfp4, returning (packed) e2m1 weight, e4m3 scale factor, fp32 global scale.\"\"\"\n global_scale = ((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / weight.float().abs().amax()).to(torch.float32)\n fp4_weight, weight_scaling_factor = pytorch_nvfp4_quantize(weight, global_scale)\n weight_scale_interleaved = linear_to_swizzled_128_4(weight_scaling_factor)\n return fp4_weight, weight_scale_interleaved, global_scale\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L151-L152\ndef round_up(x: int, y: int) -> int:\n return (x + y - 1) // y * y\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L55-L60\n# restore swizzled on block scaling factor:\n# 1. restore swizzle\n# 2. removes padding via slicing to [:mn, :k]\ndef swizzled_to_linear_128_4(a_sf_swizzled: torch.Tensor, mn, k):\n mn_padded, sf_k_padded = a_sf_swizzled.shape\n m_tiles = mn_padded // 128\n k_tiles = sf_k_padded // 4\n tmp = torch.reshape(a_sf_swizzled, (m_tiles, k_tiles, 32, 4, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, sf_k_padded)[:mn, :k]\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/main/tests/python/direct_utils/narrow_precision.py#L46-L106\ndef unpack_fp4(x: torch.Tensor) -> torch.Tensor:\n repeated = x.repeat_interleave(2, dim=1)\n repeated[:, 0::2] &= 0x0F\n repeated[:, 1::2] >>= 4\n return repeated\n\n\n_FP4_LUT = torch.tensor(\n [\n 0.0, # 0: 0000 - zero\n 0.5, # 1: 0001 - smallest positive normal\n 1.0, # 2: 0010\n 1.5, # 3: 0011\n 2.0, # 4: 0100\n 3.0, # 5: 0101\n 4.0, # 6: 0110\n 6.0, # 7: 0111 - largest positive normal\n -0.0, # 8: 1000 - negative zero\n -0.5, # 9: 1001 - smallest negative normal\n -1.0, # 10: 1010\n -1.5, # 11: 1011\n -2.0, # 12: 1100\n -3.0, # 13: 1101\n -4.0, # 14: 1110\n -6.0, # 15: 1111 - largest negative normal\n ],\n dtype=torch.float32,\n device=\"cuda\",\n)\n\n\ndef fp4_to_fp32(fp4: torch.Tensor) -> torch.Tensor:\n # Convert FP4 indices to their corresponding floating point values\n # Each index (0-15) represents a 4-bit FP4 value in E2M1 format\n # Values based on the FP4 E2M1 specification\n # NOTE: move to device triggers error in inductor. We hard code the lookup Tensor on cuda and remove the cast as a WAR `fp4_lut = _FP4_LUT.to(fp4.device)`\n return _FP4_LUT[fp4.to(torch.long)]\n\n\ndef dequantize_fp4(\n qx: torch.Tensor, sx: torch.Tensor, amax: torch.Tensor\n) -> torch.Tensor:\n sf = sx.repeat_interleave(16, dim=1).view(torch.float8_e4m3fn).to(torch.float32)\n dqx = fp4_to_fp32(unpack_fp4(qx))\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf * (amax / (6.0 * 448))\n return dequant\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This custom op is registered with nvfuser translator in benchmark_inference.py\n# using _register_nvfuser_translator. See benchmark_inference._register_nvfp4_ops().\n@torch.library.custom_op(\"nvf_cutlass::f16a_nvfp4weight_scaled_grouped_mm\", mutates_args=())\ndef nvfuser_f16a_nvfp4weight_scaled_grouped_mm(\n activation: torch.Tensor,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor,\n problem_sizes: torch.Tensor,\n) -> torch.Tensor:\n # NOTE: weight needs to be stored as (g, n, k), we'll transpose in order to hit fast kernel\n hp_weight = torch.empty(\n (fp4_weight.size(0), fp4_weight.size(2), fp4_weight.size(1) * 2),\n device=activation.device,\n dtype=activation.dtype,\n )\n for i in range(fp4_weight.size(0)):\n hp_weight[i] = dequantize_to_dtype(\n fp4_weight[i].transpose(1, 0), weight_scaling_factor[i], weight_global_scale[i], activation.dtype, fp4_weight.device, 16\n )\n return grouped_mm(activation, hp_weight.transpose(2, 1), offsets)\n\n\n@torch.library.register_fake(\"nvf_cutlass::f16a_nvfp4weight_scaled_grouped_mm\")\ndef _(\n activation: torch.Tensor,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor,\n problem_sizes: torch.Tensor,\n) -> torch.Tensor:\n # fp4_weight shape: (groups, in_features // 2, out_features)\n # Validate that activation has at least 1 dimension\n if activation.ndim == 0:\n raise ValueError(f\"Expected activation to have at least 1 dimension, got {activation.ndim}\")\n\n if (\n len(\n {\n t.device\n for t in [\n activation,\n fp4_weight,\n weight_scaling_factor,\n weight_global_scale,\n offsets,\n blockscale_offsets,\n problem_sizes,\n ]\n }\n )\n != 1\n ):\n raise ValueError(\"Expected all inputs to be on the same device.\")\n\n # After unpacking: (groups, in_features, out_features)\n # Output shape should match activation.shape[:-1] + (out_features,)\n # This handles both 2D (tokens, hidden) and 3D (batch, seq_len, hidden) inputs\n out_features = fp4_weight.size(2)\n output_shape = activation.shape[:-1] + (out_features,)\n return torch.empty(output_shape, device=activation.device, dtype=torch.bfloat16)\n\n\nclass SwiGLU(nn.Module):\n def __init__(self, hidden_size: int, intermediate_size: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False, dtype=dtype, device=device)\n self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False, dtype=dtype, device=device)\n self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False, dtype=dtype, device=device)\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.down_proj(torch.nn.functional.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))\n\n\ndef _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n if isinstance(offsets, DTensor):\n assert offsets.placements == (Replicate(),)\n offsets = offsets.to_local()\n\n for offset in offsets:\n group_sizes.append(offset - prev)\n prev = offset\n return group_sizes\n\n\nif LooseVersion(torch.__version__) >= LooseVersion(\"2.8.0\"):\n # Required -- otherwise there is a graph-break.\n _grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\nelse:\n _grouped_mm = None\n\n\ndef grouped_mm(a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n if _grouped_mm is not None:\n return _grouped_mm(a, b, offsets)\n\n group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for idx, group_a in enumerate(a.split(group_sizes)):\n group_outs.append(group_a @ b[idx])\n return torch.cat(group_outs)\n\n\nclass GroupedLinear(nn.Module):\n def __init__(self, groups: int, in_features: int, out_features: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.weight = nn.Parameter(torch.empty(groups, out_features, in_features, dtype=dtype, device=device))\n # Initialize the weight in the same way as nn.Linear\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n return grouped_mm(hidden_states, self.weight.transpose(-1, -2), offsets)\n\n\n@torch.inference_mode()\ndef quantize_grouped_linear_weight_to_nvfp4(\n weight: torch.Tensor | nn.Parameter,\n) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"Quantize grouped linear's weight to nvfp4\n\n Args:\n weight: Parameter of `GroupedLinear` of [g, n, k]\n\n Returns:\n fp4_weight: [g, k // 2, n]\n scale_factors: [g, n, k // 16]\n global_scales: [g]\n\n Note:\n The reason we choose different layout of weight is to avoid performance\n regression for bf16. See\n https://github.com/Lightning-AI/lightning-thunder/pull/2659\n \"\"\"\n assert weight.ndim == 3, \"Weight must be a 3D tensor\"\n\n device: torch.device = weight.device\n g, n, k = weight.size()\n\n with device:\n fp4_weight = torch.empty((g, n, k // 2), dtype=torch.float4_e2m1fn_x2)\n global_scales = torch.empty((g,), dtype=torch.float32)\n scale_factors = torch.empty((g, n, k // 16), dtype=torch.float8_e4m3fn)\n\n weight = weight.contiguous()\n for i in range(g):\n cur_weight = weight[i]\n global_scales[i] = cur_weight.abs().amax()\n cur_fp4_weight, cur_scale_factors = pytorch_nvfp4_quantize(cur_weight, global_scales[i])\n fp4_weight[i] = cur_fp4_weight\n scale_factors[i] = linear_to_swizzled_128_4(cur_scale_factors)\n\n return fp4_weight.transpose(-1, -2), scale_factors, global_scales\n\n\nclass NVFP4InferenceGroupedLinear(nn.Module):\n def __init__(\n self,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n ) -> None:\n super().__init__()\n self.register_buffer(\"fp4_weight\", fp4_weight)\n self.register_buffer(\"weight_scaling_factor\", weight_scaling_factor)\n self.register_buffer(\"weight_global_scale\", weight_global_scale)\n\n @property\n def out_features(self) -> int:\n return self.fp4_weight.size(2)\n\n @property\n def in_features(self) -> int:\n return self.fp4_weight.size(1) * 2\n\n @staticmethod\n def compute_auxiliary_tensors(\n hidden_states: torch.Tensor,\n offsets: torch.Tensor,\n out_features: int,\n ) -> tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Compute blockscale_offsets and problem_sizes for grouped mm.\n\n These can be computed once and reused across multiple forward calls with the same offsets.\n \"\"\"\n # expanded offsets to contain the total number of tokens.\n expanded_offsets = torch.cat([offsets, torch.tensor([hidden_states.size(0)], device=offsets.device)])\n tokens_per_group = expanded_offsets[1:] - expanded_offsets[:-1]\n problem_sizes = torch.stack(\n [\n tokens_per_group,\n torch.full_like(tokens_per_group, out_features),\n torch.full_like(tokens_per_group, hidden_states.size(1)),\n ],\n dim=1,\n )\n # Calculate block-scale offsets: round up to 128, then cumsum with initial 0\n rounded_tokens = ((tokens_per_group + 127) // 128) * 128\n blockscale_offsets = torch.cat(\n [\n torch.zeros(1, dtype=torch.int32, device=tokens_per_group.device),\n torch.cumsum(rounded_tokens, 0, dtype=torch.int32),\n ]\n )[0:-1]\n return blockscale_offsets, problem_sizes\n\n # TODO: Update this accordingly to the progress of nvfp4 kernel implementation.\n def forward(\n self,\n hidden_states: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor | None = None,\n problem_sizes: torch.Tensor | None = None,\n ) -> torch.Tensor:\n if blockscale_offsets is None or problem_sizes is None:\n # Compute them if not provided (backward compatibility)\n out_features = self.out_features\n blockscale_offsets, problem_sizes = self.compute_auxiliary_tensors(hidden_states, offsets, out_features)\n return torch.ops.nvf_cutlass.f16a_nvfp4weight_scaled_grouped_mm(\n hidden_states,\n self.fp4_weight,\n self.weight_scaling_factor,\n self.weight_global_scale,\n offsets,\n blockscale_offsets,\n problem_sizes,\n )\n\n @staticmethod\n def from_grouped_linear(grouped_linear: GroupedLinear, fqn: str | None = None) -> NVFP4InferenceGroupedLinear:\n \"\"\"Create an NVFP4InferenceGroupedLinear from a GroupedLinear.\n\n Args:\n grouped_linear (GroupedLinear): The source GroupedLinear.\n fqn (str or None): Fully qualified name. Currently unused; reserved for future use or compatibility.\n \"\"\"\n weight = grouped_linear.weight\n fp4_weight, weight_scaling_factor, weight_global_scale = quantize_grouped_linear_weight_to_nvfp4(weight)\n return NVFP4InferenceGroupedLinear(\n fp4_weight,\n weight_scaling_factor,\n weight_global_scale,\n )\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size, dtype, device)\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n return self.down_proj(\n torch.nn.functional.silu(self.gate_proj(hidden_states, offsets)) * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass NVFP4InferenceGroupedSwiGLU(nn.Module):\n \"\"\"NVFP4 GroupedSwiGLU that efficiently reuses auxiliary tensor computations.\"\"\"\n\n def __init__(\n self,\n gate_proj: NVFP4InferenceGroupedLinear,\n up_proj: NVFP4InferenceGroupedLinear,\n down_proj: NVFP4InferenceGroupedLinear,\n ):\n super().__init__()\n self.gate_proj = gate_proj\n self.up_proj = up_proj\n self.down_proj = down_proj\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n # Compute auxiliary tensors once for all three operations\n intermediate_features = self.gate_proj.out_features\n blockscale_offsets_gate, problem_sizes_gate = NVFP4InferenceGroupedLinear.compute_auxiliary_tensors(\n hidden_states, offsets, intermediate_features\n )\n\n gate_out = self.gate_proj(hidden_states, offsets, blockscale_offsets_gate, problem_sizes_gate)\n up_out = self.up_proj(hidden_states, offsets, blockscale_offsets_gate, problem_sizes_gate)\n\n intermediate = torch.nn.functional.silu(gate_out) * up_out\n\n # For down_proj, we need different problem_sizes (different output features)\n hidden_features = self.down_proj.out_features\n blockscale_offsets_down, problem_sizes_down = NVFP4InferenceGroupedLinea\n# ... truncated ...","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":true} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.down_size","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.down_size#L46-L48","kind":"function","name":"down_size","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":46,"end_line":48,"context_start_line":26,"context_end_line":68,"code":"import torch.nn as nn\nfrom torch.testing._internal.common_quantized import _f32_to_floatx_unpacked\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Replicate\n\nif TYPE_CHECKING:\n from transformers.models.llama4.modeling_llama4 import Llama4TextMoe\n\n\n__all__ = [\n \"GroupedLinear\",\n \"GroupedSwiGLU\",\n \"Llama4MoE\",\n \"NVFP4InferenceGroupedLinear\",\n \"NVFP4InferenceGroupedSwiGLU\",\n \"nvfuser_f16a_nvfp4weight_scaled_grouped_mm\",\n]\n\n\n# Ref: https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L972-L974\ndef down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n\n# Ref: https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L977-L982\ndef pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n\n# Ref: Based on `_bfloat16_to_float4_e2m1fn_x2` of https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L985-L990\ndef to_fp4(x: torch.Tensor) -> torch.Tensor:\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L8-L10","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.pack_uint4","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.pack_uint4#L52-L57","kind":"function","name":"pack_uint4","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":52,"end_line":57,"context_start_line":32,"context_end_line":77,"code":" from transformers.models.llama4.modeling_llama4 import Llama4TextMoe\n\n\n__all__ = [\n \"GroupedLinear\",\n \"GroupedSwiGLU\",\n \"Llama4MoE\",\n \"NVFP4InferenceGroupedLinear\",\n \"NVFP4InferenceGroupedSwiGLU\",\n \"nvfuser_f16a_nvfp4weight_scaled_grouped_mm\",\n]\n\n\n# Ref: https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L972-L974\ndef down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n\n# Ref: https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L977-L982\ndef pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n\n# Ref: Based on `_bfloat16_to_float4_e2m1fn_x2` of https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L985-L990\ndef to_fp4(x: torch.Tensor) -> torch.Tensor:\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L8-L10\nFLOAT4_E2M1_MAX = 6.0\nFLOAT8_E4M3_EPS = torch.finfo(torch.float8_e4m3fn).tiny\nFLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L125-L148\ndef pytorch_nvfp4_quantize(a, a_global_scale):\n BLOCK_SIZE = 16\n assert a.size(-1) % BLOCK_SIZE == 0, (","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.to_fp4","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.to_fp4#L61-L65","kind":"function","name":"to_fp4","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":61,"end_line":65,"context_start_line":41,"context_end_line":85,"code":" \"nvfuser_f16a_nvfp4weight_scaled_grouped_mm\",\n]\n\n\n# Ref: https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L972-L974\ndef down_size(size):\n assert size[-1] % 2 == 0, f\"{size} last dim not divisible by two\"\n return (*size[:-1], size[-1] // 2)\n\n\n# Ref: https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L977-L982\ndef pack_uint4(uint8_data) -> torch.Tensor:\n # converting to uint8 for operations\n shape = uint8_data.shape\n assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n\n# Ref: Based on `_bfloat16_to_float4_e2m1fn_x2` of https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L985-L990\ndef to_fp4(x: torch.Tensor) -> torch.Tensor:\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L8-L10\nFLOAT4_E2M1_MAX = 6.0\nFLOAT8_E4M3_EPS = torch.finfo(torch.float8_e4m3fn).tiny\nFLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L125-L148\ndef pytorch_nvfp4_quantize(a, a_global_scale):\n BLOCK_SIZE = 16\n assert a.size(-1) % BLOCK_SIZE == 0, (\n \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n )\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n\n # Find absolute maximum along blockwise dimension","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.pytorch_nvfp4_quantize","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.pytorch_nvfp4_quantize#L75-L100","kind":"function","name":"pytorch_nvfp4_quantize","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":75,"end_line":100,"context_start_line":55,"context_end_line":120,"code":" assert shape[-1] % 2 == 0\n uint8_data = uint8_data.contiguous().view(-1)\n return (uint8_data[1::2] << 4 | uint8_data[::2]).view(down_size(shape))\n\n\n# Ref: Based on `_bfloat16_to_float4_e2m1fn_x2` of https://github.com/pytorch/pytorch/blob/bffc7dd1/test/test_matmul_cuda.py#L985-L990\ndef to_fp4(x: torch.Tensor) -> torch.Tensor:\n x = _f32_to_floatx_unpacked(x.float(), ebits=2, mbits=1)\n x = pack_uint4(x)\n x = x.view(torch.float4_e2m1fn_x2)\n return x\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L8-L10\nFLOAT4_E2M1_MAX = 6.0\nFLOAT8_E4M3_EPS = torch.finfo(torch.float8_e4m3fn).tiny\nFLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L125-L148\ndef pytorch_nvfp4_quantize(a, a_global_scale):\n BLOCK_SIZE = 16\n assert a.size(-1) % BLOCK_SIZE == 0, (\n \"The inner-most dim must be divisible by block_size; Padding is not implemented.\"\n )\n assert a.is_contiguous(), \"Only contiguous tensors are supported.\"\n\n original_shape = a.shape\n a_fp32 = a.float().reshape(original_shape[0], -1, BLOCK_SIZE)\n\n # Find absolute maximum along blockwise dimension\n max_abs = torch.amax(torch.abs(a_fp32), dim=-1)\n block_scale_fp32 = (max_abs / FLOAT4_E2M1_MAX).float()\n\n scaled_block_scale_fp32 = block_scale_fp32 * a_global_scale\n scaled_block_scale_fp8 = torch.clamp(\n scaled_block_scale_fp32,\n min=FLOAT8_E4M3_EPS,\n max=FLOAT8_E4M3_MAX,\n ).to(torch.float8_e4m3fn)\n scaled_block_scale_fp8_fp32 = scaled_block_scale_fp8.to(torch.float)\n total_scale = scaled_block_scale_fp8_fp32 / a_global_scale\n a_scaled = a_fp32 / total_scale.unsqueeze(-1)\n a_scaled = torch.clamp(a_scaled, -FLOAT4_E2M1_MAX, FLOAT4_E2M1_MAX)\n a_scaled = a_scaled.view(original_shape)\n return to_fp4(a_scaled), scaled_block_scale_fp8\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L63-L82\n# apply swizzled on block scaling factor:\n# 1. apply padding to [mn_t * 128 , k_t * 4]\n# 2. apply swizzle\ndef linear_to_swizzled_128_4(a_sf_linear: torch.Tensor):\n mn, sf_k = a_sf_linear.shape\n m_tiles = (mn + 128 - 1) // 128\n mn_padded = m_tiles * 128\n k_tiles = (sf_k + 4 - 1) // 4\n k_padded = k_tiles * 4\n if mn_padded != mn or k_padded != sf_k:\n a_sf_padded = torch.empty(mn_padded, k_padded, dtype=a_sf_linear.dtype, device=a_sf_linear.device)\n a_sf_padded[0:mn, 0:sf_k] = a_sf_linear\n else:\n a_sf_padded = a_sf_linear\n # details about layout requirement on block-wise scaling factor\n # https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#scale-factor-layouts\n tmp = torch.reshape(a_sf_padded, (m_tiles, 4, 32, k_tiles, 4))","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.linear_to_swizzled_128_4","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.linear_to_swizzled_128_4#L107-L121","kind":"function","name":"linear_to_swizzled_128_4","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":107,"end_line":121,"context_start_line":87,"context_end_line":141,"code":" block_scale_fp32 = (max_abs / FLOAT4_E2M1_MAX).float()\n\n scaled_block_scale_fp32 = block_scale_fp32 * a_global_scale\n scaled_block_scale_fp8 = torch.clamp(\n scaled_block_scale_fp32,\n min=FLOAT8_E4M3_EPS,\n max=FLOAT8_E4M3_MAX,\n ).to(torch.float8_e4m3fn)\n scaled_block_scale_fp8_fp32 = scaled_block_scale_fp8.to(torch.float)\n total_scale = scaled_block_scale_fp8_fp32 / a_global_scale\n a_scaled = a_fp32 / total_scale.unsqueeze(-1)\n a_scaled = torch.clamp(a_scaled, -FLOAT4_E2M1_MAX, FLOAT4_E2M1_MAX)\n a_scaled = a_scaled.view(original_shape)\n return to_fp4(a_scaled), scaled_block_scale_fp8\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L63-L82\n# apply swizzled on block scaling factor:\n# 1. apply padding to [mn_t * 128 , k_t * 4]\n# 2. apply swizzle\ndef linear_to_swizzled_128_4(a_sf_linear: torch.Tensor):\n mn, sf_k = a_sf_linear.shape\n m_tiles = (mn + 128 - 1) // 128\n mn_padded = m_tiles * 128\n k_tiles = (sf_k + 4 - 1) // 4\n k_padded = k_tiles * 4\n if mn_padded != mn or k_padded != sf_k:\n a_sf_padded = torch.empty(mn_padded, k_padded, dtype=a_sf_linear.dtype, device=a_sf_linear.device)\n a_sf_padded[0:mn, 0:sf_k] = a_sf_linear\n else:\n a_sf_padded = a_sf_linear\n # details about layout requirement on block-wise scaling factor\n # https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#scale-factor-layouts\n tmp = torch.reshape(a_sf_padded, (m_tiles, 4, 32, k_tiles, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, k_padded)[:mn, :sf_k]\n\n\n@torch.inference_mode()\ndef quantize_linear_weight_to_nvfp4(\n weight: torch.Tensor | nn.Parameter,\n) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:\n \"\"\"Quantize weight to nvfp4, returning (packed) e2m1 weight, e4m3 scale factor, fp32 global scale.\"\"\"\n global_scale = ((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / weight.float().abs().amax()).to(torch.float32)\n fp4_weight, weight_scaling_factor = pytorch_nvfp4_quantize(weight, global_scale)\n weight_scale_interleaved = linear_to_swizzled_128_4(weight_scaling_factor)\n return fp4_weight, weight_scale_interleaved, global_scale\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L151-L152\ndef round_up(x: int, y: int) -> int:\n return (x + y - 1) // y * y\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L55-L60\n# restore swizzled on block scaling factor:","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.quantize_linear_weight_to_nvfp4","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.quantize_linear_weight_to_nvfp4#L125-L132","kind":"function","name":"quantize_linear_weight_to_nvfp4","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":125,"end_line":132,"context_start_line":105,"context_end_line":152,"code":"# 1. apply padding to [mn_t * 128 , k_t * 4]\n# 2. apply swizzle\ndef linear_to_swizzled_128_4(a_sf_linear: torch.Tensor):\n mn, sf_k = a_sf_linear.shape\n m_tiles = (mn + 128 - 1) // 128\n mn_padded = m_tiles * 128\n k_tiles = (sf_k + 4 - 1) // 4\n k_padded = k_tiles * 4\n if mn_padded != mn or k_padded != sf_k:\n a_sf_padded = torch.empty(mn_padded, k_padded, dtype=a_sf_linear.dtype, device=a_sf_linear.device)\n a_sf_padded[0:mn, 0:sf_k] = a_sf_linear\n else:\n a_sf_padded = a_sf_linear\n # details about layout requirement on block-wise scaling factor\n # https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#scale-factor-layouts\n tmp = torch.reshape(a_sf_padded, (m_tiles, 4, 32, k_tiles, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, k_padded)[:mn, :sf_k]\n\n\n@torch.inference_mode()\ndef quantize_linear_weight_to_nvfp4(\n weight: torch.Tensor | nn.Parameter,\n) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:\n \"\"\"Quantize weight to nvfp4, returning (packed) e2m1 weight, e4m3 scale factor, fp32 global scale.\"\"\"\n global_scale = ((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / weight.float().abs().amax()).to(torch.float32)\n fp4_weight, weight_scaling_factor = pytorch_nvfp4_quantize(weight, global_scale)\n weight_scale_interleaved = linear_to_swizzled_128_4(weight_scaling_factor)\n return fp4_weight, weight_scale_interleaved, global_scale\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L151-L152\ndef round_up(x: int, y: int) -> int:\n return (x + y - 1) // y * y\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L55-L60\n# restore swizzled on block scaling factor:\n# 1. restore swizzle\n# 2. removes padding via slicing to [:mn, :k]\ndef swizzled_to_linear_128_4(a_sf_swizzled: torch.Tensor, mn, k):\n mn_padded, sf_k_padded = a_sf_swizzled.shape\n m_tiles = mn_padded // 128\n k_tiles = sf_k_padded // 4\n tmp = torch.reshape(a_sf_swizzled, (m_tiles, k_tiles, 32, 4, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, sf_k_padded)[:mn, :k]\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/main/tests/python/direct_utils/narrow_precision.py#L46-L106\ndef unpack_fp4(x: torch.Tensor) -> torch.Tensor:","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.round_up","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.round_up#L136-L137","kind":"function","name":"round_up","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":136,"end_line":137,"context_start_line":116,"context_end_line":157,"code":" else:\n a_sf_padded = a_sf_linear\n # details about layout requirement on block-wise scaling factor\n # https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#scale-factor-layouts\n tmp = torch.reshape(a_sf_padded, (m_tiles, 4, 32, k_tiles, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, k_padded)[:mn, :sf_k]\n\n\n@torch.inference_mode()\ndef quantize_linear_weight_to_nvfp4(\n weight: torch.Tensor | nn.Parameter,\n) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:\n \"\"\"Quantize weight to nvfp4, returning (packed) e2m1 weight, e4m3 scale factor, fp32 global scale.\"\"\"\n global_scale = ((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / weight.float().abs().amax()).to(torch.float32)\n fp4_weight, weight_scaling_factor = pytorch_nvfp4_quantize(weight, global_scale)\n weight_scale_interleaved = linear_to_swizzled_128_4(weight_scaling_factor)\n return fp4_weight, weight_scale_interleaved, global_scale\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L151-L152\ndef round_up(x: int, y: int) -> int:\n return (x + y - 1) // y * y\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L55-L60\n# restore swizzled on block scaling factor:\n# 1. restore swizzle\n# 2. removes padding via slicing to [:mn, :k]\ndef swizzled_to_linear_128_4(a_sf_swizzled: torch.Tensor, mn, k):\n mn_padded, sf_k_padded = a_sf_swizzled.shape\n m_tiles = mn_padded // 128\n k_tiles = sf_k_padded // 4\n tmp = torch.reshape(a_sf_swizzled, (m_tiles, k_tiles, 32, 4, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, sf_k_padded)[:mn, :k]\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/main/tests/python/direct_utils/narrow_precision.py#L46-L106\ndef unpack_fp4(x: torch.Tensor) -> torch.Tensor:\n repeated = x.repeat_interleave(2, dim=1)\n repeated[:, 0::2] &= 0x0F\n repeated[:, 1::2] >>= 4\n return repeated\n","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.swizzled_to_linear_128_4","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.swizzled_to_linear_128_4#L144-L149","kind":"function","name":"swizzled_to_linear_128_4","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":144,"end_line":149,"context_start_line":124,"context_end_line":169,"code":"@torch.inference_mode()\ndef quantize_linear_weight_to_nvfp4(\n weight: torch.Tensor | nn.Parameter,\n) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:\n \"\"\"Quantize weight to nvfp4, returning (packed) e2m1 weight, e4m3 scale factor, fp32 global scale.\"\"\"\n global_scale = ((FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / weight.float().abs().amax()).to(torch.float32)\n fp4_weight, weight_scaling_factor = pytorch_nvfp4_quantize(weight, global_scale)\n weight_scale_interleaved = linear_to_swizzled_128_4(weight_scaling_factor)\n return fp4_weight, weight_scale_interleaved, global_scale\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L151-L152\ndef round_up(x: int, y: int) -> int:\n return (x + y - 1) // y * y\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L55-L60\n# restore swizzled on block scaling factor:\n# 1. restore swizzle\n# 2. removes padding via slicing to [:mn, :k]\ndef swizzled_to_linear_128_4(a_sf_swizzled: torch.Tensor, mn, k):\n mn_padded, sf_k_padded = a_sf_swizzled.shape\n m_tiles = mn_padded // 128\n k_tiles = sf_k_padded // 4\n tmp = torch.reshape(a_sf_swizzled, (m_tiles, k_tiles, 32, 4, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, sf_k_padded)[:mn, :k]\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/main/tests/python/direct_utils/narrow_precision.py#L46-L106\ndef unpack_fp4(x: torch.Tensor) -> torch.Tensor:\n repeated = x.repeat_interleave(2, dim=1)\n repeated[:, 0::2] &= 0x0F\n repeated[:, 1::2] >>= 4\n return repeated\n\n\n_FP4_LUT = torch.tensor(\n [\n 0.0, # 0: 0000 - zero\n 0.5, # 1: 0001 - smallest positive normal\n 1.0, # 2: 0010\n 1.5, # 3: 0011\n 2.0, # 4: 0100\n 3.0, # 5: 0101\n 4.0, # 6: 0110\n 6.0, # 7: 0111 - largest positive normal\n -0.0, # 8: 1000 - negative zero","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.unpack_fp4","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.unpack_fp4#L152-L156","kind":"function","name":"unpack_fp4","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":152,"end_line":156,"context_start_line":132,"context_end_line":176,"code":" return fp4_weight, weight_scale_interleaved, global_scale\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L151-L152\ndef round_up(x: int, y: int) -> int:\n return (x + y - 1) // y * y\n\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/d70540f9/tests/python/utils/narrow_precision.py#L55-L60\n# restore swizzled on block scaling factor:\n# 1. restore swizzle\n# 2. removes padding via slicing to [:mn, :k]\ndef swizzled_to_linear_128_4(a_sf_swizzled: torch.Tensor, mn, k):\n mn_padded, sf_k_padded = a_sf_swizzled.shape\n m_tiles = mn_padded // 128\n k_tiles = sf_k_padded // 4\n tmp = torch.reshape(a_sf_swizzled, (m_tiles, k_tiles, 32, 4, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, sf_k_padded)[:mn, :k]\n\n# Ref: https://github.com/NVIDIA/Fuser/blob/main/tests/python/direct_utils/narrow_precision.py#L46-L106\ndef unpack_fp4(x: torch.Tensor) -> torch.Tensor:\n repeated = x.repeat_interleave(2, dim=1)\n repeated[:, 0::2] &= 0x0F\n repeated[:, 1::2] >>= 4\n return repeated\n\n\n_FP4_LUT = torch.tensor(\n [\n 0.0, # 0: 0000 - zero\n 0.5, # 1: 0001 - smallest positive normal\n 1.0, # 2: 0010\n 1.5, # 3: 0011\n 2.0, # 4: 0100\n 3.0, # 5: 0101\n 4.0, # 6: 0110\n 6.0, # 7: 0111 - largest positive normal\n -0.0, # 8: 1000 - negative zero\n -0.5, # 9: 1001 - smallest negative normal\n -1.0, # 10: 1010\n -1.5, # 11: 1011\n -2.0, # 12: 1100\n -3.0, # 13: 1101\n -4.0, # 14: 1110\n -6.0, # 15: 1111 - largest negative normal","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.fp4_to_fp32","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.fp4_to_fp32#L183-L188","kind":"function","name":"fp4_to_fp32","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":183,"end_line":188,"context_start_line":163,"context_end_line":208,"code":" 1.0, # 2: 0010\n 1.5, # 3: 0011\n 2.0, # 4: 0100\n 3.0, # 5: 0101\n 4.0, # 6: 0110\n 6.0, # 7: 0111 - largest positive normal\n -0.0, # 8: 1000 - negative zero\n -0.5, # 9: 1001 - smallest negative normal\n -1.0, # 10: 1010\n -1.5, # 11: 1011\n -2.0, # 12: 1100\n -3.0, # 13: 1101\n -4.0, # 14: 1110\n -6.0, # 15: 1111 - largest negative normal\n ],\n dtype=torch.float32,\n device=\"cuda\",\n)\n\n\ndef fp4_to_fp32(fp4: torch.Tensor) -> torch.Tensor:\n # Convert FP4 indices to their corresponding floating point values\n # Each index (0-15) represents a 4-bit FP4 value in E2M1 format\n # Values based on the FP4 E2M1 specification\n # NOTE: move to device triggers error in inductor. We hard code the lookup Tensor on cuda and remove the cast as a WAR `fp4_lut = _FP4_LUT.to(fp4.device)`\n return _FP4_LUT[fp4.to(torch.long)]\n\n\ndef dequantize_fp4(\n qx: torch.Tensor, sx: torch.Tensor, amax: torch.Tensor\n) -> torch.Tensor:\n sf = sx.repeat_interleave(16, dim=1).view(torch.float8_e4m3fn).to(torch.float32)\n dqx = fp4_to_fp32(unpack_fp4(qx))\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf * (amax / (6.0 * 448))\n return dequant\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.dequantize_fp4","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.dequantize_fp4#L191-L198","kind":"function","name":"dequantize_fp4","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":191,"end_line":198,"context_start_line":171,"context_end_line":218,"code":" -1.0, # 10: 1010\n -1.5, # 11: 1011\n -2.0, # 12: 1100\n -3.0, # 13: 1101\n -4.0, # 14: 1110\n -6.0, # 15: 1111 - largest negative normal\n ],\n dtype=torch.float32,\n device=\"cuda\",\n)\n\n\ndef fp4_to_fp32(fp4: torch.Tensor) -> torch.Tensor:\n # Convert FP4 indices to their corresponding floating point values\n # Each index (0-15) represents a 4-bit FP4 value in E2M1 format\n # Values based on the FP4 E2M1 specification\n # NOTE: move to device triggers error in inductor. We hard code the lookup Tensor on cuda and remove the cast as a WAR `fp4_lut = _FP4_LUT.to(fp4.device)`\n return _FP4_LUT[fp4.to(torch.long)]\n\n\ndef dequantize_fp4(\n qx: torch.Tensor, sx: torch.Tensor, amax: torch.Tensor\n) -> torch.Tensor:\n sf = sx.repeat_interleave(16, dim=1).view(torch.float8_e4m3fn).to(torch.float32)\n dqx = fp4_to_fp32(unpack_fp4(qx))\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf * (amax / (6.0 * 448))\n return dequant\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This custom op is registered with nvfuser translator in benchmark_inference.py\n# using _register_nvfuser_translator. See benchmark_inference._register_nvfp4_ops().\n@torch.library.custom_op(\"nvf_cutlass::f16a_nvfp4weight_scaled_grouped_mm\", mutates_args=())\ndef nvfuser_f16a_nvfp4weight_scaled_grouped_mm(","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.dequantize_to_dtype","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.dequantize_to_dtype#L200-L212","kind":"function","name":"dequantize_to_dtype","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":200,"end_line":212,"context_start_line":180,"context_end_line":232,"code":")\n\n\ndef fp4_to_fp32(fp4: torch.Tensor) -> torch.Tensor:\n # Convert FP4 indices to their corresponding floating point values\n # Each index (0-15) represents a 4-bit FP4 value in E2M1 format\n # Values based on the FP4 E2M1 specification\n # NOTE: move to device triggers error in inductor. We hard code the lookup Tensor on cuda and remove the cast as a WAR `fp4_lut = _FP4_LUT.to(fp4.device)`\n return _FP4_LUT[fp4.to(torch.long)]\n\n\ndef dequantize_fp4(\n qx: torch.Tensor, sx: torch.Tensor, amax: torch.Tensor\n) -> torch.Tensor:\n sf = sx.repeat_interleave(16, dim=1).view(torch.float8_e4m3fn).to(torch.float32)\n dqx = fp4_to_fp32(unpack_fp4(qx))\n sf = sf[: dqx.shape[0], : dqx.shape[1]]\n dequant = dqx * sf * (amax / (6.0 * 448))\n return dequant\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This custom op is registered with nvfuser translator in benchmark_inference.py\n# using _register_nvfuser_translator. See benchmark_inference._register_nvfp4_ops().\n@torch.library.custom_op(\"nvf_cutlass::f16a_nvfp4weight_scaled_grouped_mm\", mutates_args=())\ndef nvfuser_f16a_nvfp4weight_scaled_grouped_mm(\n activation: torch.Tensor,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor,\n problem_sizes: torch.Tensor,\n) -> torch.Tensor:\n # NOTE: weight needs to be stored as (g, n, k), we'll transpose in order to hit fast kernel\n hp_weight = torch.empty(\n (fp4_weight.size(0), fp4_weight.size(2), fp4_weight.size(1) * 2),\n device=activation.device,\n dtype=activation.dtype,\n )","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.nvfuser_f16a_nvfp4weight_scaled_grouped_mm","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.nvfuser_f16a_nvfp4weight_scaled_grouped_mm#L218-L237","kind":"function","name":"nvfuser_f16a_nvfp4weight_scaled_grouped_mm","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":218,"end_line":237,"context_start_line":198,"context_end_line":257,"code":" return dequant\n\ndef dequantize_to_dtype(\n tensor_fp4, tensor_sf, global_scale, dtype, device, block_size=16\n):\n \"\"\"Dequantize the fp4 tensor back to high precision.\"\"\"\n # Two fp4 values are packed into one uint8.\n m, packed_k = tensor_fp4.shape\n k = packed_k * 2\n tensor_sf = tensor_sf.view(torch.float8_e4m3fn)\n tensor_sf = swizzled_to_linear_128_4(tensor_sf, m, k)\n out = dequantize_fp4(\n tensor_fp4.view(torch.uint8), tensor_sf, (6.0 * 448.0) / global_scale\n )\n return out.reshape(m, k)\n\n\n# NOTE: This custom op is registered with nvfuser translator in benchmark_inference.py\n# using _register_nvfuser_translator. See benchmark_inference._register_nvfp4_ops().\n@torch.library.custom_op(\"nvf_cutlass::f16a_nvfp4weight_scaled_grouped_mm\", mutates_args=())\ndef nvfuser_f16a_nvfp4weight_scaled_grouped_mm(\n activation: torch.Tensor,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor,\n problem_sizes: torch.Tensor,\n) -> torch.Tensor:\n # NOTE: weight needs to be stored as (g, n, k), we'll transpose in order to hit fast kernel\n hp_weight = torch.empty(\n (fp4_weight.size(0), fp4_weight.size(2), fp4_weight.size(1) * 2),\n device=activation.device,\n dtype=activation.dtype,\n )\n for i in range(fp4_weight.size(0)):\n hp_weight[i] = dequantize_to_dtype(\n fp4_weight[i].transpose(1, 0), weight_scaling_factor[i], weight_global_scale[i], activation.dtype, fp4_weight.device, 16\n )\n return grouped_mm(activation, hp_weight.transpose(2, 1), offsets)\n\n\n@torch.library.register_fake(\"nvf_cutlass::f16a_nvfp4weight_scaled_grouped_mm\")\ndef _(\n activation: torch.Tensor,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor,\n problem_sizes: torch.Tensor,\n) -> torch.Tensor:\n # fp4_weight shape: (groups, in_features // 2, out_features)\n # Validate that activation has at least 1 dimension\n if activation.ndim == 0:\n raise ValueError(f\"Expected activation to have at least 1 dimension, got {activation.ndim}\")\n\n if (\n len(\n {","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark._","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark._#L241-L279","kind":"function","name":"_","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":241,"end_line":279,"context_start_line":221,"context_end_line":299,"code":" weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor,\n problem_sizes: torch.Tensor,\n) -> torch.Tensor:\n # NOTE: weight needs to be stored as (g, n, k), we'll transpose in order to hit fast kernel\n hp_weight = torch.empty(\n (fp4_weight.size(0), fp4_weight.size(2), fp4_weight.size(1) * 2),\n device=activation.device,\n dtype=activation.dtype,\n )\n for i in range(fp4_weight.size(0)):\n hp_weight[i] = dequantize_to_dtype(\n fp4_weight[i].transpose(1, 0), weight_scaling_factor[i], weight_global_scale[i], activation.dtype, fp4_weight.device, 16\n )\n return grouped_mm(activation, hp_weight.transpose(2, 1), offsets)\n\n\n@torch.library.register_fake(\"nvf_cutlass::f16a_nvfp4weight_scaled_grouped_mm\")\ndef _(\n activation: torch.Tensor,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor,\n problem_sizes: torch.Tensor,\n) -> torch.Tensor:\n # fp4_weight shape: (groups, in_features // 2, out_features)\n # Validate that activation has at least 1 dimension\n if activation.ndim == 0:\n raise ValueError(f\"Expected activation to have at least 1 dimension, got {activation.ndim}\")\n\n if (\n len(\n {\n t.device\n for t in [\n activation,\n fp4_weight,\n weight_scaling_factor,\n weight_global_scale,\n offsets,\n blockscale_offsets,\n problem_sizes,\n ]\n }\n )\n != 1\n ):\n raise ValueError(\"Expected all inputs to be on the same device.\")\n\n # After unpacking: (groups, in_features, out_features)\n # Output shape should match activation.shape[:-1] + (out_features,)\n # This handles both 2D (tokens, hidden) and 3D (batch, seq_len, hidden) inputs\n out_features = fp4_weight.size(2)\n output_shape = activation.shape[:-1] + (out_features,)\n return torch.empty(output_shape, device=activation.device, dtype=torch.bfloat16)\n\n\nclass SwiGLU(nn.Module):\n def __init__(self, hidden_size: int, intermediate_size: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False, dtype=dtype, device=device)\n self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False, dtype=dtype, device=device)\n self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False, dtype=dtype, device=device)\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.down_proj(torch.nn.functional.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))\n\n\ndef _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n if isinstance(offsets, DTensor):\n assert offsets.placements == (Replicate(),)\n offsets = offsets.to_local()\n","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.SwiGLU","uri":"program://Fuser/class/benchmarks.python.layers_for_inference_benchmark.SwiGLU#L282-L290","kind":"class","name":"SwiGLU","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":282,"end_line":290,"context_start_line":262,"context_end_line":310,"code":" weight_scaling_factor,\n weight_global_scale,\n offsets,\n blockscale_offsets,\n problem_sizes,\n ]\n }\n )\n != 1\n ):\n raise ValueError(\"Expected all inputs to be on the same device.\")\n\n # After unpacking: (groups, in_features, out_features)\n # Output shape should match activation.shape[:-1] + (out_features,)\n # This handles both 2D (tokens, hidden) and 3D (batch, seq_len, hidden) inputs\n out_features = fp4_weight.size(2)\n output_shape = activation.shape[:-1] + (out_features,)\n return torch.empty(output_shape, device=activation.device, dtype=torch.bfloat16)\n\n\nclass SwiGLU(nn.Module):\n def __init__(self, hidden_size: int, intermediate_size: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False, dtype=dtype, device=device)\n self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False, dtype=dtype, device=device)\n self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False, dtype=dtype, device=device)\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.down_proj(torch.nn.functional.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))\n\n\ndef _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n if isinstance(offsets, DTensor):\n assert offsets.placements == (Replicate(),)\n offsets = offsets.to_local()\n\n for offset in offsets:\n group_sizes.append(offset - prev)\n prev = offset\n return group_sizes\n\n\nif LooseVersion(torch.__version__) >= LooseVersion(\"2.8.0\"):\n # Required -- otherwise there is a graph-break.\n _grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\nelse:\n _grouped_mm = None","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark._group_sizes_from_offsets","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark._group_sizes_from_offsets#L293-L303","kind":"function","name":"_group_sizes_from_offsets","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":293,"end_line":303,"context_start_line":273,"context_end_line":323,"code":"\n # After unpacking: (groups, in_features, out_features)\n # Output shape should match activation.shape[:-1] + (out_features,)\n # This handles both 2D (tokens, hidden) and 3D (batch, seq_len, hidden) inputs\n out_features = fp4_weight.size(2)\n output_shape = activation.shape[:-1] + (out_features,)\n return torch.empty(output_shape, device=activation.device, dtype=torch.bfloat16)\n\n\nclass SwiGLU(nn.Module):\n def __init__(self, hidden_size: int, intermediate_size: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False, dtype=dtype, device=device)\n self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False, dtype=dtype, device=device)\n self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False, dtype=dtype, device=device)\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return self.down_proj(torch.nn.functional.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))\n\n\ndef _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n if isinstance(offsets, DTensor):\n assert offsets.placements == (Replicate(),)\n offsets = offsets.to_local()\n\n for offset in offsets:\n group_sizes.append(offset - prev)\n prev = offset\n return group_sizes\n\n\nif LooseVersion(torch.__version__) >= LooseVersion(\"2.8.0\"):\n # Required -- otherwise there is a graph-break.\n _grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\nelse:\n _grouped_mm = None\n\n\ndef grouped_mm(a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n if _grouped_mm is not None:\n return _grouped_mm(a, b, offsets)\n\n group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for idx, group_a in enumerate(a.split(group_sizes)):\n group_outs.append(group_a @ b[idx])\n return torch.cat(group_outs)\n\n","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.grouped_mm","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.grouped_mm#L313-L321","kind":"function","name":"grouped_mm","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":313,"end_line":321,"context_start_line":293,"context_end_line":341,"code":"def _group_sizes_from_offsets(offsets: torch.Tensor) -> list[int]:\n group_sizes = []\n prev = 0\n if isinstance(offsets, DTensor):\n assert offsets.placements == (Replicate(),)\n offsets = offsets.to_local()\n\n for offset in offsets:\n group_sizes.append(offset - prev)\n prev = offset\n return group_sizes\n\n\nif LooseVersion(torch.__version__) >= LooseVersion(\"2.8.0\"):\n # Required -- otherwise there is a graph-break.\n _grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\nelse:\n _grouped_mm = None\n\n\ndef grouped_mm(a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n if _grouped_mm is not None:\n return _grouped_mm(a, b, offsets)\n\n group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for idx, group_a in enumerate(a.split(group_sizes)):\n group_outs.append(group_a @ b[idx])\n return torch.cat(group_outs)\n\n\nclass GroupedLinear(nn.Module):\n def __init__(self, groups: int, in_features: int, out_features: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.weight = nn.Parameter(torch.empty(groups, out_features, in_features, dtype=dtype, device=device))\n # Initialize the weight in the same way as nn.Linear\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n return grouped_mm(hidden_states, self.weight.transpose(-1, -2), offsets)\n\n\n@torch.inference_mode()\ndef quantize_grouped_linear_weight_to_nvfp4(\n weight: torch.Tensor | nn.Parameter,\n) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"Quantize grouped linear's weight to nvfp4\n\n Args:","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.GroupedLinear","uri":"program://Fuser/class/benchmarks.python.layers_for_inference_benchmark.GroupedLinear#L324-L332","kind":"class","name":"GroupedLinear","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":324,"end_line":332,"context_start_line":304,"context_end_line":352,"code":"\n\nif LooseVersion(torch.__version__) >= LooseVersion(\"2.8.0\"):\n # Required -- otherwise there is a graph-break.\n _grouped_mm = torch.compiler.allow_in_graph(torch._grouped_mm)\nelse:\n _grouped_mm = None\n\n\ndef grouped_mm(a: torch.Tensor, b: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n if _grouped_mm is not None:\n return _grouped_mm(a, b, offsets)\n\n group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for idx, group_a in enumerate(a.split(group_sizes)):\n group_outs.append(group_a @ b[idx])\n return torch.cat(group_outs)\n\n\nclass GroupedLinear(nn.Module):\n def __init__(self, groups: int, in_features: int, out_features: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.weight = nn.Parameter(torch.empty(groups, out_features, in_features, dtype=dtype, device=device))\n # Initialize the weight in the same way as nn.Linear\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n return grouped_mm(hidden_states, self.weight.transpose(-1, -2), offsets)\n\n\n@torch.inference_mode()\ndef quantize_grouped_linear_weight_to_nvfp4(\n weight: torch.Tensor | nn.Parameter,\n) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"Quantize grouped linear's weight to nvfp4\n\n Args:\n weight: Parameter of `GroupedLinear` of [g, n, k]\n\n Returns:\n fp4_weight: [g, k // 2, n]\n scale_factors: [g, n, k // 16]\n global_scales: [g]\n\n Note:\n The reason we choose different layout of weight is to avoid performance\n regression for bf16. See\n https://github.com/Lightning-AI/lightning-thunder/pull/2659","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.quantize_grouped_linear_weight_to_nvfp4","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.quantize_grouped_linear_weight_to_nvfp4#L336-L372","kind":"function","name":"quantize_grouped_linear_weight_to_nvfp4","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":336,"end_line":372,"context_start_line":316,"context_end_line":392,"code":"\n group_sizes = _group_sizes_from_offsets(offsets)\n group_outs = []\n for idx, group_a in enumerate(a.split(group_sizes)):\n group_outs.append(group_a @ b[idx])\n return torch.cat(group_outs)\n\n\nclass GroupedLinear(nn.Module):\n def __init__(self, groups: int, in_features: int, out_features: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.weight = nn.Parameter(torch.empty(groups, out_features, in_features, dtype=dtype, device=device))\n # Initialize the weight in the same way as nn.Linear\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n return grouped_mm(hidden_states, self.weight.transpose(-1, -2), offsets)\n\n\n@torch.inference_mode()\ndef quantize_grouped_linear_weight_to_nvfp4(\n weight: torch.Tensor | nn.Parameter,\n) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"Quantize grouped linear's weight to nvfp4\n\n Args:\n weight: Parameter of `GroupedLinear` of [g, n, k]\n\n Returns:\n fp4_weight: [g, k // 2, n]\n scale_factors: [g, n, k // 16]\n global_scales: [g]\n\n Note:\n The reason we choose different layout of weight is to avoid performance\n regression for bf16. See\n https://github.com/Lightning-AI/lightning-thunder/pull/2659\n \"\"\"\n assert weight.ndim == 3, \"Weight must be a 3D tensor\"\n\n device: torch.device = weight.device\n g, n, k = weight.size()\n\n with device:\n fp4_weight = torch.empty((g, n, k // 2), dtype=torch.float4_e2m1fn_x2)\n global_scales = torch.empty((g,), dtype=torch.float32)\n scale_factors = torch.empty((g, n, k // 16), dtype=torch.float8_e4m3fn)\n\n weight = weight.contiguous()\n for i in range(g):\n cur_weight = weight[i]\n global_scales[i] = cur_weight.abs().amax()\n cur_fp4_weight, cur_scale_factors = pytorch_nvfp4_quantize(cur_weight, global_scales[i])\n fp4_weight[i] = cur_fp4_weight\n scale_factors[i] = linear_to_swizzled_128_4(cur_scale_factors)\n\n return fp4_weight.transpose(-1, -2), scale_factors, global_scales\n\n\nclass NVFP4InferenceGroupedLinear(nn.Module):\n def __init__(\n self,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n ) -> None:\n super().__init__()\n self.register_buffer(\"fp4_weight\", fp4_weight)\n self.register_buffer(\"weight_scaling_factor\", weight_scaling_factor)\n self.register_buffer(\"weight_global_scale\", weight_global_scale)\n\n @property\n def out_features(self) -> int:\n return self.fp4_weight.size(2)\n\n @property\n def in_features(self) -> int:","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.NVFP4InferenceGroupedLinear","uri":"program://Fuser/class/benchmarks.python.layers_for_inference_benchmark.NVFP4InferenceGroupedLinear#L375-L462","kind":"class","name":"NVFP4InferenceGroupedLinear","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":375,"end_line":462,"context_start_line":355,"context_end_line":482,"code":"\n device: torch.device = weight.device\n g, n, k = weight.size()\n\n with device:\n fp4_weight = torch.empty((g, n, k // 2), dtype=torch.float4_e2m1fn_x2)\n global_scales = torch.empty((g,), dtype=torch.float32)\n scale_factors = torch.empty((g, n, k // 16), dtype=torch.float8_e4m3fn)\n\n weight = weight.contiguous()\n for i in range(g):\n cur_weight = weight[i]\n global_scales[i] = cur_weight.abs().amax()\n cur_fp4_weight, cur_scale_factors = pytorch_nvfp4_quantize(cur_weight, global_scales[i])\n fp4_weight[i] = cur_fp4_weight\n scale_factors[i] = linear_to_swizzled_128_4(cur_scale_factors)\n\n return fp4_weight.transpose(-1, -2), scale_factors, global_scales\n\n\nclass NVFP4InferenceGroupedLinear(nn.Module):\n def __init__(\n self,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n ) -> None:\n super().__init__()\n self.register_buffer(\"fp4_weight\", fp4_weight)\n self.register_buffer(\"weight_scaling_factor\", weight_scaling_factor)\n self.register_buffer(\"weight_global_scale\", weight_global_scale)\n\n @property\n def out_features(self) -> int:\n return self.fp4_weight.size(2)\n\n @property\n def in_features(self) -> int:\n return self.fp4_weight.size(1) * 2\n\n @staticmethod\n def compute_auxiliary_tensors(\n hidden_states: torch.Tensor,\n offsets: torch.Tensor,\n out_features: int,\n ) -> tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Compute blockscale_offsets and problem_sizes for grouped mm.\n\n These can be computed once and reused across multiple forward calls with the same offsets.\n \"\"\"\n # expanded offsets to contain the total number of tokens.\n expanded_offsets = torch.cat([offsets, torch.tensor([hidden_states.size(0)], device=offsets.device)])\n tokens_per_group = expanded_offsets[1:] - expanded_offsets[:-1]\n problem_sizes = torch.stack(\n [\n tokens_per_group,\n torch.full_like(tokens_per_group, out_features),\n torch.full_like(tokens_per_group, hidden_states.size(1)),\n ],\n dim=1,\n )\n # Calculate block-scale offsets: round up to 128, then cumsum with initial 0\n rounded_tokens = ((tokens_per_group + 127) // 128) * 128\n blockscale_offsets = torch.cat(\n [\n torch.zeros(1, dtype=torch.int32, device=tokens_per_group.device),\n torch.cumsum(rounded_tokens, 0, dtype=torch.int32),\n ]\n )[0:-1]\n return blockscale_offsets, problem_sizes\n\n # TODO: Update this accordingly to the progress of nvfp4 kernel implementation.\n def forward(\n self,\n hidden_states: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor | None = None,\n problem_sizes: torch.Tensor | None = None,\n ) -> torch.Tensor:\n if blockscale_offsets is None or problem_sizes is None:\n # Compute them if not provided (backward compatibility)\n out_features = self.out_features\n blockscale_offsets, problem_sizes = self.compute_auxiliary_tensors(hidden_states, offsets, out_features)\n return torch.ops.nvf_cutlass.f16a_nvfp4weight_scaled_grouped_mm(\n hidden_states,\n self.fp4_weight,\n self.weight_scaling_factor,\n self.weight_global_scale,\n offsets,\n blockscale_offsets,\n problem_sizes,\n )\n\n @staticmethod\n def from_grouped_linear(grouped_linear: GroupedLinear, fqn: str | None = None) -> NVFP4InferenceGroupedLinear:\n \"\"\"Create an NVFP4InferenceGroupedLinear from a GroupedLinear.\n\n Args:\n grouped_linear (GroupedLinear): The source GroupedLinear.\n fqn (str or None): Fully qualified name. Currently unused; reserved for future use or compatibility.\n \"\"\"\n weight = grouped_linear.weight\n fp4_weight, weight_scaling_factor, weight_global_scale = quantize_grouped_linear_weight_to_nvfp4(weight)\n return NVFP4InferenceGroupedLinear(\n fp4_weight,\n weight_scaling_factor,\n weight_global_scale,\n )\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size, dtype, device)\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n return self.down_proj(\n torch.nn.functional.silu(self.gate_proj(hidden_states, offsets)) * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass NVFP4InferenceGroupedSwiGLU(nn.Module):\n \"\"\"NVFP4 GroupedSwiGLU that efficiently reuses auxiliary tensor computations.\"\"\"\n\n def __init__(","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.GroupedSwiGLU","uri":"program://Fuser/class/benchmarks.python.layers_for_inference_benchmark.GroupedSwiGLU#L465-L476","kind":"class","name":"GroupedSwiGLU","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":465,"end_line":476,"context_start_line":445,"context_end_line":496,"code":" problem_sizes,\n )\n\n @staticmethod\n def from_grouped_linear(grouped_linear: GroupedLinear, fqn: str | None = None) -> NVFP4InferenceGroupedLinear:\n \"\"\"Create an NVFP4InferenceGroupedLinear from a GroupedLinear.\n\n Args:\n grouped_linear (GroupedLinear): The source GroupedLinear.\n fqn (str or None): Fully qualified name. Currently unused; reserved for future use or compatibility.\n \"\"\"\n weight = grouped_linear.weight\n fp4_weight, weight_scaling_factor, weight_global_scale = quantize_grouped_linear_weight_to_nvfp4(weight)\n return NVFP4InferenceGroupedLinear(\n fp4_weight,\n weight_scaling_factor,\n weight_global_scale,\n )\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size, dtype, device)\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n return self.down_proj(\n torch.nn.functional.silu(self.gate_proj(hidden_states, offsets)) * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass NVFP4InferenceGroupedSwiGLU(nn.Module):\n \"\"\"NVFP4 GroupedSwiGLU that efficiently reuses auxiliary tensor computations.\"\"\"\n\n def __init__(\n self,\n gate_proj: NVFP4InferenceGroupedLinear,\n up_proj: NVFP4InferenceGroupedLinear,\n down_proj: NVFP4InferenceGroupedLinear,\n ):\n super().__init__()\n self.gate_proj = gate_proj\n self.up_proj = up_proj\n self.down_proj = down_proj\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n # Compute auxiliary tensors once for all three operations\n intermediate_features = self.gate_proj.out_features\n blockscale_offsets_gate, problem_sizes_gate = NVFP4InferenceGroupedLinear.compute_auxiliary_tensors(","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.NVFP4InferenceGroupedSwiGLU","uri":"program://Fuser/class/benchmarks.python.layers_for_inference_benchmark.NVFP4InferenceGroupedSwiGLU#L479-L524","kind":"class","name":"NVFP4InferenceGroupedSwiGLU","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":479,"end_line":524,"context_start_line":459,"context_end_line":544,"code":" fp4_weight,\n weight_scaling_factor,\n weight_global_scale,\n )\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size, dtype, device)\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n return self.down_proj(\n torch.nn.functional.silu(self.gate_proj(hidden_states, offsets)) * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass NVFP4InferenceGroupedSwiGLU(nn.Module):\n \"\"\"NVFP4 GroupedSwiGLU that efficiently reuses auxiliary tensor computations.\"\"\"\n\n def __init__(\n self,\n gate_proj: NVFP4InferenceGroupedLinear,\n up_proj: NVFP4InferenceGroupedLinear,\n down_proj: NVFP4InferenceGroupedLinear,\n ):\n super().__init__()\n self.gate_proj = gate_proj\n self.up_proj = up_proj\n self.down_proj = down_proj\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n # Compute auxiliary tensors once for all three operations\n intermediate_features = self.gate_proj.out_features\n blockscale_offsets_gate, problem_sizes_gate = NVFP4InferenceGroupedLinear.compute_auxiliary_tensors(\n hidden_states, offsets, intermediate_features\n )\n\n gate_out = self.gate_proj(hidden_states, offsets, blockscale_offsets_gate, problem_sizes_gate)\n up_out = self.up_proj(hidden_states, offsets, blockscale_offsets_gate, problem_sizes_gate)\n\n intermediate = torch.nn.functional.silu(gate_out) * up_out\n\n # For down_proj, we need different problem_sizes (different output features)\n hidden_features = self.down_proj.out_features\n blockscale_offsets_down, problem_sizes_down = NVFP4InferenceGroupedLinear.compute_auxiliary_tensors(\n intermediate, offsets, hidden_features\n )\n\n return self.down_proj(intermediate, offsets, blockscale_offsets_down, problem_sizes_down)\n\n @staticmethod\n def from_grouped_swiglu(grouped_swiglu: GroupedSwiGLU, fqn: str | None = None) -> NVFP4InferenceGroupedSwiGLU:\n \"\"\"Create an NVFP4InferenceGroupedSwiGLU from a GroupedSwiGLU.\n\n Args:\n grouped_swiglu (GroupedSwiGLU): The source GroupedSwiGLU.\n fqn (str or None): Fully qualified name. Currently unused; reserved for future use or compatibility.\n \"\"\"\n gate_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.gate_proj)\n up_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.up_proj)\n down_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.down_proj)\n return NVFP4InferenceGroupedSwiGLU(gate_proj, up_proj, down_proj)\n\n\n# Slightly modified version of `thunder.tests.test_networks.Llama4MoE`\n# to have the same singature as transformers' Llama4TextMoe -- in this file\n# return values include `router_logits`.\n# Ref: https://github.com/huggingface/transformers/blob/ff8b88a9/src/transformers/models/llama4/modeling_llama4.py#L147-L165\nclass Llama4MoE(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.gate = nn.Linear(\n config.hidden_size,\n config.num_routed_experts,\n bias=False,\n dtype=config.dtype,\n device=config.device,\n )\n self.shared_experts = SwiGLU(\n config.hidden_size,\n config.intermediate_size * config.num_shared_experts,","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.Llama4MoE","uri":"program://Fuser/class/benchmarks.python.layers_for_inference_benchmark.Llama4MoE#L531-L641","kind":"class","name":"Llama4MoE","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":531,"end_line":641,"context_start_line":511,"context_end_line":641,"code":" return self.down_proj(intermediate, offsets, blockscale_offsets_down, problem_sizes_down)\n\n @staticmethod\n def from_grouped_swiglu(grouped_swiglu: GroupedSwiGLU, fqn: str | None = None) -> NVFP4InferenceGroupedSwiGLU:\n \"\"\"Create an NVFP4InferenceGroupedSwiGLU from a GroupedSwiGLU.\n\n Args:\n grouped_swiglu (GroupedSwiGLU): The source GroupedSwiGLU.\n fqn (str or None): Fully qualified name. Currently unused; reserved for future use or compatibility.\n \"\"\"\n gate_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.gate_proj)\n up_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.up_proj)\n down_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.down_proj)\n return NVFP4InferenceGroupedSwiGLU(gate_proj, up_proj, down_proj)\n\n\n# Slightly modified version of `thunder.tests.test_networks.Llama4MoE`\n# to have the same singature as transformers' Llama4TextMoe -- in this file\n# return values include `router_logits`.\n# Ref: https://github.com/huggingface/transformers/blob/ff8b88a9/src/transformers/models/llama4/modeling_llama4.py#L147-L165\nclass Llama4MoE(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.gate = nn.Linear(\n config.hidden_size,\n config.num_routed_experts,\n bias=False,\n dtype=config.dtype,\n device=config.device,\n )\n self.shared_experts = SwiGLU(\n config.hidden_size,\n config.intermediate_size * config.num_shared_experts,\n config.dtype,\n config.device,\n )\n self.routed_experts = GroupedSwiGLU(\n config.num_routed_experts,\n config.hidden_size,\n config.intermediate_size,\n config.dtype,\n config.device,\n )\n\n @staticmethod\n def from_transformers_llama4textmoe(moe: Llama4TextMoe) -> Llama4MoE:\n \"\"\"[CAUTION] A converter written by Gemini 2.5.\"\"\"\n from thunder.tests.llama4_moe import Config\n\n # 1. Create a config for the Llama4MoE model from the transformers config\n config = Config(\n \"Llama4MoE\",\n hidden_size=moe.hidden_dim,\n intermediate_size=moe.experts.intermediate_size,\n num_routed_experts=moe.num_experts,\n num_shared_experts=1, # Based on HF implementation having one shared_expert\n dtype=moe.router.weight.dtype,\n device=moe.router.weight.device,\n )\n\n # 2. Create an instance of our Llama4MoE\n new_moe = Llama4MoE(config)\n\n # 3. Copy the router weights (called 'gate' in our implementation)\n new_moe.gate.weight.data.copy_(moe.router.weight.data)\n\n # 4. Copy the shared expert weights\n new_moe.shared_experts.gate_proj.weight.data.copy_(moe.shared_expert.gate_proj.weight.data)\n new_moe.shared_experts.up_proj.weight.data.copy_(moe.shared_expert.up_proj.weight.data)\n new_moe.shared_experts.down_proj.weight.data.copy_(moe.shared_expert.down_proj.weight.data)\n\n # 5. For the routed experts, we need to handle the combined gate_up_proj\n # to match GroupedLinear\n # https://github.com/huggingface/transformers/blob/f4fc42216cd56ab6b68270bf80d811614d8d59e4/src/transformers/models/llama4/modeling_llama4.py#L55-L57\n # HF format: (groups, hidden_size, 2 * intermediate_size)\n # Our format: (groups, intermediate_size, hidden_size)\n\n # Split into gate and up projections\n gate_proj_w, up_proj_w = moe.experts.gate_up_proj.chunk(2, dim=2)\n\n new_moe.routed_experts.gate_proj.weight.data.copy_(gate_proj_w.transpose(-1, -2))\n new_moe.routed_experts.up_proj.weight.data.copy_(up_proj_w.transpose(-1, -2))\n\n # Handle down_proj\n # HF format: (groups, intermediate_size, hidden_size)\n # Our format: (groups, hidden, intermediate_size)\n new_moe.routed_experts.down_proj.weight.data.copy_(moe.experts.down_proj.transpose(-1, -2))\n\n return new_moe\n\n def run_routed_experts(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:\n batch_size, seq_len, _ = hidden_states.size()\n hidden_states = hidden_states.view(-1, hidden_states.size(-1)) # [s, h]\n\n router_logits = self.gate(hidden_states) # [s, n]\n topk_weight, topk_ids = router_logits.topk(1) # [s, 1]\n router_scores = topk_weight.sigmoid() # [s, 1]\n hidden_states = hidden_states * router_scores # [s, h]\n\n counts = torch.zeros(\n topk_ids.size(0),\n self.config.num_routed_experts,\n device=topk_ids.device,\n dtype=torch.int32,\n ) # [s, n]\n counts = counts.scatter(1, topk_ids, 1) # [s, n]\n tokens_per_expert = counts.sum(0) # [n]\n\n token_ids_sorted_by_expert_id = topk_ids.view(-1).argsort() # [s]\n tokens_sorted_by_expert_id = hidden_states[token_ids_sorted_by_expert_id] # [s, h]\n\n # Without `torch.int32`, we see `RuntimeError: Offsets tensor must be integer (int32) tensor, but got torch.int64.`\n # from PyTorch when calling _grouped_mm.\n # Prepend 0 to offsets for correct grouping\n offsets = torch.cat(\n [\n torch.zeros(1, dtype=torch.int32, device=tokens_per_expert.device),\n torch.cumsum(tokens_per_expert, 0, dtype=torch.int32),\n ]\n )[:-1] # [n]\n outs_sorted_by_expert_id = self.routed_experts(tokens_sorted_by_expert_id, offsets) # [s, h]\n\n token_ids_sorted_by_expert_inverse_id = torch.argsort(token_ids_sorted_by_expert_id)\n outs_sorted_by_token_id = outs_sorted_by_expert_id[token_ids_sorted_by_expert_inverse_id]\n\n return outs_sorted_by_token_id.view(batch_size, seq_len, -1), router_logits.view(batch_size, seq_len, -1)\n\n def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:\n outs_sorted_by_token_id, router_logits = self.run_routed_experts(hidden_states)\n return self.shared_experts(hidden_states) + outs_sorted_by_token_id, router_logits","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.__init__","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.__init__#L532-L554","kind":"function","name":"__init__","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":532,"end_line":554,"context_start_line":512,"context_end_line":574,"code":"\n @staticmethod\n def from_grouped_swiglu(grouped_swiglu: GroupedSwiGLU, fqn: str | None = None) -> NVFP4InferenceGroupedSwiGLU:\n \"\"\"Create an NVFP4InferenceGroupedSwiGLU from a GroupedSwiGLU.\n\n Args:\n grouped_swiglu (GroupedSwiGLU): The source GroupedSwiGLU.\n fqn (str or None): Fully qualified name. Currently unused; reserved for future use or compatibility.\n \"\"\"\n gate_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.gate_proj)\n up_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.up_proj)\n down_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.down_proj)\n return NVFP4InferenceGroupedSwiGLU(gate_proj, up_proj, down_proj)\n\n\n# Slightly modified version of `thunder.tests.test_networks.Llama4MoE`\n# to have the same singature as transformers' Llama4TextMoe -- in this file\n# return values include `router_logits`.\n# Ref: https://github.com/huggingface/transformers/blob/ff8b88a9/src/transformers/models/llama4/modeling_llama4.py#L147-L165\nclass Llama4MoE(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.gate = nn.Linear(\n config.hidden_size,\n config.num_routed_experts,\n bias=False,\n dtype=config.dtype,\n device=config.device,\n )\n self.shared_experts = SwiGLU(\n config.hidden_size,\n config.intermediate_size * config.num_shared_experts,\n config.dtype,\n config.device,\n )\n self.routed_experts = GroupedSwiGLU(\n config.num_routed_experts,\n config.hidden_size,\n config.intermediate_size,\n config.dtype,\n config.device,\n )\n\n @staticmethod\n def from_transformers_llama4textmoe(moe: Llama4TextMoe) -> Llama4MoE:\n \"\"\"[CAUTION] A converter written by Gemini 2.5.\"\"\"\n from thunder.tests.llama4_moe import Config\n\n # 1. Create a config for the Llama4MoE model from the transformers config\n config = Config(\n \"Llama4MoE\",\n hidden_size=moe.hidden_dim,\n intermediate_size=moe.experts.intermediate_size,\n num_routed_experts=moe.num_experts,\n num_shared_experts=1, # Based on HF implementation having one shared_expert\n dtype=moe.router.weight.dtype,\n device=moe.router.weight.device,\n )\n\n # 2. Create an instance of our Llama4MoE\n new_moe = Llama4MoE(config)\n","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.forward","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.forward#L639-L641","kind":"function","name":"forward","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":639,"end_line":641,"context_start_line":619,"context_end_line":641,"code":"\n token_ids_sorted_by_expert_id = topk_ids.view(-1).argsort() # [s]\n tokens_sorted_by_expert_id = hidden_states[token_ids_sorted_by_expert_id] # [s, h]\n\n # Without `torch.int32`, we see `RuntimeError: Offsets tensor must be integer (int32) tensor, but got torch.int64.`\n # from PyTorch when calling _grouped_mm.\n # Prepend 0 to offsets for correct grouping\n offsets = torch.cat(\n [\n torch.zeros(1, dtype=torch.int32, device=tokens_per_expert.device),\n torch.cumsum(tokens_per_expert, 0, dtype=torch.int32),\n ]\n )[:-1] # [n]\n outs_sorted_by_expert_id = self.routed_experts(tokens_sorted_by_expert_id, offsets) # [s, h]\n\n token_ids_sorted_by_expert_inverse_id = torch.argsort(token_ids_sorted_by_expert_id)\n outs_sorted_by_token_id = outs_sorted_by_expert_id[token_ids_sorted_by_expert_inverse_id]\n\n return outs_sorted_by_token_id.view(batch_size, seq_len, -1), router_logits.view(batch_size, seq_len, -1)\n\n def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:\n outs_sorted_by_token_id, router_logits = self.run_routed_experts(hidden_states)\n return self.shared_experts(hidden_states) + outs_sorted_by_token_id, router_logits","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.out_features","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.out_features#L388-L389","kind":"function","name":"out_features","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":388,"end_line":389,"context_start_line":368,"context_end_line":409,"code":" cur_fp4_weight, cur_scale_factors = pytorch_nvfp4_quantize(cur_weight, global_scales[i])\n fp4_weight[i] = cur_fp4_weight\n scale_factors[i] = linear_to_swizzled_128_4(cur_scale_factors)\n\n return fp4_weight.transpose(-1, -2), scale_factors, global_scales\n\n\nclass NVFP4InferenceGroupedLinear(nn.Module):\n def __init__(\n self,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n ) -> None:\n super().__init__()\n self.register_buffer(\"fp4_weight\", fp4_weight)\n self.register_buffer(\"weight_scaling_factor\", weight_scaling_factor)\n self.register_buffer(\"weight_global_scale\", weight_global_scale)\n\n @property\n def out_features(self) -> int:\n return self.fp4_weight.size(2)\n\n @property\n def in_features(self) -> int:\n return self.fp4_weight.size(1) * 2\n\n @staticmethod\n def compute_auxiliary_tensors(\n hidden_states: torch.Tensor,\n offsets: torch.Tensor,\n out_features: int,\n ) -> tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Compute blockscale_offsets and problem_sizes for grouped mm.\n\n These can be computed once and reused across multiple forward calls with the same offsets.\n \"\"\"\n # expanded offsets to contain the total number of tokens.\n expanded_offsets = torch.cat([offsets, torch.tensor([hidden_states.size(0)], device=offsets.device)])\n tokens_per_group = expanded_offsets[1:] - expanded_offsets[:-1]\n problem_sizes = torch.stack(\n [","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.in_features","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.in_features#L392-L393","kind":"function","name":"in_features","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":392,"end_line":393,"context_start_line":372,"context_end_line":413,"code":" return fp4_weight.transpose(-1, -2), scale_factors, global_scales\n\n\nclass NVFP4InferenceGroupedLinear(nn.Module):\n def __init__(\n self,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n ) -> None:\n super().__init__()\n self.register_buffer(\"fp4_weight\", fp4_weight)\n self.register_buffer(\"weight_scaling_factor\", weight_scaling_factor)\n self.register_buffer(\"weight_global_scale\", weight_global_scale)\n\n @property\n def out_features(self) -> int:\n return self.fp4_weight.size(2)\n\n @property\n def in_features(self) -> int:\n return self.fp4_weight.size(1) * 2\n\n @staticmethod\n def compute_auxiliary_tensors(\n hidden_states: torch.Tensor,\n offsets: torch.Tensor,\n out_features: int,\n ) -> tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Compute blockscale_offsets and problem_sizes for grouped mm.\n\n These can be computed once and reused across multiple forward calls with the same offsets.\n \"\"\"\n # expanded offsets to contain the total number of tokens.\n expanded_offsets = torch.cat([offsets, torch.tensor([hidden_states.size(0)], device=offsets.device)])\n tokens_per_group = expanded_offsets[1:] - expanded_offsets[:-1]\n problem_sizes = torch.stack(\n [\n tokens_per_group,\n torch.full_like(tokens_per_group, out_features),\n torch.full_like(tokens_per_group, hidden_states.size(1)),\n ],","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.compute_auxiliary_tensors","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.compute_auxiliary_tensors#L396-L424","kind":"function","name":"compute_auxiliary_tensors","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":396,"end_line":424,"context_start_line":376,"context_end_line":444,"code":" def __init__(\n self,\n fp4_weight: torch.Tensor,\n weight_scaling_factor: torch.Tensor,\n weight_global_scale: torch.Tensor,\n ) -> None:\n super().__init__()\n self.register_buffer(\"fp4_weight\", fp4_weight)\n self.register_buffer(\"weight_scaling_factor\", weight_scaling_factor)\n self.register_buffer(\"weight_global_scale\", weight_global_scale)\n\n @property\n def out_features(self) -> int:\n return self.fp4_weight.size(2)\n\n @property\n def in_features(self) -> int:\n return self.fp4_weight.size(1) * 2\n\n @staticmethod\n def compute_auxiliary_tensors(\n hidden_states: torch.Tensor,\n offsets: torch.Tensor,\n out_features: int,\n ) -> tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Compute blockscale_offsets and problem_sizes for grouped mm.\n\n These can be computed once and reused across multiple forward calls with the same offsets.\n \"\"\"\n # expanded offsets to contain the total number of tokens.\n expanded_offsets = torch.cat([offsets, torch.tensor([hidden_states.size(0)], device=offsets.device)])\n tokens_per_group = expanded_offsets[1:] - expanded_offsets[:-1]\n problem_sizes = torch.stack(\n [\n tokens_per_group,\n torch.full_like(tokens_per_group, out_features),\n torch.full_like(tokens_per_group, hidden_states.size(1)),\n ],\n dim=1,\n )\n # Calculate block-scale offsets: round up to 128, then cumsum with initial 0\n rounded_tokens = ((tokens_per_group + 127) // 128) * 128\n blockscale_offsets = torch.cat(\n [\n torch.zeros(1, dtype=torch.int32, device=tokens_per_group.device),\n torch.cumsum(rounded_tokens, 0, dtype=torch.int32),\n ]\n )[0:-1]\n return blockscale_offsets, problem_sizes\n\n # TODO: Update this accordingly to the progress of nvfp4 kernel implementation.\n def forward(\n self,\n hidden_states: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor | None = None,\n problem_sizes: torch.Tensor | None = None,\n ) -> torch.Tensor:\n if blockscale_offsets is None or problem_sizes is None:\n # Compute them if not provided (backward compatibility)\n out_features = self.out_features\n blockscale_offsets, problem_sizes = self.compute_auxiliary_tensors(hidden_states, offsets, out_features)\n return torch.ops.nvf_cutlass.f16a_nvfp4weight_scaled_grouped_mm(\n hidden_states,\n self.fp4_weight,\n self.weight_scaling_factor,\n self.weight_global_scale,\n offsets,\n blockscale_offsets,","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.from_grouped_linear","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.from_grouped_linear#L449-L462","kind":"function","name":"from_grouped_linear","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":449,"end_line":462,"context_start_line":429,"context_end_line":482,"code":" hidden_states: torch.Tensor,\n offsets: torch.Tensor,\n blockscale_offsets: torch.Tensor | None = None,\n problem_sizes: torch.Tensor | None = None,\n ) -> torch.Tensor:\n if blockscale_offsets is None or problem_sizes is None:\n # Compute them if not provided (backward compatibility)\n out_features = self.out_features\n blockscale_offsets, problem_sizes = self.compute_auxiliary_tensors(hidden_states, offsets, out_features)\n return torch.ops.nvf_cutlass.f16a_nvfp4weight_scaled_grouped_mm(\n hidden_states,\n self.fp4_weight,\n self.weight_scaling_factor,\n self.weight_global_scale,\n offsets,\n blockscale_offsets,\n problem_sizes,\n )\n\n @staticmethod\n def from_grouped_linear(grouped_linear: GroupedLinear, fqn: str | None = None) -> NVFP4InferenceGroupedLinear:\n \"\"\"Create an NVFP4InferenceGroupedLinear from a GroupedLinear.\n\n Args:\n grouped_linear (GroupedLinear): The source GroupedLinear.\n fqn (str or None): Fully qualified name. Currently unused; reserved for future use or compatibility.\n \"\"\"\n weight = grouped_linear.weight\n fp4_weight, weight_scaling_factor, weight_global_scale = quantize_grouped_linear_weight_to_nvfp4(weight)\n return NVFP4InferenceGroupedLinear(\n fp4_weight,\n weight_scaling_factor,\n weight_global_scale,\n )\n\n\nclass GroupedSwiGLU(nn.Module):\n def __init__(self, groups: int, hidden_size: int, intermediate_size: int, dtype: torch.dtype, device: str):\n super().__init__()\n self.gate_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.up_proj = GroupedLinear(groups, hidden_size, intermediate_size, dtype, device)\n self.down_proj = GroupedLinear(groups, intermediate_size, hidden_size, dtype, device)\n\n def forward(self, hidden_states: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:\n return self.down_proj(\n torch.nn.functional.silu(self.gate_proj(hidden_states, offsets)) * self.up_proj(hidden_states, offsets),\n offsets,\n )\n\n\nclass NVFP4InferenceGroupedSwiGLU(nn.Module):\n \"\"\"NVFP4 GroupedSwiGLU that efficiently reuses auxiliary tensor computations.\"\"\"\n\n def __init__(","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.from_grouped_swiglu","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.from_grouped_swiglu#L514-L524","kind":"function","name":"from_grouped_swiglu","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":514,"end_line":524,"context_start_line":494,"context_end_line":544,"code":" # Compute auxiliary tensors once for all three operations\n intermediate_features = self.gate_proj.out_features\n blockscale_offsets_gate, problem_sizes_gate = NVFP4InferenceGroupedLinear.compute_auxiliary_tensors(\n hidden_states, offsets, intermediate_features\n )\n\n gate_out = self.gate_proj(hidden_states, offsets, blockscale_offsets_gate, problem_sizes_gate)\n up_out = self.up_proj(hidden_states, offsets, blockscale_offsets_gate, problem_sizes_gate)\n\n intermediate = torch.nn.functional.silu(gate_out) * up_out\n\n # For down_proj, we need different problem_sizes (different output features)\n hidden_features = self.down_proj.out_features\n blockscale_offsets_down, problem_sizes_down = NVFP4InferenceGroupedLinear.compute_auxiliary_tensors(\n intermediate, offsets, hidden_features\n )\n\n return self.down_proj(intermediate, offsets, blockscale_offsets_down, problem_sizes_down)\n\n @staticmethod\n def from_grouped_swiglu(grouped_swiglu: GroupedSwiGLU, fqn: str | None = None) -> NVFP4InferenceGroupedSwiGLU:\n \"\"\"Create an NVFP4InferenceGroupedSwiGLU from a GroupedSwiGLU.\n\n Args:\n grouped_swiglu (GroupedSwiGLU): The source GroupedSwiGLU.\n fqn (str or None): Fully qualified name. Currently unused; reserved for future use or compatibility.\n \"\"\"\n gate_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.gate_proj)\n up_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.up_proj)\n down_proj = NVFP4InferenceGroupedLinear.from_grouped_linear(grouped_swiglu.down_proj)\n return NVFP4InferenceGroupedSwiGLU(gate_proj, up_proj, down_proj)\n\n\n# Slightly modified version of `thunder.tests.test_networks.Llama4MoE`\n# to have the same singature as transformers' Llama4TextMoe -- in this file\n# return values include `router_logits`.\n# Ref: https://github.com/huggingface/transformers/blob/ff8b88a9/src/transformers/models/llama4/modeling_llama4.py#L147-L165\nclass Llama4MoE(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.gate = nn.Linear(\n config.hidden_size,\n config.num_routed_experts,\n bias=False,\n dtype=config.dtype,\n device=config.device,\n )\n self.shared_experts = SwiGLU(\n config.hidden_size,\n config.intermediate_size * config.num_shared_experts,","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.from_transformers_llama4textmoe","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.from_transformers_llama4textmoe#L557-L600","kind":"function","name":"from_transformers_llama4textmoe","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":557,"end_line":600,"context_start_line":537,"context_end_line":620,"code":" config.num_routed_experts,\n bias=False,\n dtype=config.dtype,\n device=config.device,\n )\n self.shared_experts = SwiGLU(\n config.hidden_size,\n config.intermediate_size * config.num_shared_experts,\n config.dtype,\n config.device,\n )\n self.routed_experts = GroupedSwiGLU(\n config.num_routed_experts,\n config.hidden_size,\n config.intermediate_size,\n config.dtype,\n config.device,\n )\n\n @staticmethod\n def from_transformers_llama4textmoe(moe: Llama4TextMoe) -> Llama4MoE:\n \"\"\"[CAUTION] A converter written by Gemini 2.5.\"\"\"\n from thunder.tests.llama4_moe import Config\n\n # 1. Create a config for the Llama4MoE model from the transformers config\n config = Config(\n \"Llama4MoE\",\n hidden_size=moe.hidden_dim,\n intermediate_size=moe.experts.intermediate_size,\n num_routed_experts=moe.num_experts,\n num_shared_experts=1, # Based on HF implementation having one shared_expert\n dtype=moe.router.weight.dtype,\n device=moe.router.weight.device,\n )\n\n # 2. Create an instance of our Llama4MoE\n new_moe = Llama4MoE(config)\n\n # 3. Copy the router weights (called 'gate' in our implementation)\n new_moe.gate.weight.data.copy_(moe.router.weight.data)\n\n # 4. Copy the shared expert weights\n new_moe.shared_experts.gate_proj.weight.data.copy_(moe.shared_expert.gate_proj.weight.data)\n new_moe.shared_experts.up_proj.weight.data.copy_(moe.shared_expert.up_proj.weight.data)\n new_moe.shared_experts.down_proj.weight.data.copy_(moe.shared_expert.down_proj.weight.data)\n\n # 5. For the routed experts, we need to handle the combined gate_up_proj\n # to match GroupedLinear\n # https://github.com/huggingface/transformers/blob/f4fc42216cd56ab6b68270bf80d811614d8d59e4/src/transformers/models/llama4/modeling_llama4.py#L55-L57\n # HF format: (groups, hidden_size, 2 * intermediate_size)\n # Our format: (groups, intermediate_size, hidden_size)\n\n # Split into gate and up projections\n gate_proj_w, up_proj_w = moe.experts.gate_up_proj.chunk(2, dim=2)\n\n new_moe.routed_experts.gate_proj.weight.data.copy_(gate_proj_w.transpose(-1, -2))\n new_moe.routed_experts.up_proj.weight.data.copy_(up_proj_w.transpose(-1, -2))\n\n # Handle down_proj\n # HF format: (groups, intermediate_size, hidden_size)\n # Our format: (groups, hidden, intermediate_size)\n new_moe.routed_experts.down_proj.weight.data.copy_(moe.experts.down_proj.transpose(-1, -2))\n\n return new_moe\n\n def run_routed_experts(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:\n batch_size, seq_len, _ = hidden_states.size()\n hidden_states = hidden_states.view(-1, hidden_states.size(-1)) # [s, h]\n\n router_logits = self.gate(hidden_states) # [s, n]\n topk_weight, topk_ids = router_logits.topk(1) # [s, 1]\n router_scores = topk_weight.sigmoid() # [s, 1]\n hidden_states = hidden_states * router_scores # [s, h]\n\n counts = torch.zeros(\n topk_ids.size(0),\n self.config.num_routed_experts,\n device=topk_ids.device,\n dtype=torch.int32,\n ) # [s, n]\n counts = counts.scatter(1, topk_ids, 1) # [s, n]\n tokens_per_expert = counts.sum(0) # [n]\n\n token_ids_sorted_by_expert_id = topk_ids.view(-1).argsort() # [s]","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.layers_for_inference_benchmark.run_routed_experts","uri":"program://Fuser/function/benchmarks.python.layers_for_inference_benchmark.run_routed_experts#L602-L637","kind":"function","name":"run_routed_experts","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":602,"end_line":637,"context_start_line":582,"context_end_line":641,"code":"\n # 5. For the routed experts, we need to handle the combined gate_up_proj\n # to match GroupedLinear\n # https://github.com/huggingface/transformers/blob/f4fc42216cd56ab6b68270bf80d811614d8d59e4/src/transformers/models/llama4/modeling_llama4.py#L55-L57\n # HF format: (groups, hidden_size, 2 * intermediate_size)\n # Our format: (groups, intermediate_size, hidden_size)\n\n # Split into gate and up projections\n gate_proj_w, up_proj_w = moe.experts.gate_up_proj.chunk(2, dim=2)\n\n new_moe.routed_experts.gate_proj.weight.data.copy_(gate_proj_w.transpose(-1, -2))\n new_moe.routed_experts.up_proj.weight.data.copy_(up_proj_w.transpose(-1, -2))\n\n # Handle down_proj\n # HF format: (groups, intermediate_size, hidden_size)\n # Our format: (groups, hidden, intermediate_size)\n new_moe.routed_experts.down_proj.weight.data.copy_(moe.experts.down_proj.transpose(-1, -2))\n\n return new_moe\n\n def run_routed_experts(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:\n batch_size, seq_len, _ = hidden_states.size()\n hidden_states = hidden_states.view(-1, hidden_states.size(-1)) # [s, h]\n\n router_logits = self.gate(hidden_states) # [s, n]\n topk_weight, topk_ids = router_logits.topk(1) # [s, 1]\n router_scores = topk_weight.sigmoid() # [s, 1]\n hidden_states = hidden_states * router_scores # [s, h]\n\n counts = torch.zeros(\n topk_ids.size(0),\n self.config.num_routed_experts,\n device=topk_ids.device,\n dtype=torch.int32,\n ) # [s, n]\n counts = counts.scatter(1, topk_ids, 1) # [s, n]\n tokens_per_expert = counts.sum(0) # [n]\n\n token_ids_sorted_by_expert_id = topk_ids.view(-1).argsort() # [s]\n tokens_sorted_by_expert_id = hidden_states[token_ids_sorted_by_expert_id] # [s, h]\n\n # Without `torch.int32`, we see `RuntimeError: Offsets tensor must be integer (int32) tensor, but got torch.int64.`\n # from PyTorch when calling _grouped_mm.\n # Prepend 0 to offsets for correct grouping\n offsets = torch.cat(\n [\n torch.zeros(1, dtype=torch.int32, device=tokens_per_expert.device),\n torch.cumsum(tokens_per_expert, 0, dtype=torch.int32),\n ]\n )[:-1] # [n]\n outs_sorted_by_expert_id = self.routed_experts(tokens_sorted_by_expert_id, offsets) # [s, h]\n\n token_ids_sorted_by_expert_inverse_id = torch.argsort(token_ids_sorted_by_expert_id)\n outs_sorted_by_token_id = outs_sorted_by_expert_id[token_ids_sorted_by_expert_inverse_id]\n\n return outs_sorted_by_token_id.view(batch_size, seq_len, -1), router_logits.view(batch_size, seq_len, -1)\n\n def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:\n outs_sorted_by_token_id, router_logits = self.run_routed_experts(hidden_states)\n return self.shared_experts(hidden_states) + outs_sorted_by_token_id, router_logits","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss","uri":"program://Fuser/module/benchmarks.python.cross_entropy_loss#L1-L230","kind":"module","name":"benchmarks.python.cross_entropy_loss","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":1,"end_line":230,"context_start_line":1,"context_end_line":230,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\n\nfrom .model_configs import configs\n\n\nclass CrossEntropyLossBase:\n def __init__(self, model_name, dtype):\n self.config = configs[model_name]()\n self.dtype = dtype\n\n def model(self):\n raise NotImplementedError\n\n def inputs(self):\n hidden_states = torch.randn(\n self.config.batch_size,\n self.config.seq_len,\n self.config.hidden_size,\n device=\"cuda\",\n dtype=self.dtype,\n requires_grad=True,\n )\n labels = torch.randint(\n 0,\n self.config.vocab_size,\n (self.config.batch_size, self.config.seq_len),\n device=\"cuda\",\n requires_grad=False,\n )\n return {\"hidden_states\": hidden_states, \"labels\": labels}\n\n def grads(self):\n grad = torch.tensor(1, device=\"cuda\", dtype=self.dtype, requires_grad=False)\n return grad\n\n # please note that this computes the IO bytes based on the graph/decomposition\n # ===== Backward graph 0 =====\n # .3 class GraphModule(torch.nn.Module):\n # def forward(self, primals_1: \"i64[8192][1]cuda:0\", primals_2: \"f32[8192, 3024][3024, 1]cuda:0\",\n # amax: \"f32[8192, 1][1, 1]cuda:0\", log: \"f32[8192, 1][1, 1]cuda:0\", convert_element_type: \"f32[][]cuda:0\", tangents_1: \"f32[][]cuda:0\"):\n # # File: /opt/pytorch/nvfuser/test.py:6 in fn, code: return torch.nn.functional.cross_entropy(input, target)\n # div_1: \"f32[][]cuda:0\" = torch.ops.aten.div.Tensor(tangents_1, convert_element_type); tangents_1 = convert_element_type = None\n # unsqueeze_1: \"i64[8192, 1][1, 1]cuda:0\" = torch.ops.aten.unsqueeze.default(primals_1, 1); primals_1 = None\n # ne_3: \"b8[8192, 1][1, 1]cuda:0\" = torch.ops.aten.ne.Scalar(unsqueeze_1, -100)\n # full_default: \"i64[][]cuda:0\" = torch.ops.aten.full.default([], 0, dtype = torch.int64, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)\n # where_2: \"i64[8192, 1][1, 1]cuda:0\" = torch.ops.aten.where.self(ne_3, unsqueeze_1, full_default); unsqueeze_1 = full_default = None\n # full_default_3: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.full.default([8192, 3024], 0, dtype = torch.float32, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)\n # scatter: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.scatter.value(full_default_3, 1, where_2, -1.0); full_default_3 = where_2 = None\n # full_default_1: \"f32[][]cuda:0\" = torch.ops.aten.full.default([], 0.0, dtype = torch.float32, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)\n # where_3: \"f32[8192, 1][1, 1]cuda:0\" = torch.ops.aten.where.self(ne_3, div_1, full_default_1); ne_3 = div_1 = full_default_1 = None\n # mul: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.mul.Tensor(scatter, where_3); scatter = where_3 = None\n # sub: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(primals_2, amax); primals_2 = amax = None\n # sub_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(sub, log); sub = log = None\n # exp_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.exp.default(sub_1); sub_1 = None\n # sum_4: \"f32[8192, 1][1, 1]cuda:0\" = torch.ops.aten.sum.dim_IntList(mul, [1], True)\n # mul_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.mul.Tensor(exp_1, sum_4); exp_1 = sum_4 = None\n # sub_2: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(mul, mul_1); mul = mul_1 = None\n # return (None, sub_2)\n\n # We account for inputs primals_1, primals_2, amax, log\n # and for the output sub_2\n def grad_iobytes(self):\n n_elements = 0\n # adding size of primals_2 and the output\n n_elements += 2 * (\n self.config.batch_size * self.config.seq_len * self.config.vocab_size\n )\n # adding size of amax and log and primals_1\n n_elements += 3 * self.config.batch_size * self.config.seq_len\n # scale by dtype size\n return n_elements * self.dtype.itemsize\n\n\nclass HfQwen2(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_qwen2\", dtype)\n\n def model(self):\n from transformers.models.qwen2.modeling_qwen2 import Qwen2PreTrainedModel\n\n class MyModel(Qwen2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfPhi3(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_phi3\", dtype)\n\n def model(self):\n from transformers.models.phi3 import Phi3PreTrainedModel\n\n class MyModel(Phi3PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfMistralNemo(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_mistral_nemo\", dtype)\n\n def model(self):\n from transformers.models.mistral import MistralPreTrainedModel\n\n class MyModel(MistralPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\ncross_entropy_loss_setup = {\n \"hf_qwen2\": HfQwen2,\n \"hf_phi3\": HfPhi3,\n \"hf_mistral_nemo\": HfMistralNemo,\n}\n\n\nclass SyntheticMiniModel:\n # Vocab sizes from popular models\n sizes_from_models = [\n 49152, # Starcoder\n 129280, # DeepSeek-R1\n 128256, # Llama3\n 202048, # Llama4\n 256000, # Gemma2\n 131072, # Mistral\n 152064, # Qwen2\n 32064, # Phi3.5\n 100352, # Phi4\n 50264, # GPT-2\n ]\n\n @staticmethod\n def mini_model(logits, labels):\n labels = torch.nn.functional.pad(labels, (0, 1))\n labels = labels[1 : labels.shape[-1]]\n logits = logits.to(dtype=torch.float32)\n logits = logits.squeeze(dim=0)\n return torch.nn.functional.cross_entropy(logits, labels)\n\n @staticmethod\n def inputs(batch_size, vocab_size):\n input = torch.randn(\n 1,\n batch_size,\n vocab_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n labels = torch.randint(\n 0,\n vocab_size - 1,\n (batch_size,),\n device=\"cuda\",\n requires_grad=False,\n )\n return (input, labels)\n\n @staticmethod\n def grads():\n grad = torch.tensor(1, device=\"cuda\", dtype=torch.float32, requires_grad=False)\n return grad\n\n @staticmethod\n def generate_vocab_sizes():\n powers_of_2 = [2**i * 1024 for i in range(4, 9)]\n\n combined_set = sorted(\n set(SyntheticMiniModel.sizes_from_models) | set(powers_of_2)\n )\n\n # for each vocab size in the set we increment in steps 64 in +/- 5 directions\n # which gives the total number of vocab sizes to benchmark\n variations = set()\n step = 64\n for num in combined_set:\n for i in range(1, 6):\n variations.add(num + (i * step))\n variations.add(num - (i * step))\n\n variations.add(num)\n\n return sorted(variations)","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.CrossEntropyLossBase","uri":"program://Fuser/class/benchmarks.python.cross_entropy_loss.CrossEntropyLossBase#L9-L74","kind":"class","name":"CrossEntropyLossBase","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":9,"end_line":74,"context_start_line":1,"context_end_line":94,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\n\nfrom .model_configs import configs\n\n\nclass CrossEntropyLossBase:\n def __init__(self, model_name, dtype):\n self.config = configs[model_name]()\n self.dtype = dtype\n\n def model(self):\n raise NotImplementedError\n\n def inputs(self):\n hidden_states = torch.randn(\n self.config.batch_size,\n self.config.seq_len,\n self.config.hidden_size,\n device=\"cuda\",\n dtype=self.dtype,\n requires_grad=True,\n )\n labels = torch.randint(\n 0,\n self.config.vocab_size,\n (self.config.batch_size, self.config.seq_len),\n device=\"cuda\",\n requires_grad=False,\n )\n return {\"hidden_states\": hidden_states, \"labels\": labels}\n\n def grads(self):\n grad = torch.tensor(1, device=\"cuda\", dtype=self.dtype, requires_grad=False)\n return grad\n\n # please note that this computes the IO bytes based on the graph/decomposition\n # ===== Backward graph 0 =====\n # .3 class GraphModule(torch.nn.Module):\n # def forward(self, primals_1: \"i64[8192][1]cuda:0\", primals_2: \"f32[8192, 3024][3024, 1]cuda:0\",\n # amax: \"f32[8192, 1][1, 1]cuda:0\", log: \"f32[8192, 1][1, 1]cuda:0\", convert_element_type: \"f32[][]cuda:0\", tangents_1: \"f32[][]cuda:0\"):\n # # File: /opt/pytorch/nvfuser/test.py:6 in fn, code: return torch.nn.functional.cross_entropy(input, target)\n # div_1: \"f32[][]cuda:0\" = torch.ops.aten.div.Tensor(tangents_1, convert_element_type); tangents_1 = convert_element_type = None\n # unsqueeze_1: \"i64[8192, 1][1, 1]cuda:0\" = torch.ops.aten.unsqueeze.default(primals_1, 1); primals_1 = None\n # ne_3: \"b8[8192, 1][1, 1]cuda:0\" = torch.ops.aten.ne.Scalar(unsqueeze_1, -100)\n # full_default: \"i64[][]cuda:0\" = torch.ops.aten.full.default([], 0, dtype = torch.int64, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)\n # where_2: \"i64[8192, 1][1, 1]cuda:0\" = torch.ops.aten.where.self(ne_3, unsqueeze_1, full_default); unsqueeze_1 = full_default = None\n # full_default_3: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.full.default([8192, 3024], 0, dtype = torch.float32, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)\n # scatter: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.scatter.value(full_default_3, 1, where_2, -1.0); full_default_3 = where_2 = None\n # full_default_1: \"f32[][]cuda:0\" = torch.ops.aten.full.default([], 0.0, dtype = torch.float32, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)\n # where_3: \"f32[8192, 1][1, 1]cuda:0\" = torch.ops.aten.where.self(ne_3, div_1, full_default_1); ne_3 = div_1 = full_default_1 = None\n # mul: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.mul.Tensor(scatter, where_3); scatter = where_3 = None\n # sub: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(primals_2, amax); primals_2 = amax = None\n # sub_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(sub, log); sub = log = None\n # exp_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.exp.default(sub_1); sub_1 = None\n # sum_4: \"f32[8192, 1][1, 1]cuda:0\" = torch.ops.aten.sum.dim_IntList(mul, [1], True)\n # mul_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.mul.Tensor(exp_1, sum_4); exp_1 = sum_4 = None\n # sub_2: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(mul, mul_1); mul = mul_1 = None\n # return (None, sub_2)\n\n # We account for inputs primals_1, primals_2, amax, log\n # and for the output sub_2\n def grad_iobytes(self):\n n_elements = 0\n # adding size of primals_2 and the output\n n_elements += 2 * (\n self.config.batch_size * self.config.seq_len * self.config.vocab_size\n )\n # adding size of amax and log and primals_1\n n_elements += 3 * self.config.batch_size * self.config.seq_len\n # scale by dtype size\n return n_elements * self.dtype.itemsize\n\n\nclass HfQwen2(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_qwen2\", dtype)\n\n def model(self):\n from transformers.models.qwen2.modeling_qwen2 import Qwen2PreTrainedModel\n\n class MyModel(Qwen2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.HfQwen2","uri":"program://Fuser/class/benchmarks.python.cross_entropy_loss.HfQwen2#L77-L100","kind":"class","name":"HfQwen2","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":77,"end_line":100,"context_start_line":57,"context_end_line":120,"code":" # exp_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.exp.default(sub_1); sub_1 = None\n # sum_4: \"f32[8192, 1][1, 1]cuda:0\" = torch.ops.aten.sum.dim_IntList(mul, [1], True)\n # mul_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.mul.Tensor(exp_1, sum_4); exp_1 = sum_4 = None\n # sub_2: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(mul, mul_1); mul = mul_1 = None\n # return (None, sub_2)\n\n # We account for inputs primals_1, primals_2, amax, log\n # and for the output sub_2\n def grad_iobytes(self):\n n_elements = 0\n # adding size of primals_2 and the output\n n_elements += 2 * (\n self.config.batch_size * self.config.seq_len * self.config.vocab_size\n )\n # adding size of amax and log and primals_1\n n_elements += 3 * self.config.batch_size * self.config.seq_len\n # scale by dtype size\n return n_elements * self.dtype.itemsize\n\n\nclass HfQwen2(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_qwen2\", dtype)\n\n def model(self):\n from transformers.models.qwen2.modeling_qwen2 import Qwen2PreTrainedModel\n\n class MyModel(Qwen2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfPhi3(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_phi3\", dtype)\n\n def model(self):\n from transformers.models.phi3 import Phi3PreTrainedModel\n\n class MyModel(Phi3PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.HfPhi3","uri":"program://Fuser/class/benchmarks.python.cross_entropy_loss.HfPhi3#L103-L127","kind":"class","name":"HfPhi3","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":103,"end_line":127,"context_start_line":83,"context_end_line":147,"code":"\n class MyModel(Qwen2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfPhi3(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_phi3\", dtype)\n\n def model(self):\n from transformers.models.phi3 import Phi3PreTrainedModel\n\n class MyModel(Phi3PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfMistralNemo(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_mistral_nemo\", dtype)\n\n def model(self):\n from transformers.models.mistral import MistralPreTrainedModel\n\n class MyModel(MistralPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.HfMistralNemo","uri":"program://Fuser/class/benchmarks.python.cross_entropy_loss.HfMistralNemo#L130-L154","kind":"class","name":"HfMistralNemo","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":130,"end_line":154,"context_start_line":110,"context_end_line":174,"code":" class MyModel(Phi3PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfMistralNemo(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_mistral_nemo\", dtype)\n\n def model(self):\n from transformers.models.mistral import MistralPreTrainedModel\n\n class MyModel(MistralPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\ncross_entropy_loss_setup = {\n \"hf_qwen2\": HfQwen2,\n \"hf_phi3\": HfPhi3,\n \"hf_mistral_nemo\": HfMistralNemo,\n}\n\n\nclass SyntheticMiniModel:\n # Vocab sizes from popular models\n sizes_from_models = [\n 49152, # Starcoder\n 129280, # DeepSeek-R1\n 128256, # Llama3\n 202048, # Llama4\n 256000, # Gemma2\n 131072, # Mistral\n 152064, # Qwen2\n 32064, # Phi3.5","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.SyntheticMiniModel","uri":"program://Fuser/class/benchmarks.python.cross_entropy_loss.SyntheticMiniModel#L164-L230","kind":"class","name":"SyntheticMiniModel","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":164,"end_line":230,"context_start_line":144,"context_end_line":230,"code":" # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\ncross_entropy_loss_setup = {\n \"hf_qwen2\": HfQwen2,\n \"hf_phi3\": HfPhi3,\n \"hf_mistral_nemo\": HfMistralNemo,\n}\n\n\nclass SyntheticMiniModel:\n # Vocab sizes from popular models\n sizes_from_models = [\n 49152, # Starcoder\n 129280, # DeepSeek-R1\n 128256, # Llama3\n 202048, # Llama4\n 256000, # Gemma2\n 131072, # Mistral\n 152064, # Qwen2\n 32064, # Phi3.5\n 100352, # Phi4\n 50264, # GPT-2\n ]\n\n @staticmethod\n def mini_model(logits, labels):\n labels = torch.nn.functional.pad(labels, (0, 1))\n labels = labels[1 : labels.shape[-1]]\n logits = logits.to(dtype=torch.float32)\n logits = logits.squeeze(dim=0)\n return torch.nn.functional.cross_entropy(logits, labels)\n\n @staticmethod\n def inputs(batch_size, vocab_size):\n input = torch.randn(\n 1,\n batch_size,\n vocab_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n labels = torch.randint(\n 0,\n vocab_size - 1,\n (batch_size,),\n device=\"cuda\",\n requires_grad=False,\n )\n return (input, labels)\n\n @staticmethod\n def grads():\n grad = torch.tensor(1, device=\"cuda\", dtype=torch.float32, requires_grad=False)\n return grad\n\n @staticmethod\n def generate_vocab_sizes():\n powers_of_2 = [2**i * 1024 for i in range(4, 9)]\n\n combined_set = sorted(\n set(SyntheticMiniModel.sizes_from_models) | set(powers_of_2)\n )\n\n # for each vocab size in the set we increment in steps 64 in +/- 5 directions\n # which gives the total number of vocab sizes to benchmark\n variations = set()\n step = 64\n for num in combined_set:\n for i in range(1, 6):\n variations.add(num + (i * step))\n variations.add(num - (i * step))\n\n variations.add(num)\n\n return sorted(variations)","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.__init__","uri":"program://Fuser/function/benchmarks.python.cross_entropy_loss.__init__#L138-L145","kind":"function","name":"__init__","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":138,"end_line":145,"context_start_line":118,"context_end_line":165,"code":" self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfMistralNemo(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_mistral_nemo\", dtype)\n\n def model(self):\n from transformers.models.mistral import MistralPreTrainedModel\n\n class MyModel(MistralPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\ncross_entropy_loss_setup = {\n \"hf_qwen2\": HfQwen2,\n \"hf_phi3\": HfPhi3,\n \"hf_mistral_nemo\": HfMistralNemo,\n}\n\n\nclass SyntheticMiniModel:\n # Vocab sizes from popular models","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.model","uri":"program://Fuser/function/benchmarks.python.cross_entropy_loss.model#L134-L154","kind":"function","name":"model","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":134,"end_line":154,"context_start_line":114,"context_end_line":174,"code":" config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfMistralNemo(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_mistral_nemo\", dtype)\n\n def model(self):\n from transformers.models.mistral import MistralPreTrainedModel\n\n class MyModel(MistralPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\ncross_entropy_loss_setup = {\n \"hf_qwen2\": HfQwen2,\n \"hf_phi3\": HfPhi3,\n \"hf_mistral_nemo\": HfMistralNemo,\n}\n\n\nclass SyntheticMiniModel:\n # Vocab sizes from popular models\n sizes_from_models = [\n 49152, # Starcoder\n 129280, # DeepSeek-R1\n 128256, # Llama3\n 202048, # Llama4\n 256000, # Gemma2\n 131072, # Mistral\n 152064, # Qwen2\n 32064, # Phi3.5","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.inputs","uri":"program://Fuser/function/benchmarks.python.cross_entropy_loss.inputs#L188-L204","kind":"function","name":"inputs","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":188,"end_line":204,"context_start_line":168,"context_end_line":224,"code":" 129280, # DeepSeek-R1\n 128256, # Llama3\n 202048, # Llama4\n 256000, # Gemma2\n 131072, # Mistral\n 152064, # Qwen2\n 32064, # Phi3.5\n 100352, # Phi4\n 50264, # GPT-2\n ]\n\n @staticmethod\n def mini_model(logits, labels):\n labels = torch.nn.functional.pad(labels, (0, 1))\n labels = labels[1 : labels.shape[-1]]\n logits = logits.to(dtype=torch.float32)\n logits = logits.squeeze(dim=0)\n return torch.nn.functional.cross_entropy(logits, labels)\n\n @staticmethod\n def inputs(batch_size, vocab_size):\n input = torch.randn(\n 1,\n batch_size,\n vocab_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n labels = torch.randint(\n 0,\n vocab_size - 1,\n (batch_size,),\n device=\"cuda\",\n requires_grad=False,\n )\n return (input, labels)\n\n @staticmethod\n def grads():\n grad = torch.tensor(1, device=\"cuda\", dtype=torch.float32, requires_grad=False)\n return grad\n\n @staticmethod\n def generate_vocab_sizes():\n powers_of_2 = [2**i * 1024 for i in range(4, 9)]\n\n combined_set = sorted(\n set(SyntheticMiniModel.sizes_from_models) | set(powers_of_2)\n )\n\n # for each vocab size in the set we increment in steps 64 in +/- 5 directions\n # which gives the total number of vocab sizes to benchmark\n variations = set()\n step = 64\n for num in combined_set:\n for i in range(1, 6):","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.grads","uri":"program://Fuser/function/benchmarks.python.cross_entropy_loss.grads#L207-L209","kind":"function","name":"grads","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":207,"end_line":209,"context_start_line":187,"context_end_line":229,"code":" @staticmethod\n def inputs(batch_size, vocab_size):\n input = torch.randn(\n 1,\n batch_size,\n vocab_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n labels = torch.randint(\n 0,\n vocab_size - 1,\n (batch_size,),\n device=\"cuda\",\n requires_grad=False,\n )\n return (input, labels)\n\n @staticmethod\n def grads():\n grad = torch.tensor(1, device=\"cuda\", dtype=torch.float32, requires_grad=False)\n return grad\n\n @staticmethod\n def generate_vocab_sizes():\n powers_of_2 = [2**i * 1024 for i in range(4, 9)]\n\n combined_set = sorted(\n set(SyntheticMiniModel.sizes_from_models) | set(powers_of_2)\n )\n\n # for each vocab size in the set we increment in steps 64 in +/- 5 directions\n # which gives the total number of vocab sizes to benchmark\n variations = set()\n step = 64\n for num in combined_set:\n for i in range(1, 6):\n variations.add(num + (i * step))\n variations.add(num - (i * step))\n\n variations.add(num)\n","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.grad_iobytes","uri":"program://Fuser/function/benchmarks.python.cross_entropy_loss.grad_iobytes#L65-L74","kind":"function","name":"grad_iobytes","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":65,"end_line":74,"context_start_line":45,"context_end_line":94,"code":" # div_1: \"f32[][]cuda:0\" = torch.ops.aten.div.Tensor(tangents_1, convert_element_type); tangents_1 = convert_element_type = None\n # unsqueeze_1: \"i64[8192, 1][1, 1]cuda:0\" = torch.ops.aten.unsqueeze.default(primals_1, 1); primals_1 = None\n # ne_3: \"b8[8192, 1][1, 1]cuda:0\" = torch.ops.aten.ne.Scalar(unsqueeze_1, -100)\n # full_default: \"i64[][]cuda:0\" = torch.ops.aten.full.default([], 0, dtype = torch.int64, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)\n # where_2: \"i64[8192, 1][1, 1]cuda:0\" = torch.ops.aten.where.self(ne_3, unsqueeze_1, full_default); unsqueeze_1 = full_default = None\n # full_default_3: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.full.default([8192, 3024], 0, dtype = torch.float32, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)\n # scatter: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.scatter.value(full_default_3, 1, where_2, -1.0); full_default_3 = where_2 = None\n # full_default_1: \"f32[][]cuda:0\" = torch.ops.aten.full.default([], 0.0, dtype = torch.float32, layout = torch.strided, device = device(type='cuda', index=0), pin_memory = False)\n # where_3: \"f32[8192, 1][1, 1]cuda:0\" = torch.ops.aten.where.self(ne_3, div_1, full_default_1); ne_3 = div_1 = full_default_1 = None\n # mul: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.mul.Tensor(scatter, where_3); scatter = where_3 = None\n # sub: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(primals_2, amax); primals_2 = amax = None\n # sub_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(sub, log); sub = log = None\n # exp_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.exp.default(sub_1); sub_1 = None\n # sum_4: \"f32[8192, 1][1, 1]cuda:0\" = torch.ops.aten.sum.dim_IntList(mul, [1], True)\n # mul_1: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.mul.Tensor(exp_1, sum_4); exp_1 = sum_4 = None\n # sub_2: \"f32[8192, 3024][3024, 1]cuda:0\" = torch.ops.aten.sub.Tensor(mul, mul_1); mul = mul_1 = None\n # return (None, sub_2)\n\n # We account for inputs primals_1, primals_2, amax, log\n # and for the output sub_2\n def grad_iobytes(self):\n n_elements = 0\n # adding size of primals_2 and the output\n n_elements += 2 * (\n self.config.batch_size * self.config.seq_len * self.config.vocab_size\n )\n # adding size of amax and log and primals_1\n n_elements += 3 * self.config.batch_size * self.config.seq_len\n # scale by dtype size\n return n_elements * self.dtype.itemsize\n\n\nclass HfQwen2(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_qwen2\", dtype)\n\n def model(self):\n from transformers.models.qwen2.modeling_qwen2 import Qwen2PreTrainedModel\n\n class MyModel(Qwen2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.mini_model","uri":"program://Fuser/function/benchmarks.python.cross_entropy_loss.mini_model#L180-L185","kind":"function","name":"mini_model","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":180,"end_line":185,"context_start_line":160,"context_end_line":205,"code":" \"hf_mistral_nemo\": HfMistralNemo,\n}\n\n\nclass SyntheticMiniModel:\n # Vocab sizes from popular models\n sizes_from_models = [\n 49152, # Starcoder\n 129280, # DeepSeek-R1\n 128256, # Llama3\n 202048, # Llama4\n 256000, # Gemma2\n 131072, # Mistral\n 152064, # Qwen2\n 32064, # Phi3.5\n 100352, # Phi4\n 50264, # GPT-2\n ]\n\n @staticmethod\n def mini_model(logits, labels):\n labels = torch.nn.functional.pad(labels, (0, 1))\n labels = labels[1 : labels.shape[-1]]\n logits = logits.to(dtype=torch.float32)\n logits = logits.squeeze(dim=0)\n return torch.nn.functional.cross_entropy(logits, labels)\n\n @staticmethod\n def inputs(batch_size, vocab_size):\n input = torch.randn(\n 1,\n batch_size,\n vocab_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n labels = torch.randint(\n 0,\n vocab_size - 1,\n (batch_size,),\n device=\"cuda\",\n requires_grad=False,\n )\n return (input, labels)\n","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.generate_vocab_sizes","uri":"program://Fuser/function/benchmarks.python.cross_entropy_loss.generate_vocab_sizes#L212-L230","kind":"function","name":"generate_vocab_sizes","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":212,"end_line":230,"context_start_line":192,"context_end_line":230,"code":" vocab_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=True,\n )\n labels = torch.randint(\n 0,\n vocab_size - 1,\n (batch_size,),\n device=\"cuda\",\n requires_grad=False,\n )\n return (input, labels)\n\n @staticmethod\n def grads():\n grad = torch.tensor(1, device=\"cuda\", dtype=torch.float32, requires_grad=False)\n return grad\n\n @staticmethod\n def generate_vocab_sizes():\n powers_of_2 = [2**i * 1024 for i in range(4, 9)]\n\n combined_set = sorted(\n set(SyntheticMiniModel.sizes_from_models) | set(powers_of_2)\n )\n\n # for each vocab size in the set we increment in steps 64 in +/- 5 directions\n # which gives the total number of vocab sizes to benchmark\n variations = set()\n step = 64\n for num in combined_set:\n for i in range(1, 6):\n variations.add(num + (i * step))\n variations.add(num - (i * step))\n\n variations.add(num)\n\n return sorted(variations)","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.MyModel","uri":"program://Fuser/class/benchmarks.python.cross_entropy_loss.MyModel#L137-L152","kind":"class","name":"MyModel","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":137,"end_line":152,"context_start_line":117,"context_end_line":172,"code":" # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfMistralNemo(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_mistral_nemo\", dtype)\n\n def model(self):\n from transformers.models.mistral import MistralPreTrainedModel\n\n class MyModel(MistralPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\ncross_entropy_loss_setup = {\n \"hf_qwen2\": HfQwen2,\n \"hf_phi3\": HfPhi3,\n \"hf_mistral_nemo\": HfMistralNemo,\n}\n\n\nclass SyntheticMiniModel:\n # Vocab sizes from popular models\n sizes_from_models = [\n 49152, # Starcoder\n 129280, # DeepSeek-R1\n 128256, # Llama3\n 202048, # Llama4\n 256000, # Gemma2\n 131072, # Mistral","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.cross_entropy_loss.forward","uri":"program://Fuser/function/benchmarks.python.cross_entropy_loss.forward#L147-L152","kind":"function","name":"forward","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":147,"end_line":152,"context_start_line":127,"context_end_line":172,"code":" return MyModel(self.config).cuda().to(self.dtype)\n\n\nclass HfMistralNemo(CrossEntropyLossBase):\n def __init__(self, dtype):\n super().__init__(\"hf_mistral_nemo\", dtype)\n\n def model(self):\n from transformers.models.mistral import MistralPreTrainedModel\n\n class MyModel(MistralPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.lm_head = torch.nn.Linear(\n config.hidden_size, config.vocab_size, bias=False\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def forward(self, hidden_states: torch.Tensor, labels: torch.LongTensor):\n logits = self.lm_head(hidden_states)\n loss = self.loss_function(\n logits=logits, labels=labels, vocab_size=self.config.vocab_size\n )\n return (loss,)\n\n return MyModel(self.config).cuda().to(self.dtype)\n\n\ncross_entropy_loss_setup = {\n \"hf_qwen2\": HfQwen2,\n \"hf_phi3\": HfPhi3,\n \"hf_mistral_nemo\": HfMistralNemo,\n}\n\n\nclass SyntheticMiniModel:\n # Vocab sizes from popular models\n sizes_from_models = [\n 49152, # Starcoder\n 129280, # DeepSeek-R1\n 128256, # Llama3\n 202048, # Llama4\n 256000, # Gemma2\n 131072, # Mistral","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_instancenorm_bwd","uri":"program://Fuser/module/benchmarks.python.test_instancenorm_bwd#L1-L54","kind":"module","name":"benchmarks.python.test_instancenorm_bwd","path":"benchmarks/python/test_instancenorm_bwd.py","language":"python","start_line":1,"end_line":54,"context_start_line":1,"context_end_line":54,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_bwd_nvf_benchmark, norm_bwd_baseline_benchmark\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n norm_bwd_nvf_benchmark(\n benchmark,\n size,\n dtype,\n \"instance_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n )\n\n\n@pytest.mark.parametrize(\"executor\", [\"eager\", \"torchcompile\"])\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_bwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_bwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"instance_norm\"\n )","source_hash":"e633a66f3167934af57e920646a245098f36e5e5d81b16ab9445ff957bdac4bb","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_instancenorm_bwd.test_instancenorm_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_instancenorm_bwd.test_instancenorm_bwd_nvf_benchmark#L19-L36","kind":"function","name":"test_instancenorm_bwd_nvf_benchmark","path":"benchmarks/python/test_instancenorm_bwd.py","language":"python","start_line":19,"end_line":36,"context_start_line":1,"context_end_line":54,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_bwd_nvf_benchmark, norm_bwd_baseline_benchmark\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n norm_bwd_nvf_benchmark(\n benchmark,\n size,\n dtype,\n \"instance_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n )\n\n\n@pytest.mark.parametrize(\"executor\", [\"eager\", \"torchcompile\"])\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_bwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_bwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"instance_norm\"\n )","source_hash":"e633a66f3167934af57e920646a245098f36e5e5d81b16ab9445ff957bdac4bb","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_instancenorm_bwd.test_instancenorm_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_instancenorm_bwd.test_instancenorm_bwd_baseline_benchmark#L49-L54","kind":"function","name":"test_instancenorm_bwd_baseline_benchmark","path":"benchmarks/python/test_instancenorm_bwd.py","language":"python","start_line":49,"end_line":54,"context_start_line":29,"context_end_line":54,"code":" benchmark,\n size,\n dtype,\n \"instance_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n )\n\n\n@pytest.mark.parametrize(\"executor\", [\"eager\", \"torchcompile\"])\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_bwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_bwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"instance_norm\"\n )","source_hash":"e633a66f3167934af57e920646a245098f36e5e5d81b16ab9445ff957bdac4bb","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference","uri":"program://Fuser/module/benchmarks.python.benchmark_inference#L1-L944","kind":"module","name":"benchmarks.python.benchmark_inference","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":1,"end_line":944,"context_start_line":1,"context_end_line":944,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"Inference benchmark focusing on throughput and latency metrics of prefill and decode phases.\n\nAutoModelForCausalLM from Hugging Face transformers is used for model implementation.\n\nKey metrics:\n- Throughput (tokens/second)\n- Latency (ms/token)\n- Time to First Token (TTFT)\n- Time Between Output Tokens (TBOT)\n\nPulled from the lightning-thunder repo. Reference:\nhttps://github.com/Lightning-AI/lightning-thunder/blob/4d3a3c3a7481efdc6a23cdeea99c3ffd31af5e78/thunder/benchmarks/benchmark_inference.py\n\"\"\"\n\n# fmt: off\n\nfrom __future__ import annotations\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass, field\nimport argparse\nimport json\nimport os\nimport statistics\nimport time\nimport warnings\nfrom typing import Any\nfrom collections.abc import Callable\nfrom looseversion import LooseVersion\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom torch.distributed.device_mesh import init_device_mesh\nfrom torch.distributed.tensor.parallel import parallelize_module, RowwiseParallel, ColwiseParallel\nfrom tqdm import tqdm\nimport transformers\nfrom transformers import AutoConfig, AutoModelForCausalLM\nfrom transformers.cache_utils import HybridChunkedCache, StaticCache\nfrom transformers.models.llama4 import Llama4TextConfig\nfrom transformers.models.llama4.modeling_llama4 import Llama4TextMoe\nfrom torch.distributed.tensor.placement_types import Shard\nfrom torch.distributed.tensor import DTensor\n\nimport thunder\nfrom thunder.dynamo.compiler import thunderfx\nif __name__ == \"__main__\":\n # TODO: remove this after folks switch to pytest\n from layers_for_inference_benchmark import (\n GroupedSwiGLU,\n Llama4MoE,\n NVFP4InferenceGroupedSwiGLU,\n nvfuser_f16a_nvfp4weight_scaled_grouped_mm,\n )\nelse:\n from .layers_for_inference_benchmark import (\n GroupedSwiGLU,\n Llama4MoE,\n NVFP4InferenceGroupedSwiGLU,\n nvfuser_f16a_nvfp4weight_scaled_grouped_mm,\n )\nfrom thunder.tests.distributed.test_moe import GroupedLinearColwiseParallel, GroupedLinearRowwiseParallel\nfrom thunder.transforms.cudagraph import CUDAGraphTransform\nfrom thunder.torch.custom_op import _register_custom_op, _register_nvfuser_translator\n\n\nRANK = int(os.environ.get(\"RANK\", 0))\nLOCAL_RANK = int(os.environ.get(\"LOCAL_RANK\", 0))\nWORLD_SIZE = int(os.environ.get(\"WORLD_SIZE\", 1))\nMASTER_ADDR = os.environ.get(\"MASTER_ADDR\", \"localhost\")\nMASTER_PORT = os.environ.get(\"MASTER_PORT\", \"29500\")\nos.environ[\"TORCH_NCCL_ASYNC_ERROR_HANDLING\"] = \"1\"\n\nDEVICE = torch.device(\"cuda\", LOCAL_RANK)\ntorch.cuda.set_device(DEVICE)\n\nif dist.is_torchelastic_launched():\n mesh = init_device_mesh(\"cuda\", (WORLD_SIZE,), mesh_dim_names=(\"tp\",))\nelse:\n mesh = None\n\nLLAMA4_MAVERICK_MODEL_ID: str = \"meta-llama/Llama-4-Maverick-17B-128E\"\nllama_4_Maverick_17B_128E_cfg_str = r\"\"\" {\n \"attention_bias\": false,\n \"attention_chunk_size\": 8192,\n \"attention_dropout\": 0.0,\n \"attn_scale\": 0.1,\n \"attn_temperature_tuning\": true,\n \"bos_token_id\": 200000,\n \"cache_implementation\": \"hybrid\",\n \"eos_token_id\": [\n 200001,\n 200007,\n 200008\n ],\n \"floor_scale\": 8192,\n \"for_llm_compressor\": false,\n \"head_dim\": 128,\n \"hidden_act\": \"silu\",\n \"hidden_size\": 5120,\n \"initializer_range\": 0.02,\n \"interleave_moe_layer_step\": 2,\n \"intermediate_size\": 8192,\n \"intermediate_size_mlp\": 16384,\n \"max_position_embeddings\": 262144,\n \"model_type\": \"llama4_text\",\n \"moe_layers\": [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47],\n \"no_rope_layers\": [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0],\n \"num_attention_heads\": 40,\n \"num_experts_per_tok\": 1,\n \"num_hidden_layers\": 48,\n \"num_key_value_heads\": 8,\n \"num_local_experts\": 128,\n \"output_router_logits\": false,\n \"pad_token_id\": 200018,\n \"rms_norm_eps\": 1e-05,\n \"rope_scaling\": null,\n \"rope_theta\": 500000.0,\n \"router_aux_loss_coef\": 0.001,\n \"router_jitter_noise\": 0.0,\n \"torch_dtype\": \"bfloat16\",\n \"use_cache\": true,\n \"use_qk_norm\": false,\n \"vocab_size\": 202048\n}\n\"\"\"\n\n\n# TODO: Add mm quantization once nvfuser implements nvfp4 gemm\n# Register nvfp4 custom ops with Thunder and nvFuser\ndef _register_nvfp4_ops():\n \"\"\"Register nvfp4 custom operations with Thunder.\"\"\"\n # Register f16a_nvfp4weight_scaled_grouped_mm with nvfuser translator\n _nvfp4_grouped_mm_symbol = _register_custom_op(nvfuser_f16a_nvfp4weight_scaled_grouped_mm)\n\n def nvfp4_grouped_mm_translator(\n activation,\n fp4_weight,\n weight_scaling_factor,\n global_scale,\n offsets,\n blockscale_offsets,\n problem_sizes,\n *,\n fd,\n lc_to_nv_map,\n ):\n from nvfuser_direct import DataType\n from thunder.executors.nvfuserex_impl import getnv\n\n nv_act = getnv(activation, fd, lc_to_nv_map)\n nv_fp4_w = getnv(fp4_weight, fd, lc_to_nv_map)\n nv_sf_w = getnv(weight_scaling_factor, fd, lc_to_nv_map)\n nv_alpha = getnv(global_scale, fd, lc_to_nv_map)\n nv_offsets = getnv(offsets, fd, lc_to_nv_map)\n nv_blocksf_offsets = getnv(blockscale_offsets, fd, lc_to_nv_map)\n nv_problem_sizes = getnv(problem_sizes, fd, lc_to_nv_map)\n fp4_mat1, layout_fp8_scale1 = fd.ops.nv_grouped_block_quantize(nv_act, nv_offsets, nv_blocksf_offsets)\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n nv_fp4_w,\n layout_fp8_scale1,\n nv_sf_w,\n nv_alpha,\n # NOTE: we might need to call contiguous on problem_sizes\n nv_problem_sizes,\n nv_offsets,\n nv_blocksf_offsets,\n DataType.BFloat16,\n )\n return out\n\n _register_nvfuser_translator(_nvfp4_grouped_mm_symbol, nvfp4_grouped_mm_translator)\n\n\n# The logic is based on https://github.com/pytorch/ao/blob/b34c1037/torchao/quantization/quant_api.py#L230\ndef _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n replacement_fn: Callable[[torch.nn.Module, str], torch.nn.Module],\n filter_fn: Callable[[torch.nn.Module, str], bool],\n cur_fqn=\"\",\n) -> None:\n \"\"\"\n Recursively replaces each child module in `model` with the result of `replacement_fn(child)`\n\n replacement_fn (Callable[[torch.nn.Module, str], torch.nn.Module]): The function to replace matching modules.\n filter_fn (Callable[[torch.nn.Module, str], bool]): The function to filter matching modules.\n cur_fqn (str): The current fully qualified name of the module.\n\n Returns:\n None\n \"\"\"\n if filter_fn(model, cur_fqn[:-1]):\n model = replacement_fn(model, cur_fqn[:-1])\n return model\n else:\n named_children_list = list(model.named_children())\n for name, child in named_children_list:\n new_child = _replace_with_custom_fn_if_matches_filter_with_name(\n child,\n replacement_fn,\n filter_fn,\n f\"{cur_fqn}{name}.\",\n )\n if new_child is not child:\n setattr(model, name, new_child)\n return model\n\n\ndef _replace_llama4_moe(model: nn.Module) -> None:\n \"\"\"Replace Llama4TextMoe with Llama4MoE to use grouped gemm.\"\"\"\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: Llama4MoE.from_transformers_llama4textmoe(model),\n lambda model, cur_fqn: isinstance(model, Llama4TextMoe),\n )\n\n\ndef _quantize_llama4(model: nn.Module) -> None:\n \"\"\"Replace linear and/or MoE with nvfp4 inference version.\n\n Args:\n model: The model to quantize\n\n Note: GroupedSwiGLU is always quantized when this function is called.\n \"\"\"\n # Always quantize GroupedSwiGLU when this function is called\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n NVFP4InferenceGroupedSwiGLU.from_grouped_swiglu,\n lambda model, cur_fqn: isinstance(model, GroupedSwiGLU),\n )\n\n\n@contextmanager\ndef timer():\n torch.cuda.synchronize()\n t1 = t2 = time.perf_counter()\n yield lambda: (t2 - t1) * 1000 # Convert to ms\n torch.cuda.synchronize()\n t2 = time.perf_counter()\n\n\n@dataclass\nclass InferenceBenchmarkConfig:\n \"\"\"Configuration for inference benchmarking\"\"\"\n\n model_name: str\n batch_size: int\n input_length: int\n output_length: int\n num_layers: int | None\n num_iterations: int\n warmup_iterations: int\n enable_nvfp4: bool # Enable NVFP4 registration and quantize GroupedSwiGLU in MoE\n fx_report_folder: str | None\n enable_nv_linear: bool\n mode: str\n disable_moe_replacement: bool\n attn_implementation: str | None\n thunder_cache: str | None\n enable_cudagraph: bool\n debug_moe: bool\n use_hardcoded_model: bool\n\n\n@dataclass\nclass InferenceMetrics:\n \"\"\"Metrics collected during inference benchmarking\"\"\"\n\n throughput_tokens_per_sec: float = 0.0\n latency_ms_per_token: float = 0.0\n time_to_first_token_ms: float = 0.0\n time_between_output_tokens_ms: float = 0.0\n total_time_ms: float = 0.0\n memory_used_gb: float = 0.0\n peak_memory_gb: float = 0.0\n\n # Separate prefill and decode metrics\n prefill_throughput_tokens_per_sec: float = 0.0\n decode_throughput_tokens_per_sec: float = 0.0\n prefill_time_ms: float = 0.0\n decode_time_ms: float = 0.0\n\n # Per-iteration metrics for variance analysis\n iteration_times: list[float] = field(default_factory=list)\n ttft_times: list[float] = field(default_factory=list)\n prefill_times: list[float] = field(default_factory=list)\n decode_times: list[float] = field(default_factory=list)\n\n\nclass InferenceBenchmark:\n \"\"\"Main benchmark class\"\"\"\n\n def __init__(self, config: InferenceBenchmarkConfig):\n self.config = config\n self.metrics = InferenceMetrics()\n # profiler_toggle is used to start/stop profiler for moe debugging\n self.profiler_toggle = False\n\n # NOTE: Model resides on meta device\n model = self._load_model()\n assert all(p.device == torch.device(\"meta\") for p in model.parameters())\n\n # NOTE: Replacement happens before model is materialized\n # otherwise, the memory usage will be increased due to\n # additional parameters materialized from the replacement module\n if not self.config.disable_moe_replacement:\n _replace_llama4_moe(model)\n assert all(p.device == torch.device(\"meta\") for p in model.parameters())\n\n tp_plan = {\n \"*.layers.*.self_attn.q_proj\": ColwiseParallel(use_local_output=True),\n \"*.layers.*.self_attn.k_proj\": ColwiseParallel(use_local_output=True),\n \"*.layers.*.self_attn.v_proj\": ColwiseParallel(use_local_output=True),\n \"*.layers.*.self_attn.o_proj\": RowwiseParallel(use_local_output=True),\n \"*.layers.*.feed_forward.gate_proj\": ColwiseParallel(use_local_output=False),\n \"*.layers.*.feed_forward.up_proj\": ColwiseParallel(use_local_output=False),\n \"*.layers.*.feed_forward.down_proj\": RowwiseParallel(use_local_output=True),\n }\n\n if self.config.disable_moe_replacement:\n tp_plan.update(\n {\n # HF MoE\n \"*.layers.*.feed_forward.shared_expert.gate_proj\": ColwiseParallel(use_local_output=False),\n \"*.layers.*.feed_forward.shared_expert.up_proj\": ColwiseParallel(use_local_output=False),\n \"*.layers.*.feed_forward.shared_expert.down_proj\": RowwiseParallel(use_local_output=True),\n # TODO:Need to write ParallelStyle for HF's grouped_mm implementation.\n }\n )\n\n else:\n tp_plan.update(\n {\n # Custom MoE\n \"*.layers.*.feed_forward.shared_experts.gate_proj\": ColwiseParallel(\n use_local_output=False, output_layouts=Shard(2)\n ),\n \"*.layers.*.feed_forward.shared_experts.up_proj\": ColwiseParallel(\n use_local_output=False, output_layouts=Shard(2)\n ),\n \"*.layers.*.feed_forward.shared_experts.down_proj\": RowwiseParallel(),\n \"*.layers.*.feed_forward.routed_experts.gate_proj\": GroupedLinearColwiseParallel(\n use_local_output=False\n ),\n \"*.layers.*.feed_forward.routed_experts.up_proj\": GroupedLinearColwiseParallel(\n use_local_output=False\n ),\n \"*.layers.*.feed_forward.routed_experts.down_proj\": GroupedLinearRowwiseParallel(),\n }\n )\n\n if mesh:\n model = parallelize_module(model, mesh, tp_plan)\n\n # Sanity check\n if not self.config.disable_moe_replacement:\n assert type(model.model.layers[1].feed_forward.shared_experts.gate_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.shared_experts.up_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.shared_experts.down_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.routed_experts.gate_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.routed_experts.up_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.routed_experts.down_proj.weight) == DTensor\n else:\n assert type(model.model.layers[1].feed_forward.shared_expert.gate_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.shared_expert.up_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.shared_expert.down_proj.weight) == DTensor\n\n # Materialize the model on the device (after Llama4MoE replacement and sharding)\n model.to_empty(device=DEVICE)\n assert all(p.device == DEVICE for p in model.parameters())\n\n # Required as thunder doesn't understand inference mode\n # And some prims like `prims._grouped_mm` don't have grad rule defined yet.\n for p in model.parameters():\n p.requires_grad_(False)\n\n assert all(not p.requires_grad for p in model.parameters())\n\n # `thunderfx` seems to hide the access to vocab_size somewhere so\n # store it here before any compiler is applied.\n self.vocab_size = model.vocab_size\n\n if self.config.enable_nvfp4:\n _quantize_llama4(model)\n\n # If debug_moe is on, we'll only compile the moe section, which is much easier to digest.\n if self.config.debug_moe:\n def compile_wrapper(model, jitter):\n class ModelWrapper(torch.nn.Module):\n\n def __init__(self, model, jitter):\n super().__init__()\n self.model = jitter._compile_model(model)\n assert not hasattr(jitter.model, \"_backend\")\n # store a reference to the compiled backend, so we can print the trace later.\n if jitter.config.mode == \"thunder\":\n jitter.model._backend = self.model._backend\n self.jitter = jitter\n\n def forward(self, *args, **kwargs):\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStart()\n out = self.model(*args, **kwargs)\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStop()\n return out\n\n return ModelWrapper(model, jitter)\n\n self.model = model\n # reuse the `replace` function with compilation.\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: compile_wrapper(model, self),\n lambda model, cur_fqn: isinstance(model, Llama4MoE),\n )\n else:\n self.model = self._compile_model(model)\n\n\n @property\n def _thunder_jit_options(self) -> dict[str, Any]:\n # `nv_enable_linear=True` might fail with distributed run\n # ref: https://github.com/NVIDIA/Fuser/issues/4507\n res = {\"transforms\": []}\n if self.config.enable_nv_linear:\n res[\"nv_enable_linear\"] = True\n res[\"nv_enable_matmul\"] = True\n if self.config.mode == \"thunderjit\":\n from thunder.recipes.hf_transformers import SDPAMaskTransform\n\n if not hasattr(self, \"_mask_transform\"):\n self._mask_transform = SDPAMaskTransform()\n res[\"transforms\"].append(self._mask_transform)\n res[\"executors\"] = [self._mask_transform.get_executor(), *thunder.get_default_executors()]\n if self.config.enable_cudagraph:\n res[\"transforms\"].append(CUDAGraphTransform())\n if self.config.thunder_cache is not None:\n res[\"cache\"] = self.config.thunder_cache\n\n return res\n\n def _compile_model(self, model):\n match self.config.mode:\n case \"eager\":\n return model\n case \"inductor\":\n if (self.config.enable_cudagraph):\n return torch.compile(model, mode=\"reduce-overhead\")\n else:\n return torch.compile(model, mode=\"default\")\n case \"thunder\":\n return thunderfx(model, **self._thunder_jit_options)\n case \"thunderjit\":\n return thunder.jit(model, **self._thunder_jit_options)\n case _:\n raise ValueError(f\"Unknown mode: {self.config.mode}\")\n\n def _load_model(self) -> torch.nn.Module:\n \"\"\"Load the model based on configuration\"\"\"\n model_id = self.config.model_name\n\n config = None\n if self.config.use_hardcoded_model:\n config = Llama4TextConfig.from_dict(\n json.loads(llama_4_Maverick_17B_128E_cfg_str)\n )\n else:\n config = AutoConfig.from_pretrained(model_id)\n\n if hasattr(config, \"text_config\"):\n config = config.text_config\n if self.config.num_layers:\n config.num_hidden_layers = self.config.num_layers\n\n self.hf_config = config\n\n with torch.device(\"meta\"):\n model = AutoModelForCausalLM.from_config(\n config, torch_dtype=torch.bfloat16, attn_implementation=self.config.attn_implementation\n )\n\n return model\n\n def generate_batch(self) -> tuple[torch.Tensor, HybridChunkedCache]:\n \"\"\"Generate a batch of input tokens\"\"\"\n batch_size = self.config.batch_size\n input_length = self.config.input_length\n\n input_ids = torch.randint(0, self.vocab_size, (batch_size, input_length), device=DEVICE)\n if LooseVersion(transformers.__version__) >= LooseVersion(\"4.55\"):\n # Transformers deprecated HybridChunkedCache in favour of static in 4.55.x\n # NOTE: tp_size should only reflect tensor parallelism size, not total world size.\n # If 2D parallelism (data parallel + tensor parallel) is added in the future,\n # tp_size should be set to the tensor parallelism size only (e.g., WORLD_SIZE // DP_SIZE),\n # not WORLD_SIZE, so that StaticCache correctly handles sharded KV heads.\n past_key_values = StaticCache(\n config=self.hf_config,\n max_batch_size=input_ids.shape[0],\n max_cache_len=input_ids.shape[1] + self.config.output_length,\n device=DEVICE,\n dtype=torch.bfloat16,\n tp_size=W\n# ... truncated ...","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":true} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference._register_nvfp4_ops","uri":"program://Fuser/function/benchmarks.python.benchmark_inference._register_nvfp4_ops#L134-L176","kind":"function","name":"_register_nvfp4_ops","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":134,"end_line":176,"context_start_line":114,"context_end_line":196,"code":" \"num_hidden_layers\": 48,\n \"num_key_value_heads\": 8,\n \"num_local_experts\": 128,\n \"output_router_logits\": false,\n \"pad_token_id\": 200018,\n \"rms_norm_eps\": 1e-05,\n \"rope_scaling\": null,\n \"rope_theta\": 500000.0,\n \"router_aux_loss_coef\": 0.001,\n \"router_jitter_noise\": 0.0,\n \"torch_dtype\": \"bfloat16\",\n \"use_cache\": true,\n \"use_qk_norm\": false,\n \"vocab_size\": 202048\n}\n\"\"\"\n\n\n# TODO: Add mm quantization once nvfuser implements nvfp4 gemm\n# Register nvfp4 custom ops with Thunder and nvFuser\ndef _register_nvfp4_ops():\n \"\"\"Register nvfp4 custom operations with Thunder.\"\"\"\n # Register f16a_nvfp4weight_scaled_grouped_mm with nvfuser translator\n _nvfp4_grouped_mm_symbol = _register_custom_op(nvfuser_f16a_nvfp4weight_scaled_grouped_mm)\n\n def nvfp4_grouped_mm_translator(\n activation,\n fp4_weight,\n weight_scaling_factor,\n global_scale,\n offsets,\n blockscale_offsets,\n problem_sizes,\n *,\n fd,\n lc_to_nv_map,\n ):\n from nvfuser_direct import DataType\n from thunder.executors.nvfuserex_impl import getnv\n\n nv_act = getnv(activation, fd, lc_to_nv_map)\n nv_fp4_w = getnv(fp4_weight, fd, lc_to_nv_map)\n nv_sf_w = getnv(weight_scaling_factor, fd, lc_to_nv_map)\n nv_alpha = getnv(global_scale, fd, lc_to_nv_map)\n nv_offsets = getnv(offsets, fd, lc_to_nv_map)\n nv_blocksf_offsets = getnv(blockscale_offsets, fd, lc_to_nv_map)\n nv_problem_sizes = getnv(problem_sizes, fd, lc_to_nv_map)\n fp4_mat1, layout_fp8_scale1 = fd.ops.nv_grouped_block_quantize(nv_act, nv_offsets, nv_blocksf_offsets)\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n nv_fp4_w,\n layout_fp8_scale1,\n nv_sf_w,\n nv_alpha,\n # NOTE: we might need to call contiguous on problem_sizes\n nv_problem_sizes,\n nv_offsets,\n nv_blocksf_offsets,\n DataType.BFloat16,\n )\n return out\n\n _register_nvfuser_translator(_nvfp4_grouped_mm_symbol, nvfp4_grouped_mm_translator)\n\n\n# The logic is based on https://github.com/pytorch/ao/blob/b34c1037/torchao/quantization/quant_api.py#L230\ndef _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n replacement_fn: Callable[[torch.nn.Module, str], torch.nn.Module],\n filter_fn: Callable[[torch.nn.Module, str], bool],\n cur_fqn=\"\",\n) -> None:\n \"\"\"\n Recursively replaces each child module in `model` with the result of `replacement_fn(child)`\n\n replacement_fn (Callable[[torch.nn.Module, str], torch.nn.Module]): The function to replace matching modules.\n filter_fn (Callable[[torch.nn.Module, str], bool]): The function to filter matching modules.\n cur_fqn (str): The current fully qualified name of the module.\n\n Returns:\n None\n \"\"\"\n if filter_fn(model, cur_fqn[:-1]):","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference._replace_with_custom_fn_if_matches_filter_with_name","uri":"program://Fuser/function/benchmarks.python.benchmark_inference._replace_with_custom_fn_if_matches_filter_with_name#L180-L210","kind":"function","name":"_replace_with_custom_fn_if_matches_filter_with_name","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":180,"end_line":210,"context_start_line":160,"context_end_line":230,"code":" nv_problem_sizes = getnv(problem_sizes, fd, lc_to_nv_map)\n fp4_mat1, layout_fp8_scale1 = fd.ops.nv_grouped_block_quantize(nv_act, nv_offsets, nv_blocksf_offsets)\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n nv_fp4_w,\n layout_fp8_scale1,\n nv_sf_w,\n nv_alpha,\n # NOTE: we might need to call contiguous on problem_sizes\n nv_problem_sizes,\n nv_offsets,\n nv_blocksf_offsets,\n DataType.BFloat16,\n )\n return out\n\n _register_nvfuser_translator(_nvfp4_grouped_mm_symbol, nvfp4_grouped_mm_translator)\n\n\n# The logic is based on https://github.com/pytorch/ao/blob/b34c1037/torchao/quantization/quant_api.py#L230\ndef _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n replacement_fn: Callable[[torch.nn.Module, str], torch.nn.Module],\n filter_fn: Callable[[torch.nn.Module, str], bool],\n cur_fqn=\"\",\n) -> None:\n \"\"\"\n Recursively replaces each child module in `model` with the result of `replacement_fn(child)`\n\n replacement_fn (Callable[[torch.nn.Module, str], torch.nn.Module]): The function to replace matching modules.\n filter_fn (Callable[[torch.nn.Module, str], bool]): The function to filter matching modules.\n cur_fqn (str): The current fully qualified name of the module.\n\n Returns:\n None\n \"\"\"\n if filter_fn(model, cur_fqn[:-1]):\n model = replacement_fn(model, cur_fqn[:-1])\n return model\n else:\n named_children_list = list(model.named_children())\n for name, child in named_children_list:\n new_child = _replace_with_custom_fn_if_matches_filter_with_name(\n child,\n replacement_fn,\n filter_fn,\n f\"{cur_fqn}{name}.\",\n )\n if new_child is not child:\n setattr(model, name, new_child)\n return model\n\n\ndef _replace_llama4_moe(model: nn.Module) -> None:\n \"\"\"Replace Llama4TextMoe with Llama4MoE to use grouped gemm.\"\"\"\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: Llama4MoE.from_transformers_llama4textmoe(model),\n lambda model, cur_fqn: isinstance(model, Llama4TextMoe),\n )\n\n\ndef _quantize_llama4(model: nn.Module) -> None:\n \"\"\"Replace linear and/or MoE with nvfp4 inference version.\n\n Args:\n model: The model to quantize\n\n Note: GroupedSwiGLU is always quantized when this function is called.\n \"\"\"\n # Always quantize GroupedSwiGLU when this function is called","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference._replace_llama4_moe","uri":"program://Fuser/function/benchmarks.python.benchmark_inference._replace_llama4_moe#L213-L219","kind":"function","name":"_replace_llama4_moe","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":213,"end_line":219,"context_start_line":193,"context_end_line":239,"code":" Returns:\n None\n \"\"\"\n if filter_fn(model, cur_fqn[:-1]):\n model = replacement_fn(model, cur_fqn[:-1])\n return model\n else:\n named_children_list = list(model.named_children())\n for name, child in named_children_list:\n new_child = _replace_with_custom_fn_if_matches_filter_with_name(\n child,\n replacement_fn,\n filter_fn,\n f\"{cur_fqn}{name}.\",\n )\n if new_child is not child:\n setattr(model, name, new_child)\n return model\n\n\ndef _replace_llama4_moe(model: nn.Module) -> None:\n \"\"\"Replace Llama4TextMoe with Llama4MoE to use grouped gemm.\"\"\"\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: Llama4MoE.from_transformers_llama4textmoe(model),\n lambda model, cur_fqn: isinstance(model, Llama4TextMoe),\n )\n\n\ndef _quantize_llama4(model: nn.Module) -> None:\n \"\"\"Replace linear and/or MoE with nvfp4 inference version.\n\n Args:\n model: The model to quantize\n\n Note: GroupedSwiGLU is always quantized when this function is called.\n \"\"\"\n # Always quantize GroupedSwiGLU when this function is called\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n NVFP4InferenceGroupedSwiGLU.from_grouped_swiglu,\n lambda model, cur_fqn: isinstance(model, GroupedSwiGLU),\n )\n\n\n@contextmanager\ndef timer():","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference._quantize_llama4","uri":"program://Fuser/function/benchmarks.python.benchmark_inference._quantize_llama4#L222-L235","kind":"function","name":"_quantize_llama4","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":222,"end_line":235,"context_start_line":202,"context_end_line":255,"code":" new_child = _replace_with_custom_fn_if_matches_filter_with_name(\n child,\n replacement_fn,\n filter_fn,\n f\"{cur_fqn}{name}.\",\n )\n if new_child is not child:\n setattr(model, name, new_child)\n return model\n\n\ndef _replace_llama4_moe(model: nn.Module) -> None:\n \"\"\"Replace Llama4TextMoe with Llama4MoE to use grouped gemm.\"\"\"\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: Llama4MoE.from_transformers_llama4textmoe(model),\n lambda model, cur_fqn: isinstance(model, Llama4TextMoe),\n )\n\n\ndef _quantize_llama4(model: nn.Module) -> None:\n \"\"\"Replace linear and/or MoE with nvfp4 inference version.\n\n Args:\n model: The model to quantize\n\n Note: GroupedSwiGLU is always quantized when this function is called.\n \"\"\"\n # Always quantize GroupedSwiGLU when this function is called\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n NVFP4InferenceGroupedSwiGLU.from_grouped_swiglu,\n lambda model, cur_fqn: isinstance(model, GroupedSwiGLU),\n )\n\n\n@contextmanager\ndef timer():\n torch.cuda.synchronize()\n t1 = t2 = time.perf_counter()\n yield lambda: (t2 - t1) * 1000 # Convert to ms\n torch.cuda.synchronize()\n t2 = time.perf_counter()\n\n\n@dataclass\nclass InferenceBenchmarkConfig:\n \"\"\"Configuration for inference benchmarking\"\"\"\n\n model_name: str\n batch_size: int\n input_length: int\n output_length: int\n num_layers: int | None","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.timer","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.timer#L239-L244","kind":"function","name":"timer","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":239,"end_line":244,"context_start_line":219,"context_end_line":264,"code":" )\n\n\ndef _quantize_llama4(model: nn.Module) -> None:\n \"\"\"Replace linear and/or MoE with nvfp4 inference version.\n\n Args:\n model: The model to quantize\n\n Note: GroupedSwiGLU is always quantized when this function is called.\n \"\"\"\n # Always quantize GroupedSwiGLU when this function is called\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n NVFP4InferenceGroupedSwiGLU.from_grouped_swiglu,\n lambda model, cur_fqn: isinstance(model, GroupedSwiGLU),\n )\n\n\n@contextmanager\ndef timer():\n torch.cuda.synchronize()\n t1 = t2 = time.perf_counter()\n yield lambda: (t2 - t1) * 1000 # Convert to ms\n torch.cuda.synchronize()\n t2 = time.perf_counter()\n\n\n@dataclass\nclass InferenceBenchmarkConfig:\n \"\"\"Configuration for inference benchmarking\"\"\"\n\n model_name: str\n batch_size: int\n input_length: int\n output_length: int\n num_layers: int | None\n num_iterations: int\n warmup_iterations: int\n enable_nvfp4: bool # Enable NVFP4 registration and quantize GroupedSwiGLU in MoE\n fx_report_folder: str | None\n enable_nv_linear: bool\n mode: str\n disable_moe_replacement: bool\n attn_implementation: str | None\n thunder_cache: str | None","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.InferenceBenchmarkConfig","uri":"program://Fuser/class/benchmarks.python.benchmark_inference.InferenceBenchmarkConfig#L248-L267","kind":"class","name":"InferenceBenchmarkConfig","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":248,"end_line":267,"context_start_line":228,"context_end_line":287,"code":" Note: GroupedSwiGLU is always quantized when this function is called.\n \"\"\"\n # Always quantize GroupedSwiGLU when this function is called\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n NVFP4InferenceGroupedSwiGLU.from_grouped_swiglu,\n lambda model, cur_fqn: isinstance(model, GroupedSwiGLU),\n )\n\n\n@contextmanager\ndef timer():\n torch.cuda.synchronize()\n t1 = t2 = time.perf_counter()\n yield lambda: (t2 - t1) * 1000 # Convert to ms\n torch.cuda.synchronize()\n t2 = time.perf_counter()\n\n\n@dataclass\nclass InferenceBenchmarkConfig:\n \"\"\"Configuration for inference benchmarking\"\"\"\n\n model_name: str\n batch_size: int\n input_length: int\n output_length: int\n num_layers: int | None\n num_iterations: int\n warmup_iterations: int\n enable_nvfp4: bool # Enable NVFP4 registration and quantize GroupedSwiGLU in MoE\n fx_report_folder: str | None\n enable_nv_linear: bool\n mode: str\n disable_moe_replacement: bool\n attn_implementation: str | None\n thunder_cache: str | None\n enable_cudagraph: bool\n debug_moe: bool\n use_hardcoded_model: bool\n\n\n@dataclass\nclass InferenceMetrics:\n \"\"\"Metrics collected during inference benchmarking\"\"\"\n\n throughput_tokens_per_sec: float = 0.0\n latency_ms_per_token: float = 0.0\n time_to_first_token_ms: float = 0.0\n time_between_output_tokens_ms: float = 0.0\n total_time_ms: float = 0.0\n memory_used_gb: float = 0.0\n peak_memory_gb: float = 0.0\n\n # Separate prefill and decode metrics\n prefill_throughput_tokens_per_sec: float = 0.0\n decode_throughput_tokens_per_sec: float = 0.0\n prefill_time_ms: float = 0.0\n decode_time_ms: float = 0.0\n","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.InferenceMetrics","uri":"program://Fuser/class/benchmarks.python.benchmark_inference.InferenceMetrics#L271-L292","kind":"class","name":"InferenceMetrics","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":271,"end_line":292,"context_start_line":251,"context_end_line":312,"code":" model_name: str\n batch_size: int\n input_length: int\n output_length: int\n num_layers: int | None\n num_iterations: int\n warmup_iterations: int\n enable_nvfp4: bool # Enable NVFP4 registration and quantize GroupedSwiGLU in MoE\n fx_report_folder: str | None\n enable_nv_linear: bool\n mode: str\n disable_moe_replacement: bool\n attn_implementation: str | None\n thunder_cache: str | None\n enable_cudagraph: bool\n debug_moe: bool\n use_hardcoded_model: bool\n\n\n@dataclass\nclass InferenceMetrics:\n \"\"\"Metrics collected during inference benchmarking\"\"\"\n\n throughput_tokens_per_sec: float = 0.0\n latency_ms_per_token: float = 0.0\n time_to_first_token_ms: float = 0.0\n time_between_output_tokens_ms: float = 0.0\n total_time_ms: float = 0.0\n memory_used_gb: float = 0.0\n peak_memory_gb: float = 0.0\n\n # Separate prefill and decode metrics\n prefill_throughput_tokens_per_sec: float = 0.0\n decode_throughput_tokens_per_sec: float = 0.0\n prefill_time_ms: float = 0.0\n decode_time_ms: float = 0.0\n\n # Per-iteration metrics for variance analysis\n iteration_times: list[float] = field(default_factory=list)\n ttft_times: list[float] = field(default_factory=list)\n prefill_times: list[float] = field(default_factory=list)\n decode_times: list[float] = field(default_factory=list)\n\n\nclass InferenceBenchmark:\n \"\"\"Main benchmark class\"\"\"\n\n def __init__(self, config: InferenceBenchmarkConfig):\n self.config = config\n self.metrics = InferenceMetrics()\n # profiler_toggle is used to start/stop profiler for moe debugging\n self.profiler_toggle = False\n\n # NOTE: Model resides on meta device\n model = self._load_model()\n assert all(p.device == torch.device(\"meta\") for p in model.parameters())\n\n # NOTE: Replacement happens before model is materialized\n # otherwise, the memory usage will be increased due to\n # additional parameters materialized from the replacement module\n if not self.config.disable_moe_replacement:\n _replace_llama4_moe(model)","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.InferenceBenchmark","uri":"program://Fuser/class/benchmarks.python.benchmark_inference.InferenceBenchmark#L295-L781","kind":"class","name":"InferenceBenchmark","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":295,"end_line":781,"context_start_line":275,"context_end_line":801,"code":" latency_ms_per_token: float = 0.0\n time_to_first_token_ms: float = 0.0\n time_between_output_tokens_ms: float = 0.0\n total_time_ms: float = 0.0\n memory_used_gb: float = 0.0\n peak_memory_gb: float = 0.0\n\n # Separate prefill and decode metrics\n prefill_throughput_tokens_per_sec: float = 0.0\n decode_throughput_tokens_per_sec: float = 0.0\n prefill_time_ms: float = 0.0\n decode_time_ms: float = 0.0\n\n # Per-iteration metrics for variance analysis\n iteration_times: list[float] = field(default_factory=list)\n ttft_times: list[float] = field(default_factory=list)\n prefill_times: list[float] = field(default_factory=list)\n decode_times: list[float] = field(default_factory=list)\n\n\nclass InferenceBenchmark:\n \"\"\"Main benchmark class\"\"\"\n\n def __init__(self, config: InferenceBenchmarkConfig):\n self.config = config\n self.metrics = InferenceMetrics()\n # profiler_toggle is used to start/stop profiler for moe debugging\n self.profiler_toggle = False\n\n # NOTE: Model resides on meta device\n model = self._load_model()\n assert all(p.device == torch.device(\"meta\") for p in model.parameters())\n\n # NOTE: Replacement happens before model is materialized\n # otherwise, the memory usage will be increased due to\n # additional parameters materialized from the replacement module\n if not self.config.disable_moe_replacement:\n _replace_llama4_moe(model)\n assert all(p.device == torch.device(\"meta\") for p in model.parameters())\n\n tp_plan = {\n \"*.layers.*.self_attn.q_proj\": ColwiseParallel(use_local_output=True),\n \"*.layers.*.self_attn.k_proj\": ColwiseParallel(use_local_output=True),\n \"*.layers.*.self_attn.v_proj\": ColwiseParallel(use_local_output=True),\n \"*.layers.*.self_attn.o_proj\": RowwiseParallel(use_local_output=True),\n \"*.layers.*.feed_forward.gate_proj\": ColwiseParallel(use_local_output=False),\n \"*.layers.*.feed_forward.up_proj\": ColwiseParallel(use_local_output=False),\n \"*.layers.*.feed_forward.down_proj\": RowwiseParallel(use_local_output=True),\n }\n\n if self.config.disable_moe_replacement:\n tp_plan.update(\n {\n # HF MoE\n \"*.layers.*.feed_forward.shared_expert.gate_proj\": ColwiseParallel(use_local_output=False),\n \"*.layers.*.feed_forward.shared_expert.up_proj\": ColwiseParallel(use_local_output=False),\n \"*.layers.*.feed_forward.shared_expert.down_proj\": RowwiseParallel(use_local_output=True),\n # TODO:Need to write ParallelStyle for HF's grouped_mm implementation.\n }\n )\n\n else:\n tp_plan.update(\n {\n # Custom MoE\n \"*.layers.*.feed_forward.shared_experts.gate_proj\": ColwiseParallel(\n use_local_output=False, output_layouts=Shard(2)\n ),\n \"*.layers.*.feed_forward.shared_experts.up_proj\": ColwiseParallel(\n use_local_output=False, output_layouts=Shard(2)\n ),\n \"*.layers.*.feed_forward.shared_experts.down_proj\": RowwiseParallel(),\n \"*.layers.*.feed_forward.routed_experts.gate_proj\": GroupedLinearColwiseParallel(\n use_local_output=False\n ),\n \"*.layers.*.feed_forward.routed_experts.up_proj\": GroupedLinearColwiseParallel(\n use_local_output=False\n ),\n \"*.layers.*.feed_forward.routed_experts.down_proj\": GroupedLinearRowwiseParallel(),\n }\n )\n\n if mesh:\n model = parallelize_module(model, mesh, tp_plan)\n\n # Sanity check\n if not self.config.disable_moe_replacement:\n assert type(model.model.layers[1].feed_forward.shared_experts.gate_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.shared_experts.up_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.shared_experts.down_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.routed_experts.gate_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.routed_experts.up_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.routed_experts.down_proj.weight) == DTensor\n else:\n assert type(model.model.layers[1].feed_forward.shared_expert.gate_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.shared_expert.up_proj.weight) == DTensor\n assert type(model.model.layers[1].feed_forward.shared_expert.down_proj.weight) == DTensor\n\n # Materialize the model on the device (after Llama4MoE replacement and sharding)\n model.to_empty(device=DEVICE)\n assert all(p.device == DEVICE for p in model.parameters())\n\n # Required as thunder doesn't understand inference mode\n # And some prims like `prims._grouped_mm` don't have grad rule defined yet.\n for p in model.parameters():\n p.requires_grad_(False)\n\n assert all(not p.requires_grad for p in model.parameters())\n\n # `thunderfx` seems to hide the access to vocab_size somewhere so\n # store it here before any compiler is applied.\n self.vocab_size = model.vocab_size\n\n if self.config.enable_nvfp4:\n _quantize_llama4(model)\n\n # If debug_moe is on, we'll only compile the moe section, which is much easier to digest.\n if self.config.debug_moe:\n def compile_wrapper(model, jitter):\n class ModelWrapper(torch.nn.Module):\n\n def __init__(self, model, jitter):\n super().__init__()\n self.model = jitter._compile_model(model)\n assert not hasattr(jitter.model, \"_backend\")\n # store a reference to the compiled backend, so we can print the trace later.\n if jitter.config.mode == \"thunder\":\n jitter.model._backend = self.model._backend\n self.jitter = jitter\n\n def forward(self, *args, **kwargs):\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStart()\n out = self.model(*args, **kwargs)\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStop()\n return out\n\n return ModelWrapper(model, jitter)\n\n self.model = model\n # reuse the `replace` function with compilation.\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: compile_wrapper(model, self),\n lambda model, cur_fqn: isinstance(model, Llama4MoE),\n )\n else:\n self.model = self._compile_model(model)\n\n\n @property\n def _thunder_jit_options(self) -> dict[str, Any]:\n # `nv_enable_linear=True` might fail with distributed run\n # ref: https://github.com/NVIDIA/Fuser/issues/4507\n res = {\"transforms\": []}\n if self.config.enable_nv_linear:\n res[\"nv_enable_linear\"] = True\n res[\"nv_enable_matmul\"] = True\n if self.config.mode == \"thunderjit\":\n from thunder.recipes.hf_transformers import SDPAMaskTransform\n\n if not hasattr(self, \"_mask_transform\"):\n self._mask_transform = SDPAMaskTransform()\n res[\"transforms\"].append(self._mask_transform)\n res[\"executors\"] = [self._mask_transform.get_executor(), *thunder.get_default_executors()]\n if self.config.enable_cudagraph:\n res[\"transforms\"].append(CUDAGraphTransform())\n if self.config.thunder_cache is not None:\n res[\"cache\"] = self.config.thunder_cache\n\n return res\n\n def _compile_model(self, model):\n match self.config.mode:\n case \"eager\":\n return model\n case \"inductor\":\n if (self.config.enable_cudagraph):\n return torch.compile(model, mode=\"reduce-overhead\")\n else:\n return torch.compile(model, mode=\"default\")\n case \"thunder\":\n return thunderfx(model, **self._thunder_jit_options)\n case \"thunderjit\":\n return thunder.jit(model, **self._thunder_jit_options)\n case _:\n raise ValueError(f\"Unknown mode: {self.config.mode}\")\n\n def _load_model(self) -> torch.nn.Module:\n \"\"\"Load the model based on configuration\"\"\"\n model_id = self.config.model_name\n\n config = None\n if self.config.use_hardcoded_model:\n config = Llama4TextConfig.from_dict(\n json.loads(llama_4_Maverick_17B_128E_cfg_str)\n )\n else:\n config = AutoConfig.from_pretrained(model_id)\n\n if hasattr(config, \"text_config\"):\n config = config.text_config\n if self.config.num_layers:\n config.num_hidden_layers = self.config.num_layers\n\n self.hf_config = config\n\n with torch.device(\"meta\"):\n model = AutoModelForCausalLM.from_config(\n config, torch_dtype=torch.bfloat16, attn_implementation=self.config.attn_implementation\n )\n\n return model\n\n def generate_batch(self) -> tuple[torch.Tensor, HybridChunkedCache]:\n \"\"\"Generate a batch of input tokens\"\"\"\n batch_size = self.config.batch_size\n input_length = self.config.input_length\n\n input_ids = torch.randint(0, self.vocab_size, (batch_size, input_length), device=DEVICE)\n if LooseVersion(transformers.__version__) >= LooseVersion(\"4.55\"):\n # Transformers deprecated HybridChunkedCache in favour of static in 4.55.x\n # NOTE: tp_size should only reflect tensor parallelism size, not total world size.\n # If 2D parallelism (data parallel + tensor parallel) is added in the future,\n # tp_size should be set to the tensor parallelism size only (e.g., WORLD_SIZE // DP_SIZE),\n # not WORLD_SIZE, so that StaticCache correctly handles sharded KV heads.\n past_key_values = StaticCache(\n config=self.hf_config,\n max_batch_size=input_ids.shape[0],\n max_cache_len=input_ids.shape[1] + self.config.output_length,\n device=DEVICE,\n dtype=torch.bfloat16,\n tp_size=WORLD_SIZE,\n )\n else:\n past_key_values = HybridChunkedCache(\n self.hf_config, input_ids.shape[0], input_ids.shape[1] + self.config.output_length\n )\n for layer_idx in range(self.hf_config.num_hidden_layers):\n # key_states.shape[1] is used to retrieve the number of key value heads, all other dimensions can be 1 and ignored\n # https://github.com/huggingface/transformers/blob/9300728665aaeb0ebf4db99f9d9fbce916b4a183/src/transformers/cache_utils.py#L1822\n dummy_key_states = torch.empty(1, self.hf_config.num_key_value_heads // WORLD_SIZE, 1, 1, device=DEVICE)\n past_key_values.initialise_cache_layer(layer_idx, dummy_key_states)\n\n return input_ids, past_key_values\n\n def get_next_token(\n self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache | StaticCache\n ) -> torch.Tensor:\n with torch.no_grad():\n outputs = self.model(input_ids, past_key_values=past_key_values, use_cache=True)\n logits = outputs.logits # [B, seq_len, vocab_size]\n next_token_logits = logits[:, -1, :]\n next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)\n return next_token\n\n def prefill(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Prefill phase: Process the entire input prompt at once.\n Returns the next token.\n\n Similar to: https://github.com/pytorch-labs/gpt-fast/blob/main/generate.py#L68-L82\n \"\"\"\n return self.get_next_token(input_ids, past_key_values)\n\n def decode_one_token(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Decode phase: Generate a single token given the current sequence.\n Returns the next token.\n \"\"\"\n # input_pos: [B, 1] One token at the time\n assert input_ids.shape[-1] == 1, f\"Expected shape (B, 1), but found {input_ids.shape}\"\n return self.get_next_token(input_ids, past_key_values)\n\n # TODO: Running `torchrun --nproc-per-node 2 thunder/benchmarks/benchmark_inference.py --input-length 32 --output-length 32 --mode eager --num-iterations 10`\n # with inference mode results in\n # [rank1]: File \"/opt/pytorch/lightning-thunder/thunder/benchmarks/layers_for_inference_benchmark.py\", line 358, in grouped_mm\n # [rank1]: group_outs.append(group_a @ b[idx])\n # [rank1]: ~^^^^^\n # [rank1]: RuntimeError: Cannot set version_counter for inference tensor\n # @torch.inference_mode()\n def generate(\n self, input_ids: torch.Tensor, max_new_tokens: int, past_key_values: HybridChunkedCache\n ) -> dict[str, Any]:\n \"\"\"\n Generate tokens using separate prefill and decode phases.\n Returns detailed metrics for both phases.\n \"\"\"\n # Prefill phase - process the entire prompt\n with timer() as prefill_timer:\n torch.cuda.nvtx.range_push(\"prefill\")\n first_token = self.prefill(input_ids, past_key_values)\n torch.cuda.nvtx.range_pop()\n prefill_time = prefill_timer()\n generated_tokens = [first_token]\n\n # Decode phase - generate remaining tokens one by one\n next_token = first_token\n with timer() as decode_timer:\n for idx in range(max_new_tokens - 1):\n torch.cuda.nvtx.range_push(\"decode:\" + str(idx))\n next_token = self.decode_one_token(next_token, past_key_values)\n generated_tokens.append(next_token)\n torch.cuda.nvtx.range_pop()\n\n total_decode_time = decode_timer()\n\n return {\n \"prefill_time_ms\": prefill_time,\n \"decode_time_ms\": total_decode_time,\n \"generated_tokens\": generated_tokens,\n \"total_tokens\": max_new_tokens,\n }\n\n def measure_inference_step(\n self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache, max_new_tokens: int\n ) -> dict[str, float]:\n \"\"\"Measure a single inference step with detailed timing using separate prefill/decode\"\"\"\n # Generate tokens with separate prefill/decode tracking\n generation_result = self.generate(input_ids, max_new_tokens, past_key_values)\n total_time = generation_result[\"prefill_time_ms\"] + generation_result[\"decode_time_ms\"]\n\n # Extract metrics\n ttft = generation_result[\"prefill_time_ms\"] # Time to first token is the prefill time\n total_decode_time = generation_result[\"decode_time_ms\"]\n avg_tbot = total_decode_time / (max_new_tokens - 1) if max_new_tokens > 1 else 0\n\n # Calculate throughput\n total_tokens = self.config.output_length * self.config.batch_size\n throughput = (total_tokens / total_time) * 1000 # tokens/second\n\n # Calculate separate prefill and decode throughput\n prefill_tokens = self.config.input_length * self.config.batch_size\n prefill_throughput = (prefill_tokens / generation_result[\"prefill_time_ms\"]) * 1000\n\n decode_tokens = (self.config.output_length - 1) * self.config.batch_size\n decode_throughput = (decode_tokens / total_decode_time) * 1000 if total_decode_time > 0 else 0\n\n return {\n \"ttft\": ttft,\n \"avg_tbot\": avg_tbot,\n \"total_time\": total_time,\n \"throughput\": throughput,\n \"prefill_throughput\": prefill_throughput,\n \"decode_throughput\": decode_throughput,\n \"prefill_time\": generation_result[\"prefill_time_ms\"],\n \"total_decode_time\": total_decode_time,\n }\n\n def run_benchmark(self) -> InferenceMetrics:\n \"\"\"Run the full benchmark and collect metrics\"\"\"\n print(f\"Running inference benchmark for {self.config.model_name}\")\n\n print(f\"Batch size: {self.config.batch_size}\")\n print(f\"Input length: {self.config.input_length}\")\n print(f\"Output length: {self.config.output_length}\")\n print(f\"Mode: {self.config.mode}\")\n\n print(f\"\\nWarming up with {self.config.warmup_iterations} iterations...\")\n input_ids, past_key_values = self.generate_batch()\n\n for idx in tqdm(range(self.config.warmup_iterations), disable=LOCAL_RANK != 0):\n past_key_values.reset()\n # Use output_length to warm up sufficiently. Otherwise, Thunder's\n # first-run latency is terribly slow due to lack of dynamic shape\n # support.\n torch.cuda.nvtx.range_push(\"warmup:\" + str(idx))\n _ = self.measure_inference_step(input_ids, past_key_values, self.config.output_length)\n torch.cuda.nvtx.range_pop()\n\n print(f\"\\nRunning {self.config.num_iterations} benchmark iterations...\")\n all_metrics = []\n\n if torch.cuda.is_available():\n torch.cuda.reset_peak_memory_stats()\n\n for idx in tqdm(range(self.config.num_iterations), disable=LOCAL_RANK != 0):\n past_key_values.reset()\n\n is_under_nsys = bool(os.environ.get(\"NSYS_PROFILING_SESSION_ID\"))\n # Wrap each non-warmup iteration with cudaProfilerStart() and\n # cudaProfilerStop(). This allows the user to run\n # ```shell\n # nsys profile --capture-range=cudaProfilerApi --capture-range-end=repeat: ...\n # ```\n # to record only the non-warmup iterations.\n # Note when debug_moe is on, we'll defer the flag inside the moe wrapper.\n self.profiler_toggle = is_under_nsys\n if is_under_nsys and not self.config.debug_moe:\n torch.cuda.cudart().cudaProfilerStart()\n torch.cuda.nvtx.range_push(\"step:\" + str(idx))\n iter_metrics = self.measure_inference_step(input_ids, past_key_values, self.config.output_length)\n torch.cuda.nvtx.range_pop()\n if is_under_nsys and not self.config.debug_moe:\n torch.cuda.cudart().cudaProfilerStop()\n\n all_metrics.append(iter_metrics)\n\n # Track metrics\n self.metrics.iteration_times.append(iter_metrics[\"total_time\"])\n self.metrics.ttft_times.append(iter_metrics[\"ttft\"])\n self.metrics.prefill_times.append(iter_metrics[\"prefill_time\"])\n self.metrics.decode_times.append(iter_metrics[\"total_decode_time\"])\n\n self._calculate_aggregate_metrics(all_metrics)\n\n if torch.cuda.is_available():\n self.metrics.memory_used_gb = torch.cuda.memory_allocated() / 1e9\n self.metrics.peak_memory_gb = torch.cuda.max_memory_allocated() / 1e9\n\n if self.config.fx_report_folder is not None and self.config.mode == \"thunder\":\n self.model._backend.save_reproducer_to_folder(self.config.fx_report_folder)\n return\n\n return self.metrics\n\n def _calculate_aggregate_metrics(self, all_metrics: list[dict[str, Any]]):\n \"\"\"Calculate aggregate metrics from individual iterations\"\"\"\n # Average throughput\n throughputs = [m[\"throughput\"] for m\n# ... truncated ...","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":true} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.CustomFormatter","uri":"program://Fuser/class/benchmarks.python.benchmark_inference.CustomFormatter#L784-L785","kind":"class","name":"CustomFormatter","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":784,"end_line":785,"context_start_line":764,"context_end_line":805,"code":" \"prefill_time_ms\": self.metrics.prefill_time_ms,\n \"decode_time_ms\": self.metrics.decode_time_ms,\n \"total_time_ms\": self.metrics.total_time_ms,\n \"memory_used_gb\": self.metrics.memory_used_gb,\n \"peak_memory_gb\": self.metrics.peak_memory_gb,\n },\n \"detailed_metrics\": {\n \"iteration_times\": self.metrics.iteration_times,\n \"ttft_times\": self.metrics.ttft_times,\n \"prefill_times\": self.metrics.prefill_times,\n \"decode_times\": self.metrics.decode_times,\n },\n }\n\n with open(filename, \"w\") as f:\n json.dump(results, f, indent=2)\n\n print(f\"\\nResults saved to {filename}\")\n\n\nclass CustomFormatter(argparse.RawDescriptionHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):\n pass\n\n\ndef parse_args() -> argparse.Namespace:\n \"\"\"Command line interface for the benchmark\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Thunder Inference Benchmark\",\n formatter_class=CustomFormatter,\n epilog=\"\"\"\nExamples:\n python benchmark_inference.py --input-length 2048 --output-length 512 --model-name meta-llama/Llama-4-Maverick-17B-128E --mode eager\n \"\"\",\n )\n\n parser.add_argument(\n \"--model-name\",\n type=str,\n default=LLAMA4_MAVERICK_MODEL_ID,\n help=\"Model to benchmark\",\n )\n parser.add_argument(\"--batch-size\", type=int, default=1, help=\"Batch size for inference\")","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.parse_args","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.parse_args#L788-L881","kind":"function","name":"parse_args","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":788,"end_line":881,"context_start_line":768,"context_end_line":901,"code":" \"peak_memory_gb\": self.metrics.peak_memory_gb,\n },\n \"detailed_metrics\": {\n \"iteration_times\": self.metrics.iteration_times,\n \"ttft_times\": self.metrics.ttft_times,\n \"prefill_times\": self.metrics.prefill_times,\n \"decode_times\": self.metrics.decode_times,\n },\n }\n\n with open(filename, \"w\") as f:\n json.dump(results, f, indent=2)\n\n print(f\"\\nResults saved to {filename}\")\n\n\nclass CustomFormatter(argparse.RawDescriptionHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):\n pass\n\n\ndef parse_args() -> argparse.Namespace:\n \"\"\"Command line interface for the benchmark\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Thunder Inference Benchmark\",\n formatter_class=CustomFormatter,\n epilog=\"\"\"\nExamples:\n python benchmark_inference.py --input-length 2048 --output-length 512 --model-name meta-llama/Llama-4-Maverick-17B-128E --mode eager\n \"\"\",\n )\n\n parser.add_argument(\n \"--model-name\",\n type=str,\n default=LLAMA4_MAVERICK_MODEL_ID,\n help=\"Model to benchmark\",\n )\n parser.add_argument(\"--batch-size\", type=int, default=1, help=\"Batch size for inference\")\n parser.add_argument(\n \"--input-length\",\n type=int,\n default=2048,\n help=\"Input sequence length\",\n )\n parser.add_argument(\n \"--output-length\",\n type=int,\n default=128,\n help=\"Output sequence length\",\n )\n parser.add_argument(\"--num-iterations\", type=int, default=100, help=\"Number of benchmark iterations\")\n parser.add_argument(\"--warmup-iterations\", type=int, default=10, help=\"Number of warmup iterations\")\n parser.add_argument(\n \"--num-layers\",\n default=2,\n type=int,\n help=\"Number of layers of the moddel. Llama4 Maverick has 48 hidden layers, which could be too memory hungry\",\n )\n parser.add_argument(\n \"--disable-moe-replacement\",\n action=\"store_true\",\n help=\"Disallow replacement of Llama4TextMoe with our custom Llama4MoE which uses grouped gemm.\",\n )\n\n # Execution configuration\n parser.add_argument(\n \"--mode\",\n type=str,\n default=\"eager\",\n choices=(\"thunder\", \"eager\", \"inductor\", \"thunderjit\"),\n help=\"Compilation mode: thunder, eager (default), or inductor. thunder runs thunderfx.\",\n )\n parser.add_argument(\n \"--fx-report-folder\",\n default=None,\n type=str,\n help=\"Specify the folder for thunderfx_benchmark_report.\",\n )\n\n parser.add_argument(\n \"--enable-nvfp4\",\n action=\"store_true\",\n help=\"Enable NVFP4 quantization for MoE GroupedSwiGLU layers (has nvfuser grouped_mm support)\",\n )\n parser.add_argument(\n \"--enable-nv-linear\",\n action=\"store_true\",\n help=\"let nvfuser take care of linear and matmul, note that this might fail with distributed run. See: https://github.com/NVIDIA/Fuser/issues/4507\",\n )\n\n parser.add_argument(\n \"--thunder-trace\",\n action=\"store_true\",\n help=\"Enable debug dump of thunder trace\",\n )\n parser.add_argument(\n \"--debug-moe\",\n action=\"store_true\",\n help=\"Enable debug of MoE, limiting profile and compilation only to the hand written MoE layer\",\n )\n parser.add_argument(\"--save-results\", action=\"store_true\", help=\"Save results to JSON file\")\n parser.add_argument(\"--output-dir\", type=str, default=\"./results\", help=\"Directory to save results\")\n parser.add_argument(\n \"--thunder-cache\",\n type=str,\n default=None,\n help=\"Cache option: no caching, same input, constant values, symbolic values. See `cache` argument of `thunder.jit` for more details.\",\n )\n parser.add_argument(\"--enable-cudagraph\", action=\"store_true\", help=\"Pass CUDAGraphTransform to Thunder, or use reduce-overhead for torch.compile\")\n parser.add_argument(\"--attn-implementation\", type=str, default=None, help=\"Attention implementation\")\n parser.add_argument(\"--use-hardcoded-model\", action=\"store_true\", help=\"Use the hardcoded Llama4 config, rather than pulling from huggingfaces\")\n\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n if args.save_results:\n os.makedirs(args.output_dir, exist_ok=True)\n\n # Register NVFP4 custom ops with nvfuser translators when enabled\n if args.enable_nvfp4:\n try:\n _register_nvfp4_ops()\n except Exception as e:\n # If registration fails (e.g., nvfuser not available), warn and continue\n warnings.warn(f\"Failed to register nvfp4 custom ops: {e}\")\n\n config = InferenceBenchmarkConfig(\n model_name=args.model_name,\n batch_size=args.batch_size,\n input_length=args.input_length,\n output_length=args.output_length,","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.main","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.main#L884-L933","kind":"function","name":"main","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":884,"end_line":933,"context_start_line":864,"context_end_line":944,"code":" \"--debug-moe\",\n action=\"store_true\",\n help=\"Enable debug of MoE, limiting profile and compilation only to the hand written MoE layer\",\n )\n parser.add_argument(\"--save-results\", action=\"store_true\", help=\"Save results to JSON file\")\n parser.add_argument(\"--output-dir\", type=str, default=\"./results\", help=\"Directory to save results\")\n parser.add_argument(\n \"--thunder-cache\",\n type=str,\n default=None,\n help=\"Cache option: no caching, same input, constant values, symbolic values. See `cache` argument of `thunder.jit` for more details.\",\n )\n parser.add_argument(\"--enable-cudagraph\", action=\"store_true\", help=\"Pass CUDAGraphTransform to Thunder, or use reduce-overhead for torch.compile\")\n parser.add_argument(\"--attn-implementation\", type=str, default=None, help=\"Attention implementation\")\n parser.add_argument(\"--use-hardcoded-model\", action=\"store_true\", help=\"Use the hardcoded Llama4 config, rather than pulling from huggingfaces\")\n\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n if args.save_results:\n os.makedirs(args.output_dir, exist_ok=True)\n\n # Register NVFP4 custom ops with nvfuser translators when enabled\n if args.enable_nvfp4:\n try:\n _register_nvfp4_ops()\n except Exception as e:\n # If registration fails (e.g., nvfuser not available), warn and continue\n warnings.warn(f\"Failed to register nvfp4 custom ops: {e}\")\n\n config = InferenceBenchmarkConfig(\n model_name=args.model_name,\n batch_size=args.batch_size,\n input_length=args.input_length,\n output_length=args.output_length,\n num_layers=args.num_layers,\n num_iterations=args.num_iterations,\n warmup_iterations=args.warmup_iterations,\n mode=args.mode,\n enable_nvfp4=args.enable_nvfp4,\n fx_report_folder=args.fx_report_folder,\n enable_nv_linear=args.enable_nv_linear,\n disable_moe_replacement=args.disable_moe_replacement,\n attn_implementation=args.attn_implementation,\n thunder_cache=args.thunder_cache,\n enable_cudagraph=args.enable_cudagraph,\n debug_moe=args.debug_moe,\n use_hardcoded_model=args.use_hardcoded_model,\n )\n benchmark = InferenceBenchmark(config)\n\n benchmark.run_benchmark()\n benchmark.print_results()\n\n if args.thunder_trace and args.mode == \"thunder\":\n backend = benchmark.model._backend\n for subgraph_info in backend.subgraph_infos:\n assert isinstance(subgraph_info.original_graph_module, torch.fx.GraphModule)\n assert len(subgraph_info.thunder_compiled_fns)\n for thunder_fn in subgraph_info.thunder_compiled_fns:\n print(thunder.last_traces(thunder_fn)[-1])\n\n if args.save_results:\n timestamp = time.strftime(\"%Y%m%d_%H%M%S\")\n filename = f\"thunder_inference_{args.model_name.replace('/', '_')}_{timestamp}.json\"\n path = os.path.join(args.output_dir, filename)\n benchmark.save_results(path)\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception:\n raise\n finally:\n if mesh:\n for process_group in mesh.get_all_groups():\n dist.destroy_process_group(process_group)","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.nvfp4_grouped_mm_translator","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.nvfp4_grouped_mm_translator#L139-L174","kind":"function","name":"nvfp4_grouped_mm_translator","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":139,"end_line":174,"context_start_line":119,"context_end_line":194,"code":" \"rms_norm_eps\": 1e-05,\n \"rope_scaling\": null,\n \"rope_theta\": 500000.0,\n \"router_aux_loss_coef\": 0.001,\n \"router_jitter_noise\": 0.0,\n \"torch_dtype\": \"bfloat16\",\n \"use_cache\": true,\n \"use_qk_norm\": false,\n \"vocab_size\": 202048\n}\n\"\"\"\n\n\n# TODO: Add mm quantization once nvfuser implements nvfp4 gemm\n# Register nvfp4 custom ops with Thunder and nvFuser\ndef _register_nvfp4_ops():\n \"\"\"Register nvfp4 custom operations with Thunder.\"\"\"\n # Register f16a_nvfp4weight_scaled_grouped_mm with nvfuser translator\n _nvfp4_grouped_mm_symbol = _register_custom_op(nvfuser_f16a_nvfp4weight_scaled_grouped_mm)\n\n def nvfp4_grouped_mm_translator(\n activation,\n fp4_weight,\n weight_scaling_factor,\n global_scale,\n offsets,\n blockscale_offsets,\n problem_sizes,\n *,\n fd,\n lc_to_nv_map,\n ):\n from nvfuser_direct import DataType\n from thunder.executors.nvfuserex_impl import getnv\n\n nv_act = getnv(activation, fd, lc_to_nv_map)\n nv_fp4_w = getnv(fp4_weight, fd, lc_to_nv_map)\n nv_sf_w = getnv(weight_scaling_factor, fd, lc_to_nv_map)\n nv_alpha = getnv(global_scale, fd, lc_to_nv_map)\n nv_offsets = getnv(offsets, fd, lc_to_nv_map)\n nv_blocksf_offsets = getnv(blockscale_offsets, fd, lc_to_nv_map)\n nv_problem_sizes = getnv(problem_sizes, fd, lc_to_nv_map)\n fp4_mat1, layout_fp8_scale1 = fd.ops.nv_grouped_block_quantize(nv_act, nv_offsets, nv_blocksf_offsets)\n out = fd.ops.cutlass_nvfp4_grouped_mm(\n fp4_mat1,\n nv_fp4_w,\n layout_fp8_scale1,\n nv_sf_w,\n nv_alpha,\n # NOTE: we might need to call contiguous on problem_sizes\n nv_problem_sizes,\n nv_offsets,\n nv_blocksf_offsets,\n DataType.BFloat16,\n )\n return out\n\n _register_nvfuser_translator(_nvfp4_grouped_mm_symbol, nvfp4_grouped_mm_translator)\n\n\n# The logic is based on https://github.com/pytorch/ao/blob/b34c1037/torchao/quantization/quant_api.py#L230\ndef _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n replacement_fn: Callable[[torch.nn.Module, str], torch.nn.Module],\n filter_fn: Callable[[torch.nn.Module, str], bool],\n cur_fqn=\"\",\n) -> None:\n \"\"\"\n Recursively replaces each child module in `model` with the result of `replacement_fn(child)`\n\n replacement_fn (Callable[[torch.nn.Module, str], torch.nn.Module]): The function to replace matching modules.\n filter_fn (Callable[[torch.nn.Module, str], bool]): The function to filter matching modules.\n cur_fqn (str): The current fully qualified name of the module.\n\n Returns:\n None","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.__init__","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.__init__#L396-L403","kind":"function","name":"__init__","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":396,"end_line":403,"context_start_line":376,"context_end_line":423,"code":"\n # Required as thunder doesn't understand inference mode\n # And some prims like `prims._grouped_mm` don't have grad rule defined yet.\n for p in model.parameters():\n p.requires_grad_(False)\n\n assert all(not p.requires_grad for p in model.parameters())\n\n # `thunderfx` seems to hide the access to vocab_size somewhere so\n # store it here before any compiler is applied.\n self.vocab_size = model.vocab_size\n\n if self.config.enable_nvfp4:\n _quantize_llama4(model)\n\n # If debug_moe is on, we'll only compile the moe section, which is much easier to digest.\n if self.config.debug_moe:\n def compile_wrapper(model, jitter):\n class ModelWrapper(torch.nn.Module):\n\n def __init__(self, model, jitter):\n super().__init__()\n self.model = jitter._compile_model(model)\n assert not hasattr(jitter.model, \"_backend\")\n # store a reference to the compiled backend, so we can print the trace later.\n if jitter.config.mode == \"thunder\":\n jitter.model._backend = self.model._backend\n self.jitter = jitter\n\n def forward(self, *args, **kwargs):\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStart()\n out = self.model(*args, **kwargs)\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStop()\n return out\n\n return ModelWrapper(model, jitter)\n\n self.model = model\n # reuse the `replace` function with compilation.\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: compile_wrapper(model, self),\n lambda model, cur_fqn: isinstance(model, Llama4MoE),\n )\n else:\n self.model = self._compile_model(model)","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference._thunder_jit_options","uri":"program://Fuser/function/benchmarks.python.benchmark_inference._thunder_jit_options#L427-L446","kind":"function","name":"_thunder_jit_options","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":427,"end_line":446,"context_start_line":407,"context_end_line":466,"code":" torch.cuda.cudart().cudaProfilerStart()\n out = self.model(*args, **kwargs)\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStop()\n return out\n\n return ModelWrapper(model, jitter)\n\n self.model = model\n # reuse the `replace` function with compilation.\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: compile_wrapper(model, self),\n lambda model, cur_fqn: isinstance(model, Llama4MoE),\n )\n else:\n self.model = self._compile_model(model)\n\n\n @property\n def _thunder_jit_options(self) -> dict[str, Any]:\n # `nv_enable_linear=True` might fail with distributed run\n # ref: https://github.com/NVIDIA/Fuser/issues/4507\n res = {\"transforms\": []}\n if self.config.enable_nv_linear:\n res[\"nv_enable_linear\"] = True\n res[\"nv_enable_matmul\"] = True\n if self.config.mode == \"thunderjit\":\n from thunder.recipes.hf_transformers import SDPAMaskTransform\n\n if not hasattr(self, \"_mask_transform\"):\n self._mask_transform = SDPAMaskTransform()\n res[\"transforms\"].append(self._mask_transform)\n res[\"executors\"] = [self._mask_transform.get_executor(), *thunder.get_default_executors()]\n if self.config.enable_cudagraph:\n res[\"transforms\"].append(CUDAGraphTransform())\n if self.config.thunder_cache is not None:\n res[\"cache\"] = self.config.thunder_cache\n\n return res\n\n def _compile_model(self, model):\n match self.config.mode:\n case \"eager\":\n return model\n case \"inductor\":\n if (self.config.enable_cudagraph):\n return torch.compile(model, mode=\"reduce-overhead\")\n else:\n return torch.compile(model, mode=\"default\")\n case \"thunder\":\n return thunderfx(model, **self._thunder_jit_options)\n case \"thunderjit\":\n return thunder.jit(model, **self._thunder_jit_options)\n case _:\n raise ValueError(f\"Unknown mode: {self.config.mode}\")\n\n def _load_model(self) -> torch.nn.Module:\n \"\"\"Load the model based on configuration\"\"\"\n model_id = self.config.model_name","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference._compile_model","uri":"program://Fuser/function/benchmarks.python.benchmark_inference._compile_model#L448-L462","kind":"function","name":"_compile_model","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":448,"end_line":462,"context_start_line":428,"context_end_line":482,"code":" # `nv_enable_linear=True` might fail with distributed run\n # ref: https://github.com/NVIDIA/Fuser/issues/4507\n res = {\"transforms\": []}\n if self.config.enable_nv_linear:\n res[\"nv_enable_linear\"] = True\n res[\"nv_enable_matmul\"] = True\n if self.config.mode == \"thunderjit\":\n from thunder.recipes.hf_transformers import SDPAMaskTransform\n\n if not hasattr(self, \"_mask_transform\"):\n self._mask_transform = SDPAMaskTransform()\n res[\"transforms\"].append(self._mask_transform)\n res[\"executors\"] = [self._mask_transform.get_executor(), *thunder.get_default_executors()]\n if self.config.enable_cudagraph:\n res[\"transforms\"].append(CUDAGraphTransform())\n if self.config.thunder_cache is not None:\n res[\"cache\"] = self.config.thunder_cache\n\n return res\n\n def _compile_model(self, model):\n match self.config.mode:\n case \"eager\":\n return model\n case \"inductor\":\n if (self.config.enable_cudagraph):\n return torch.compile(model, mode=\"reduce-overhead\")\n else:\n return torch.compile(model, mode=\"default\")\n case \"thunder\":\n return thunderfx(model, **self._thunder_jit_options)\n case \"thunderjit\":\n return thunder.jit(model, **self._thunder_jit_options)\n case _:\n raise ValueError(f\"Unknown mode: {self.config.mode}\")\n\n def _load_model(self) -> torch.nn.Module:\n \"\"\"Load the model based on configuration\"\"\"\n model_id = self.config.model_name\n\n config = None\n if self.config.use_hardcoded_model:\n config = Llama4TextConfig.from_dict(\n json.loads(llama_4_Maverick_17B_128E_cfg_str)\n )\n else:\n config = AutoConfig.from_pretrained(model_id)\n\n if hasattr(config, \"text_config\"):\n config = config.text_config\n if self.config.num_layers:\n config.num_hidden_layers = self.config.num_layers\n\n self.hf_config = config\n","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference._load_model","uri":"program://Fuser/function/benchmarks.python.benchmark_inference._load_model#L464-L488","kind":"function","name":"_load_model","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":464,"end_line":488,"context_start_line":444,"context_end_line":508,"code":" res[\"cache\"] = self.config.thunder_cache\n\n return res\n\n def _compile_model(self, model):\n match self.config.mode:\n case \"eager\":\n return model\n case \"inductor\":\n if (self.config.enable_cudagraph):\n return torch.compile(model, mode=\"reduce-overhead\")\n else:\n return torch.compile(model, mode=\"default\")\n case \"thunder\":\n return thunderfx(model, **self._thunder_jit_options)\n case \"thunderjit\":\n return thunder.jit(model, **self._thunder_jit_options)\n case _:\n raise ValueError(f\"Unknown mode: {self.config.mode}\")\n\n def _load_model(self) -> torch.nn.Module:\n \"\"\"Load the model based on configuration\"\"\"\n model_id = self.config.model_name\n\n config = None\n if self.config.use_hardcoded_model:\n config = Llama4TextConfig.from_dict(\n json.loads(llama_4_Maverick_17B_128E_cfg_str)\n )\n else:\n config = AutoConfig.from_pretrained(model_id)\n\n if hasattr(config, \"text_config\"):\n config = config.text_config\n if self.config.num_layers:\n config.num_hidden_layers = self.config.num_layers\n\n self.hf_config = config\n\n with torch.device(\"meta\"):\n model = AutoModelForCausalLM.from_config(\n config, torch_dtype=torch.bfloat16, attn_implementation=self.config.attn_implementation\n )\n\n return model\n\n def generate_batch(self) -> tuple[torch.Tensor, HybridChunkedCache]:\n \"\"\"Generate a batch of input tokens\"\"\"\n batch_size = self.config.batch_size\n input_length = self.config.input_length\n\n input_ids = torch.randint(0, self.vocab_size, (batch_size, input_length), device=DEVICE)\n if LooseVersion(transformers.__version__) >= LooseVersion(\"4.55\"):\n # Transformers deprecated HybridChunkedCache in favour of static in 4.55.x\n # NOTE: tp_size should only reflect tensor parallelism size, not total world size.\n # If 2D parallelism (data parallel + tensor parallel) is added in the future,\n # tp_size should be set to the tensor parallelism size only (e.g., WORLD_SIZE // DP_SIZE),\n # not WORLD_SIZE, so that StaticCache correctly handles sharded KV heads.\n past_key_values = StaticCache(\n config=self.hf_config,\n max_batch_size=input_ids.shape[0],\n max_cache_len=input_ids.shape[1] + self.config.output_length,\n device=DEVICE,\n dtype=torch.bfloat16,\n tp_size=WORLD_SIZE,","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.generate_batch","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.generate_batch#L490-L520","kind":"function","name":"generate_batch","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":490,"end_line":520,"context_start_line":470,"context_end_line":540,"code":" config = Llama4TextConfig.from_dict(\n json.loads(llama_4_Maverick_17B_128E_cfg_str)\n )\n else:\n config = AutoConfig.from_pretrained(model_id)\n\n if hasattr(config, \"text_config\"):\n config = config.text_config\n if self.config.num_layers:\n config.num_hidden_layers = self.config.num_layers\n\n self.hf_config = config\n\n with torch.device(\"meta\"):\n model = AutoModelForCausalLM.from_config(\n config, torch_dtype=torch.bfloat16, attn_implementation=self.config.attn_implementation\n )\n\n return model\n\n def generate_batch(self) -> tuple[torch.Tensor, HybridChunkedCache]:\n \"\"\"Generate a batch of input tokens\"\"\"\n batch_size = self.config.batch_size\n input_length = self.config.input_length\n\n input_ids = torch.randint(0, self.vocab_size, (batch_size, input_length), device=DEVICE)\n if LooseVersion(transformers.__version__) >= LooseVersion(\"4.55\"):\n # Transformers deprecated HybridChunkedCache in favour of static in 4.55.x\n # NOTE: tp_size should only reflect tensor parallelism size, not total world size.\n # If 2D parallelism (data parallel + tensor parallel) is added in the future,\n # tp_size should be set to the tensor parallelism size only (e.g., WORLD_SIZE // DP_SIZE),\n # not WORLD_SIZE, so that StaticCache correctly handles sharded KV heads.\n past_key_values = StaticCache(\n config=self.hf_config,\n max_batch_size=input_ids.shape[0],\n max_cache_len=input_ids.shape[1] + self.config.output_length,\n device=DEVICE,\n dtype=torch.bfloat16,\n tp_size=WORLD_SIZE,\n )\n else:\n past_key_values = HybridChunkedCache(\n self.hf_config, input_ids.shape[0], input_ids.shape[1] + self.config.output_length\n )\n for layer_idx in range(self.hf_config.num_hidden_layers):\n # key_states.shape[1] is used to retrieve the number of key value heads, all other dimensions can be 1 and ignored\n # https://github.com/huggingface/transformers/blob/9300728665aaeb0ebf4db99f9d9fbce916b4a183/src/transformers/cache_utils.py#L1822\n dummy_key_states = torch.empty(1, self.hf_config.num_key_value_heads // WORLD_SIZE, 1, 1, device=DEVICE)\n past_key_values.initialise_cache_layer(layer_idx, dummy_key_states)\n\n return input_ids, past_key_values\n\n def get_next_token(\n self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache | StaticCache\n ) -> torch.Tensor:\n with torch.no_grad():\n outputs = self.model(input_ids, past_key_values=past_key_values, use_cache=True)\n logits = outputs.logits # [B, seq_len, vocab_size]\n next_token_logits = logits[:, -1, :]\n next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)\n return next_token\n\n def prefill(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Prefill phase: Process the entire input prompt at once.\n Returns the next token.\n\n Similar to: https://github.com/pytorch-labs/gpt-fast/blob/main/generate.py#L68-L82\n \"\"\"\n return self.get_next_token(input_ids, past_key_values)\n","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.get_next_token","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.get_next_token#L522-L530","kind":"function","name":"get_next_token","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":522,"end_line":530,"context_start_line":502,"context_end_line":550,"code":" past_key_values = StaticCache(\n config=self.hf_config,\n max_batch_size=input_ids.shape[0],\n max_cache_len=input_ids.shape[1] + self.config.output_length,\n device=DEVICE,\n dtype=torch.bfloat16,\n tp_size=WORLD_SIZE,\n )\n else:\n past_key_values = HybridChunkedCache(\n self.hf_config, input_ids.shape[0], input_ids.shape[1] + self.config.output_length\n )\n for layer_idx in range(self.hf_config.num_hidden_layers):\n # key_states.shape[1] is used to retrieve the number of key value heads, all other dimensions can be 1 and ignored\n # https://github.com/huggingface/transformers/blob/9300728665aaeb0ebf4db99f9d9fbce916b4a183/src/transformers/cache_utils.py#L1822\n dummy_key_states = torch.empty(1, self.hf_config.num_key_value_heads // WORLD_SIZE, 1, 1, device=DEVICE)\n past_key_values.initialise_cache_layer(layer_idx, dummy_key_states)\n\n return input_ids, past_key_values\n\n def get_next_token(\n self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache | StaticCache\n ) -> torch.Tensor:\n with torch.no_grad():\n outputs = self.model(input_ids, past_key_values=past_key_values, use_cache=True)\n logits = outputs.logits # [B, seq_len, vocab_size]\n next_token_logits = logits[:, -1, :]\n next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)\n return next_token\n\n def prefill(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Prefill phase: Process the entire input prompt at once.\n Returns the next token.\n\n Similar to: https://github.com/pytorch-labs/gpt-fast/blob/main/generate.py#L68-L82\n \"\"\"\n return self.get_next_token(input_ids, past_key_values)\n\n def decode_one_token(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Decode phase: Generate a single token given the current sequence.\n Returns the next token.\n \"\"\"\n # input_pos: [B, 1] One token at the time\n assert input_ids.shape[-1] == 1, f\"Expected shape (B, 1), but found {input_ids.shape}\"\n return self.get_next_token(input_ids, past_key_values)\n\n # TODO: Running `torchrun --nproc-per-node 2 thunder/benchmarks/benchmark_inference.py --input-length 32 --output-length 32 --mode eager --num-iterations 10`","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.prefill","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.prefill#L532-L539","kind":"function","name":"prefill","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":532,"end_line":539,"context_start_line":512,"context_end_line":559,"code":" self.hf_config, input_ids.shape[0], input_ids.shape[1] + self.config.output_length\n )\n for layer_idx in range(self.hf_config.num_hidden_layers):\n # key_states.shape[1] is used to retrieve the number of key value heads, all other dimensions can be 1 and ignored\n # https://github.com/huggingface/transformers/blob/9300728665aaeb0ebf4db99f9d9fbce916b4a183/src/transformers/cache_utils.py#L1822\n dummy_key_states = torch.empty(1, self.hf_config.num_key_value_heads // WORLD_SIZE, 1, 1, device=DEVICE)\n past_key_values.initialise_cache_layer(layer_idx, dummy_key_states)\n\n return input_ids, past_key_values\n\n def get_next_token(\n self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache | StaticCache\n ) -> torch.Tensor:\n with torch.no_grad():\n outputs = self.model(input_ids, past_key_values=past_key_values, use_cache=True)\n logits = outputs.logits # [B, seq_len, vocab_size]\n next_token_logits = logits[:, -1, :]\n next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)\n return next_token\n\n def prefill(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Prefill phase: Process the entire input prompt at once.\n Returns the next token.\n\n Similar to: https://github.com/pytorch-labs/gpt-fast/blob/main/generate.py#L68-L82\n \"\"\"\n return self.get_next_token(input_ids, past_key_values)\n\n def decode_one_token(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Decode phase: Generate a single token given the current sequence.\n Returns the next token.\n \"\"\"\n # input_pos: [B, 1] One token at the time\n assert input_ids.shape[-1] == 1, f\"Expected shape (B, 1), but found {input_ids.shape}\"\n return self.get_next_token(input_ids, past_key_values)\n\n # TODO: Running `torchrun --nproc-per-node 2 thunder/benchmarks/benchmark_inference.py --input-length 32 --output-length 32 --mode eager --num-iterations 10`\n # with inference mode results in\n # [rank1]: File \"/opt/pytorch/lightning-thunder/thunder/benchmarks/layers_for_inference_benchmark.py\", line 358, in grouped_mm\n # [rank1]: group_outs.append(group_a @ b[idx])\n # [rank1]: ~^^^^^\n # [rank1]: RuntimeError: Cannot set version_counter for inference tensor\n # @torch.inference_mode()\n def generate(\n self, input_ids: torch.Tensor, max_new_tokens: int, past_key_values: HybridChunkedCache\n ) -> dict[str, Any]:","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.decode_one_token","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.decode_one_token#L541-L548","kind":"function","name":"decode_one_token","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":541,"end_line":548,"context_start_line":521,"context_end_line":568,"code":"\n def get_next_token(\n self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache | StaticCache\n ) -> torch.Tensor:\n with torch.no_grad():\n outputs = self.model(input_ids, past_key_values=past_key_values, use_cache=True)\n logits = outputs.logits # [B, seq_len, vocab_size]\n next_token_logits = logits[:, -1, :]\n next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)\n return next_token\n\n def prefill(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Prefill phase: Process the entire input prompt at once.\n Returns the next token.\n\n Similar to: https://github.com/pytorch-labs/gpt-fast/blob/main/generate.py#L68-L82\n \"\"\"\n return self.get_next_token(input_ids, past_key_values)\n\n def decode_one_token(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Decode phase: Generate a single token given the current sequence.\n Returns the next token.\n \"\"\"\n # input_pos: [B, 1] One token at the time\n assert input_ids.shape[-1] == 1, f\"Expected shape (B, 1), but found {input_ids.shape}\"\n return self.get_next_token(input_ids, past_key_values)\n\n # TODO: Running `torchrun --nproc-per-node 2 thunder/benchmarks/benchmark_inference.py --input-length 32 --output-length 32 --mode eager --num-iterations 10`\n # with inference mode results in\n # [rank1]: File \"/opt/pytorch/lightning-thunder/thunder/benchmarks/layers_for_inference_benchmark.py\", line 358, in grouped_mm\n # [rank1]: group_outs.append(group_a @ b[idx])\n # [rank1]: ~^^^^^\n # [rank1]: RuntimeError: Cannot set version_counter for inference tensor\n # @torch.inference_mode()\n def generate(\n self, input_ids: torch.Tensor, max_new_tokens: int, past_key_values: HybridChunkedCache\n ) -> dict[str, Any]:\n \"\"\"\n Generate tokens using separate prefill and decode phases.\n Returns detailed metrics for both phases.\n \"\"\"\n # Prefill phase - process the entire prompt\n with timer() as prefill_timer:\n torch.cuda.nvtx.range_push(\"prefill\")\n first_token = self.prefill(input_ids, past_key_values)\n torch.cuda.nvtx.range_pop()","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.generate","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.generate#L557-L588","kind":"function","name":"generate","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":557,"end_line":588,"context_start_line":537,"context_end_line":608,"code":" Similar to: https://github.com/pytorch-labs/gpt-fast/blob/main/generate.py#L68-L82\n \"\"\"\n return self.get_next_token(input_ids, past_key_values)\n\n def decode_one_token(self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache) -> torch.Tensor:\n \"\"\"\n Decode phase: Generate a single token given the current sequence.\n Returns the next token.\n \"\"\"\n # input_pos: [B, 1] One token at the time\n assert input_ids.shape[-1] == 1, f\"Expected shape (B, 1), but found {input_ids.shape}\"\n return self.get_next_token(input_ids, past_key_values)\n\n # TODO: Running `torchrun --nproc-per-node 2 thunder/benchmarks/benchmark_inference.py --input-length 32 --output-length 32 --mode eager --num-iterations 10`\n # with inference mode results in\n # [rank1]: File \"/opt/pytorch/lightning-thunder/thunder/benchmarks/layers_for_inference_benchmark.py\", line 358, in grouped_mm\n # [rank1]: group_outs.append(group_a @ b[idx])\n # [rank1]: ~^^^^^\n # [rank1]: RuntimeError: Cannot set version_counter for inference tensor\n # @torch.inference_mode()\n def generate(\n self, input_ids: torch.Tensor, max_new_tokens: int, past_key_values: HybridChunkedCache\n ) -> dict[str, Any]:\n \"\"\"\n Generate tokens using separate prefill and decode phases.\n Returns detailed metrics for both phases.\n \"\"\"\n # Prefill phase - process the entire prompt\n with timer() as prefill_timer:\n torch.cuda.nvtx.range_push(\"prefill\")\n first_token = self.prefill(input_ids, past_key_values)\n torch.cuda.nvtx.range_pop()\n prefill_time = prefill_timer()\n generated_tokens = [first_token]\n\n # Decode phase - generate remaining tokens one by one\n next_token = first_token\n with timer() as decode_timer:\n for idx in range(max_new_tokens - 1):\n torch.cuda.nvtx.range_push(\"decode:\" + str(idx))\n next_token = self.decode_one_token(next_token, past_key_values)\n generated_tokens.append(next_token)\n torch.cuda.nvtx.range_pop()\n\n total_decode_time = decode_timer()\n\n return {\n \"prefill_time_ms\": prefill_time,\n \"decode_time_ms\": total_decode_time,\n \"generated_tokens\": generated_tokens,\n \"total_tokens\": max_new_tokens,\n }\n\n def measure_inference_step(\n self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache, max_new_tokens: int\n ) -> dict[str, float]:\n \"\"\"Measure a single inference step with detailed timing using separate prefill/decode\"\"\"\n # Generate tokens with separate prefill/decode tracking\n generation_result = self.generate(input_ids, max_new_tokens, past_key_values)\n total_time = generation_result[\"prefill_time_ms\"] + generation_result[\"decode_time_ms\"]\n\n # Extract metrics\n ttft = generation_result[\"prefill_time_ms\"] # Time to first token is the prefill time\n total_decode_time = generation_result[\"decode_time_ms\"]\n avg_tbot = total_decode_time / (max_new_tokens - 1) if max_new_tokens > 1 else 0\n\n # Calculate throughput\n total_tokens = self.config.output_length * self.config.batch_size\n throughput = (total_tokens / total_time) * 1000 # tokens/second\n\n # Calculate separate prefill and decode throughput\n prefill_tokens = self.config.input_length * self.config.batch_size","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.measure_inference_step","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.measure_inference_step#L590-L623","kind":"function","name":"measure_inference_step","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":590,"end_line":623,"context_start_line":570,"context_end_line":643,"code":" generated_tokens = [first_token]\n\n # Decode phase - generate remaining tokens one by one\n next_token = first_token\n with timer() as decode_timer:\n for idx in range(max_new_tokens - 1):\n torch.cuda.nvtx.range_push(\"decode:\" + str(idx))\n next_token = self.decode_one_token(next_token, past_key_values)\n generated_tokens.append(next_token)\n torch.cuda.nvtx.range_pop()\n\n total_decode_time = decode_timer()\n\n return {\n \"prefill_time_ms\": prefill_time,\n \"decode_time_ms\": total_decode_time,\n \"generated_tokens\": generated_tokens,\n \"total_tokens\": max_new_tokens,\n }\n\n def measure_inference_step(\n self, input_ids: torch.Tensor, past_key_values: HybridChunkedCache, max_new_tokens: int\n ) -> dict[str, float]:\n \"\"\"Measure a single inference step with detailed timing using separate prefill/decode\"\"\"\n # Generate tokens with separate prefill/decode tracking\n generation_result = self.generate(input_ids, max_new_tokens, past_key_values)\n total_time = generation_result[\"prefill_time_ms\"] + generation_result[\"decode_time_ms\"]\n\n # Extract metrics\n ttft = generation_result[\"prefill_time_ms\"] # Time to first token is the prefill time\n total_decode_time = generation_result[\"decode_time_ms\"]\n avg_tbot = total_decode_time / (max_new_tokens - 1) if max_new_tokens > 1 else 0\n\n # Calculate throughput\n total_tokens = self.config.output_length * self.config.batch_size\n throughput = (total_tokens / total_time) * 1000 # tokens/second\n\n # Calculate separate prefill and decode throughput\n prefill_tokens = self.config.input_length * self.config.batch_size\n prefill_throughput = (prefill_tokens / generation_result[\"prefill_time_ms\"]) * 1000\n\n decode_tokens = (self.config.output_length - 1) * self.config.batch_size\n decode_throughput = (decode_tokens / total_decode_time) * 1000 if total_decode_time > 0 else 0\n\n return {\n \"ttft\": ttft,\n \"avg_tbot\": avg_tbot,\n \"total_time\": total_time,\n \"throughput\": throughput,\n \"prefill_throughput\": prefill_throughput,\n \"decode_throughput\": decode_throughput,\n \"prefill_time\": generation_result[\"prefill_time_ms\"],\n \"total_decode_time\": total_decode_time,\n }\n\n def run_benchmark(self) -> InferenceMetrics:\n \"\"\"Run the full benchmark and collect metrics\"\"\"\n print(f\"Running inference benchmark for {self.config.model_name}\")\n\n print(f\"Batch size: {self.config.batch_size}\")\n print(f\"Input length: {self.config.input_length}\")\n print(f\"Output length: {self.config.output_length}\")\n print(f\"Mode: {self.config.mode}\")\n\n print(f\"\\nWarming up with {self.config.warmup_iterations} iterations...\")\n input_ids, past_key_values = self.generate_batch()\n\n for idx in tqdm(range(self.config.warmup_iterations), disable=LOCAL_RANK != 0):\n past_key_values.reset()\n # Use output_length to warm up sufficiently. Otherwise, Thunder's\n # first-run latency is terribly slow due to lack of dynamic shape\n # support.\n torch.cuda.nvtx.range_push(\"warmup:\" + str(idx))\n _ = self.measure_inference_step(input_ids, past_key_values, self.config.output_length)","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.run_benchmark","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.run_benchmark#L625-L690","kind":"function","name":"run_benchmark","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":625,"end_line":690,"context_start_line":605,"context_end_line":710,"code":" throughput = (total_tokens / total_time) * 1000 # tokens/second\n\n # Calculate separate prefill and decode throughput\n prefill_tokens = self.config.input_length * self.config.batch_size\n prefill_throughput = (prefill_tokens / generation_result[\"prefill_time_ms\"]) * 1000\n\n decode_tokens = (self.config.output_length - 1) * self.config.batch_size\n decode_throughput = (decode_tokens / total_decode_time) * 1000 if total_decode_time > 0 else 0\n\n return {\n \"ttft\": ttft,\n \"avg_tbot\": avg_tbot,\n \"total_time\": total_time,\n \"throughput\": throughput,\n \"prefill_throughput\": prefill_throughput,\n \"decode_throughput\": decode_throughput,\n \"prefill_time\": generation_result[\"prefill_time_ms\"],\n \"total_decode_time\": total_decode_time,\n }\n\n def run_benchmark(self) -> InferenceMetrics:\n \"\"\"Run the full benchmark and collect metrics\"\"\"\n print(f\"Running inference benchmark for {self.config.model_name}\")\n\n print(f\"Batch size: {self.config.batch_size}\")\n print(f\"Input length: {self.config.input_length}\")\n print(f\"Output length: {self.config.output_length}\")\n print(f\"Mode: {self.config.mode}\")\n\n print(f\"\\nWarming up with {self.config.warmup_iterations} iterations...\")\n input_ids, past_key_values = self.generate_batch()\n\n for idx in tqdm(range(self.config.warmup_iterations), disable=LOCAL_RANK != 0):\n past_key_values.reset()\n # Use output_length to warm up sufficiently. Otherwise, Thunder's\n # first-run latency is terribly slow due to lack of dynamic shape\n # support.\n torch.cuda.nvtx.range_push(\"warmup:\" + str(idx))\n _ = self.measure_inference_step(input_ids, past_key_values, self.config.output_length)\n torch.cuda.nvtx.range_pop()\n\n print(f\"\\nRunning {self.config.num_iterations} benchmark iterations...\")\n all_metrics = []\n\n if torch.cuda.is_available():\n torch.cuda.reset_peak_memory_stats()\n\n for idx in tqdm(range(self.config.num_iterations), disable=LOCAL_RANK != 0):\n past_key_values.reset()\n\n is_under_nsys = bool(os.environ.get(\"NSYS_PROFILING_SESSION_ID\"))\n # Wrap each non-warmup iteration with cudaProfilerStart() and\n # cudaProfilerStop(). This allows the user to run\n # ```shell\n # nsys profile --capture-range=cudaProfilerApi --capture-range-end=repeat: ...\n # ```\n # to record only the non-warmup iterations.\n # Note when debug_moe is on, we'll defer the flag inside the moe wrapper.\n self.profiler_toggle = is_under_nsys\n if is_under_nsys and not self.config.debug_moe:\n torch.cuda.cudart().cudaProfilerStart()\n torch.cuda.nvtx.range_push(\"step:\" + str(idx))\n iter_metrics = self.measure_inference_step(input_ids, past_key_values, self.config.output_length)\n torch.cuda.nvtx.range_pop()\n if is_under_nsys and not self.config.debug_moe:\n torch.cuda.cudart().cudaProfilerStop()\n\n all_metrics.append(iter_metrics)\n\n # Track metrics\n self.metrics.iteration_times.append(iter_metrics[\"total_time\"])\n self.metrics.ttft_times.append(iter_metrics[\"ttft\"])\n self.metrics.prefill_times.append(iter_metrics[\"prefill_time\"])\n self.metrics.decode_times.append(iter_metrics[\"total_decode_time\"])\n\n self._calculate_aggregate_metrics(all_metrics)\n\n if torch.cuda.is_available():\n self.metrics.memory_used_gb = torch.cuda.memory_allocated() / 1e9\n self.metrics.peak_memory_gb = torch.cuda.max_memory_allocated() / 1e9\n\n if self.config.fx_report_folder is not None and self.config.mode == \"thunder\":\n self.model._backend.save_reproducer_to_folder(self.config.fx_report_folder)\n return\n\n return self.metrics\n\n def _calculate_aggregate_metrics(self, all_metrics: list[dict[str, Any]]):\n \"\"\"Calculate aggregate metrics from individual iterations\"\"\"\n # Average throughput\n throughputs = [m[\"throughput\"] for m in all_metrics]\n self.metrics.throughput_tokens_per_sec = statistics.mean(throughputs)\n\n # Average latency\n total_times = [m[\"total_time\"] for m in all_metrics]\n total_tokens = self.config.output_length * self.config.batch_size\n self.metrics.latency_ms_per_token = statistics.mean(total_times) / total_tokens\n\n # TTFT\n ttfts = [m[\"ttft\"] for m in all_metrics]\n self.metrics.time_to_first_token_ms = statistics.mean(ttfts)\n\n # TBOT\n self.metrics.time_between_output_tokens_ms = statistics.mean([m[\"avg_tbot\"] for m in all_metrics])\n\n # Total time","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference._calculate_aggregate_metrics","uri":"program://Fuser/function/benchmarks.python.benchmark_inference._calculate_aggregate_metrics#L692-L723","kind":"function","name":"_calculate_aggregate_metrics","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":692,"end_line":723,"context_start_line":672,"context_end_line":743,"code":" all_metrics.append(iter_metrics)\n\n # Track metrics\n self.metrics.iteration_times.append(iter_metrics[\"total_time\"])\n self.metrics.ttft_times.append(iter_metrics[\"ttft\"])\n self.metrics.prefill_times.append(iter_metrics[\"prefill_time\"])\n self.metrics.decode_times.append(iter_metrics[\"total_decode_time\"])\n\n self._calculate_aggregate_metrics(all_metrics)\n\n if torch.cuda.is_available():\n self.metrics.memory_used_gb = torch.cuda.memory_allocated() / 1e9\n self.metrics.peak_memory_gb = torch.cuda.max_memory_allocated() / 1e9\n\n if self.config.fx_report_folder is not None and self.config.mode == \"thunder\":\n self.model._backend.save_reproducer_to_folder(self.config.fx_report_folder)\n return\n\n return self.metrics\n\n def _calculate_aggregate_metrics(self, all_metrics: list[dict[str, Any]]):\n \"\"\"Calculate aggregate metrics from individual iterations\"\"\"\n # Average throughput\n throughputs = [m[\"throughput\"] for m in all_metrics]\n self.metrics.throughput_tokens_per_sec = statistics.mean(throughputs)\n\n # Average latency\n total_times = [m[\"total_time\"] for m in all_metrics]\n total_tokens = self.config.output_length * self.config.batch_size\n self.metrics.latency_ms_per_token = statistics.mean(total_times) / total_tokens\n\n # TTFT\n ttfts = [m[\"ttft\"] for m in all_metrics]\n self.metrics.time_to_first_token_ms = statistics.mean(ttfts)\n\n # TBOT\n self.metrics.time_between_output_tokens_ms = statistics.mean([m[\"avg_tbot\"] for m in all_metrics])\n\n # Total time\n self.metrics.total_time_ms = statistics.mean(total_times)\n\n # Prefill metrics\n prefill_throughputs = [m[\"prefill_throughput\"] for m in all_metrics]\n self.metrics.prefill_throughput_tokens_per_sec = statistics.mean(prefill_throughputs)\n prefill_times = [m[\"prefill_time\"] for m in all_metrics]\n self.metrics.prefill_time_ms = statistics.mean(prefill_times)\n\n # Decode metrics\n decode_throughputs = [m[\"decode_throughput\"] for m in all_metrics]\n self.metrics.decode_throughput_tokens_per_sec = statistics.mean(decode_throughputs)\n decode_times = [m[\"total_decode_time\"] for m in all_metrics]\n self.metrics.decode_time_ms = statistics.mean(decode_times)\n\n def print_results(self):\n \"\"\"Print benchmark results in a formatted way\"\"\"\n print(\"\\n\" + \"=\" * 60)\n print(f\"BENCHMARK RESULTS - {self.config.model_name} {self.config.mode}\")\n print(\"=\" * 60)\n\n print(\"\\nThroughput Metrics:\")\n print(f\" Overall Throughput: {self.metrics.throughput_tokens_per_sec:.2f} tokens/sec\")\n print(f\" Prefill Throughput: {self.metrics.prefill_throughput_tokens_per_sec:.2f} tokens/sec\")\n print(f\" Decode Throughput: {self.metrics.decode_throughput_tokens_per_sec:.2f} tokens/sec\")\n print(f\" Latency: {self.metrics.latency_ms_per_token:.2f} ms/token\")\n\n print(\"\\nLatency Breakdown:\")\n print(f\" Time to First Token (TTFT): {self.metrics.time_to_first_token_ms:.2f} ms\")\n print(f\" Time Between Output Tokens (TBOT): {self.metrics.time_between_output_tokens_ms:.2f} ms\")\n print(f\" Prefill Time: {self.metrics.prefill_time_ms:.2f} ms\")\n print(f\" Decode Time: {self.metrics.decode_time_ms:.2f} ms\")\n print(f\" Total Generation Time: {self.metrics.total_time_ms:.2f} ms\")\n","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.print_results","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.print_results#L725-L751","kind":"function","name":"print_results","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":725,"end_line":751,"context_start_line":705,"context_end_line":771,"code":" self.metrics.time_to_first_token_ms = statistics.mean(ttfts)\n\n # TBOT\n self.metrics.time_between_output_tokens_ms = statistics.mean([m[\"avg_tbot\"] for m in all_metrics])\n\n # Total time\n self.metrics.total_time_ms = statistics.mean(total_times)\n\n # Prefill metrics\n prefill_throughputs = [m[\"prefill_throughput\"] for m in all_metrics]\n self.metrics.prefill_throughput_tokens_per_sec = statistics.mean(prefill_throughputs)\n prefill_times = [m[\"prefill_time\"] for m in all_metrics]\n self.metrics.prefill_time_ms = statistics.mean(prefill_times)\n\n # Decode metrics\n decode_throughputs = [m[\"decode_throughput\"] for m in all_metrics]\n self.metrics.decode_throughput_tokens_per_sec = statistics.mean(decode_throughputs)\n decode_times = [m[\"total_decode_time\"] for m in all_metrics]\n self.metrics.decode_time_ms = statistics.mean(decode_times)\n\n def print_results(self):\n \"\"\"Print benchmark results in a formatted way\"\"\"\n print(\"\\n\" + \"=\" * 60)\n print(f\"BENCHMARK RESULTS - {self.config.model_name} {self.config.mode}\")\n print(\"=\" * 60)\n\n print(\"\\nThroughput Metrics:\")\n print(f\" Overall Throughput: {self.metrics.throughput_tokens_per_sec:.2f} tokens/sec\")\n print(f\" Prefill Throughput: {self.metrics.prefill_throughput_tokens_per_sec:.2f} tokens/sec\")\n print(f\" Decode Throughput: {self.metrics.decode_throughput_tokens_per_sec:.2f} tokens/sec\")\n print(f\" Latency: {self.metrics.latency_ms_per_token:.2f} ms/token\")\n\n print(\"\\nLatency Breakdown:\")\n print(f\" Time to First Token (TTFT): {self.metrics.time_to_first_token_ms:.2f} ms\")\n print(f\" Time Between Output Tokens (TBOT): {self.metrics.time_between_output_tokens_ms:.2f} ms\")\n print(f\" Prefill Time: {self.metrics.prefill_time_ms:.2f} ms\")\n print(f\" Decode Time: {self.metrics.decode_time_ms:.2f} ms\")\n print(f\" Total Generation Time: {self.metrics.total_time_ms:.2f} ms\")\n\n print(\"\\nMemory Usage:\")\n print(f\" Current Memory: {self.metrics.memory_used_gb:.2f} GB\")\n print(f\" Peak Memory: {self.metrics.peak_memory_gb:.2f} GB\")\n\n if len(self.metrics.iteration_times) > 1:\n print(\"\\nVariance Analysis:\")\n print(f\" Throughput Std Dev: {statistics.stdev(self.metrics.iteration_times):.2f} ms\")\n print(f\" TTFT Std Dev: {statistics.stdev(self.metrics.ttft_times):.2f} ms\")\n\n def save_results(self, filename: str):\n \"\"\"Save results to JSON file\"\"\"\n results = {\n \"config\": self.config.__dict__,\n \"metrics\": {\n \"throughput_tokens_per_sec\": self.metrics.throughput_tokens_per_sec,\n \"prefill_throughput_tokens_per_sec\": self.metrics.prefill_throughput_tokens_per_sec,\n \"decode_throughput_tokens_per_sec\": self.metrics.decode_throughput_tokens_per_sec,\n \"latency_ms_per_token\": self.metrics.latency_ms_per_token,\n \"time_to_first_token_ms\": self.metrics.time_to_first_token_ms,\n \"time_between_output_tokens_ms\": self.metrics.time_between_output_tokens_ms,\n \"prefill_time_ms\": self.metrics.prefill_time_ms,\n \"decode_time_ms\": self.metrics.decode_time_ms,\n \"total_time_ms\": self.metrics.total_time_ms,\n \"memory_used_gb\": self.metrics.memory_used_gb,\n \"peak_memory_gb\": self.metrics.peak_memory_gb,\n },\n \"detailed_metrics\": {\n \"iteration_times\": self.metrics.iteration_times,","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.save_results","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.save_results#L753-L781","kind":"function","name":"save_results","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":753,"end_line":781,"context_start_line":733,"context_end_line":801,"code":" print(f\" Prefill Throughput: {self.metrics.prefill_throughput_tokens_per_sec:.2f} tokens/sec\")\n print(f\" Decode Throughput: {self.metrics.decode_throughput_tokens_per_sec:.2f} tokens/sec\")\n print(f\" Latency: {self.metrics.latency_ms_per_token:.2f} ms/token\")\n\n print(\"\\nLatency Breakdown:\")\n print(f\" Time to First Token (TTFT): {self.metrics.time_to_first_token_ms:.2f} ms\")\n print(f\" Time Between Output Tokens (TBOT): {self.metrics.time_between_output_tokens_ms:.2f} ms\")\n print(f\" Prefill Time: {self.metrics.prefill_time_ms:.2f} ms\")\n print(f\" Decode Time: {self.metrics.decode_time_ms:.2f} ms\")\n print(f\" Total Generation Time: {self.metrics.total_time_ms:.2f} ms\")\n\n print(\"\\nMemory Usage:\")\n print(f\" Current Memory: {self.metrics.memory_used_gb:.2f} GB\")\n print(f\" Peak Memory: {self.metrics.peak_memory_gb:.2f} GB\")\n\n if len(self.metrics.iteration_times) > 1:\n print(\"\\nVariance Analysis:\")\n print(f\" Throughput Std Dev: {statistics.stdev(self.metrics.iteration_times):.2f} ms\")\n print(f\" TTFT Std Dev: {statistics.stdev(self.metrics.ttft_times):.2f} ms\")\n\n def save_results(self, filename: str):\n \"\"\"Save results to JSON file\"\"\"\n results = {\n \"config\": self.config.__dict__,\n \"metrics\": {\n \"throughput_tokens_per_sec\": self.metrics.throughput_tokens_per_sec,\n \"prefill_throughput_tokens_per_sec\": self.metrics.prefill_throughput_tokens_per_sec,\n \"decode_throughput_tokens_per_sec\": self.metrics.decode_throughput_tokens_per_sec,\n \"latency_ms_per_token\": self.metrics.latency_ms_per_token,\n \"time_to_first_token_ms\": self.metrics.time_to_first_token_ms,\n \"time_between_output_tokens_ms\": self.metrics.time_between_output_tokens_ms,\n \"prefill_time_ms\": self.metrics.prefill_time_ms,\n \"decode_time_ms\": self.metrics.decode_time_ms,\n \"total_time_ms\": self.metrics.total_time_ms,\n \"memory_used_gb\": self.metrics.memory_used_gb,\n \"peak_memory_gb\": self.metrics.peak_memory_gb,\n },\n \"detailed_metrics\": {\n \"iteration_times\": self.metrics.iteration_times,\n \"ttft_times\": self.metrics.ttft_times,\n \"prefill_times\": self.metrics.prefill_times,\n \"decode_times\": self.metrics.decode_times,\n },\n }\n\n with open(filename, \"w\") as f:\n json.dump(results, f, indent=2)\n\n print(f\"\\nResults saved to {filename}\")\n\n\nclass CustomFormatter(argparse.RawDescriptionHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):\n pass\n\n\ndef parse_args() -> argparse.Namespace:\n \"\"\"Command line interface for the benchmark\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Thunder Inference Benchmark\",\n formatter_class=CustomFormatter,\n epilog=\"\"\"\nExamples:\n python benchmark_inference.py --input-length 2048 --output-length 512 --model-name meta-llama/Llama-4-Maverick-17B-128E --mode eager\n \"\"\",\n )\n\n parser.add_argument(\n \"--model-name\",\n type=str,","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.compile_wrapper","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.compile_wrapper#L393-L413","kind":"function","name":"compile_wrapper","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":393,"end_line":413,"context_start_line":373,"context_end_line":433,"code":" # Materialize the model on the device (after Llama4MoE replacement and sharding)\n model.to_empty(device=DEVICE)\n assert all(p.device == DEVICE for p in model.parameters())\n\n # Required as thunder doesn't understand inference mode\n # And some prims like `prims._grouped_mm` don't have grad rule defined yet.\n for p in model.parameters():\n p.requires_grad_(False)\n\n assert all(not p.requires_grad for p in model.parameters())\n\n # `thunderfx` seems to hide the access to vocab_size somewhere so\n # store it here before any compiler is applied.\n self.vocab_size = model.vocab_size\n\n if self.config.enable_nvfp4:\n _quantize_llama4(model)\n\n # If debug_moe is on, we'll only compile the moe section, which is much easier to digest.\n if self.config.debug_moe:\n def compile_wrapper(model, jitter):\n class ModelWrapper(torch.nn.Module):\n\n def __init__(self, model, jitter):\n super().__init__()\n self.model = jitter._compile_model(model)\n assert not hasattr(jitter.model, \"_backend\")\n # store a reference to the compiled backend, so we can print the trace later.\n if jitter.config.mode == \"thunder\":\n jitter.model._backend = self.model._backend\n self.jitter = jitter\n\n def forward(self, *args, **kwargs):\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStart()\n out = self.model(*args, **kwargs)\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStop()\n return out\n\n return ModelWrapper(model, jitter)\n\n self.model = model\n # reuse the `replace` function with compilation.\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: compile_wrapper(model, self),\n lambda model, cur_fqn: isinstance(model, Llama4MoE),\n )\n else:\n self.model = self._compile_model(model)\n\n\n @property\n def _thunder_jit_options(self) -> dict[str, Any]:\n # `nv_enable_linear=True` might fail with distributed run\n # ref: https://github.com/NVIDIA/Fuser/issues/4507\n res = {\"transforms\": []}\n if self.config.enable_nv_linear:\n res[\"nv_enable_linear\"] = True\n res[\"nv_enable_matmul\"] = True","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.ModelWrapper","uri":"program://Fuser/class/benchmarks.python.benchmark_inference.ModelWrapper#L394-L411","kind":"class","name":"ModelWrapper","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":394,"end_line":411,"context_start_line":374,"context_end_line":431,"code":" model.to_empty(device=DEVICE)\n assert all(p.device == DEVICE for p in model.parameters())\n\n # Required as thunder doesn't understand inference mode\n # And some prims like `prims._grouped_mm` don't have grad rule defined yet.\n for p in model.parameters():\n p.requires_grad_(False)\n\n assert all(not p.requires_grad for p in model.parameters())\n\n # `thunderfx` seems to hide the access to vocab_size somewhere so\n # store it here before any compiler is applied.\n self.vocab_size = model.vocab_size\n\n if self.config.enable_nvfp4:\n _quantize_llama4(model)\n\n # If debug_moe is on, we'll only compile the moe section, which is much easier to digest.\n if self.config.debug_moe:\n def compile_wrapper(model, jitter):\n class ModelWrapper(torch.nn.Module):\n\n def __init__(self, model, jitter):\n super().__init__()\n self.model = jitter._compile_model(model)\n assert not hasattr(jitter.model, \"_backend\")\n # store a reference to the compiled backend, so we can print the trace later.\n if jitter.config.mode == \"thunder\":\n jitter.model._backend = self.model._backend\n self.jitter = jitter\n\n def forward(self, *args, **kwargs):\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStart()\n out = self.model(*args, **kwargs)\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStop()\n return out\n\n return ModelWrapper(model, jitter)\n\n self.model = model\n # reuse the `replace` function with compilation.\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: compile_wrapper(model, self),\n lambda model, cur_fqn: isinstance(model, Llama4MoE),\n )\n else:\n self.model = self._compile_model(model)\n\n\n @property\n def _thunder_jit_options(self) -> dict[str, Any]:\n # `nv_enable_linear=True` might fail with distributed run\n # ref: https://github.com/NVIDIA/Fuser/issues/4507\n res = {\"transforms\": []}\n if self.config.enable_nv_linear:","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_inference.forward","uri":"program://Fuser/function/benchmarks.python.benchmark_inference.forward#L405-L411","kind":"function","name":"forward","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":405,"end_line":411,"context_start_line":385,"context_end_line":431,"code":" # store it here before any compiler is applied.\n self.vocab_size = model.vocab_size\n\n if self.config.enable_nvfp4:\n _quantize_llama4(model)\n\n # If debug_moe is on, we'll only compile the moe section, which is much easier to digest.\n if self.config.debug_moe:\n def compile_wrapper(model, jitter):\n class ModelWrapper(torch.nn.Module):\n\n def __init__(self, model, jitter):\n super().__init__()\n self.model = jitter._compile_model(model)\n assert not hasattr(jitter.model, \"_backend\")\n # store a reference to the compiled backend, so we can print the trace later.\n if jitter.config.mode == \"thunder\":\n jitter.model._backend = self.model._backend\n self.jitter = jitter\n\n def forward(self, *args, **kwargs):\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStart()\n out = self.model(*args, **kwargs)\n if self.jitter.profiler_toggle:\n torch.cuda.cudart().cudaProfilerStop()\n return out\n\n return ModelWrapper(model, jitter)\n\n self.model = model\n # reuse the `replace` function with compilation.\n _replace_with_custom_fn_if_matches_filter_with_name(\n model,\n lambda model, cur_fqn: compile_wrapper(model, self),\n lambda model, cur_fqn: isinstance(model, Llama4MoE),\n )\n else:\n self.model = self._compile_model(model)\n\n\n @property\n def _thunder_jit_options(self) -> dict[str, Any]:\n # `nv_enable_linear=True` might fail with distributed run\n # ref: https://github.com/NVIDIA/Fuser/issues/4507\n res = {\"transforms\": []}\n if self.config.enable_nv_linear:","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_embedding","uri":"program://Fuser/module/benchmarks.python.test_embedding#L1-L103","kind":"module","name":"benchmarks.python.test_embedding","path":"benchmarks/python/test_embedding.py","language":"python","start_line":1,"end_line":103,"context_start_line":1,"context_end_line":103,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\n\nimport torch\n\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nfrom .global_params import FLOAT_DTYPES\nfrom .torch_ops import embedding\n\n\n# (vocab, hidden) configurations seen in models.\nEMBEDDING_CONFIGS = [\n (152064, 3584), # hf_qwen2\n (32064, 3072), # hf_phi3\n (131072, 5120), # hf_mistral_nemo\n]\n\nSEQ_LENGTHS = [\n 1024,\n 2048,\n 3072,\n 4096,\n 8192,\n 12288,\n 16384,\n 20480,\n 24576,\n 28672,\n 32768,\n]\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"vocab_hidden\", EMBEDDING_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_embedding_fwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n vocab_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n if executor == \"thunder\":\n kwargs[\"nv_enable_embedding\"] = True\n\n indices = torch.randint(0, vocab_hidden[0], (seq_length,), device=\"cuda\")\n embedding_table = torch.randn(\n vocab_hidden, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n\n benchmark_fn = with_executor(executor, embedding, **kwargs)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [indices, embedding_table],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"vocab_hidden\", EMBEDDING_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_embedding_bwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n vocab_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n if executor == \"thunder\":\n kwargs[\"nv_enable_embedding\"] = True\n\n indices = torch.randint(0, vocab_hidden[0], (seq_length,), device=\"cuda\")\n grads = torch.randn((seq_length, vocab_hidden[1]), device=\"cuda\", dtype=dtype)\n embedding_table = torch.randn(\n vocab_hidden, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, embedding, **kwargs)\n fwd_inputs = [indices, embedding_table]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n )","source_hash":"fbfd7b4fa120c45ccab591156c2e35833f004911bb880a7f7b4377362640c058","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_embedding.test_embedding_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_embedding.test_embedding_fwd_baseline_benchmark#L45-L68","kind":"function","name":"test_embedding_fwd_baseline_benchmark","path":"benchmarks/python/test_embedding.py","language":"python","start_line":45,"end_line":68,"context_start_line":25,"context_end_line":88,"code":"\nSEQ_LENGTHS = [\n 1024,\n 2048,\n 3072,\n 4096,\n 8192,\n 12288,\n 16384,\n 20480,\n 24576,\n 28672,\n 32768,\n]\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"vocab_hidden\", EMBEDDING_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_embedding_fwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n vocab_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n if executor == \"thunder\":\n kwargs[\"nv_enable_embedding\"] = True\n\n indices = torch.randint(0, vocab_hidden[0], (seq_length,), device=\"cuda\")\n embedding_table = torch.randn(\n vocab_hidden, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n\n benchmark_fn = with_executor(executor, embedding, **kwargs)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [indices, embedding_table],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"vocab_hidden\", EMBEDDING_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_embedding_bwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n vocab_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n if executor == \"thunder\":\n kwargs[\"nv_enable_embedding\"] = True\n\n indices = torch.randint(0, vocab_hidden[0], (seq_length,), device=\"cuda\")","source_hash":"fbfd7b4fa120c45ccab591156c2e35833f004911bb880a7f7b4377362640c058","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_embedding.test_embedding_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_embedding.test_embedding_bwd_baseline_benchmark#L75-L103","kind":"function","name":"test_embedding_bwd_baseline_benchmark","path":"benchmarks/python/test_embedding.py","language":"python","start_line":75,"end_line":103,"context_start_line":55,"context_end_line":103,"code":" if executor == \"thunder\":\n kwargs[\"nv_enable_embedding\"] = True\n\n indices = torch.randint(0, vocab_hidden[0], (seq_length,), device=\"cuda\")\n embedding_table = torch.randn(\n vocab_hidden, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n\n benchmark_fn = with_executor(executor, embedding, **kwargs)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [indices, embedding_table],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.parametrize(\"vocab_hidden\", EMBEDDING_CONFIGS)\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\ndef test_embedding_bwd_baseline_benchmark(\n benchmark,\n seq_length: int,\n vocab_hidden: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n if executor == \"thunder\":\n kwargs[\"nv_enable_embedding\"] = True\n\n indices = torch.randint(0, vocab_hidden[0], (seq_length,), device=\"cuda\")\n grads = torch.randn((seq_length, vocab_hidden[1]), device=\"cuda\", dtype=dtype)\n embedding_table = torch.randn(\n vocab_hidden, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, embedding, **kwargs)\n fwd_inputs = [indices, embedding_table]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n )","source_hash":"fbfd7b4fa120c45ccab591156c2e35833f004911bb880a7f7b4377362640c058","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_fwd","uri":"program://Fuser/module/benchmarks.python.test_nanogpt_attn_fwd#L1-L163","kind":"module","name":"benchmarks.python.test_nanogpt_attn_fwd","path":"benchmarks/python/test_nanogpt_attn_fwd.py","language":"python","start_line":1,"end_line":163,"context_start_line":1,"context_end_line":163,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import nanogpt_attn\n\n\n# Fusion from nanogpt attention module\n# The nvFuser defintion only includes the non-matmul computation (masked_fill + softmax + dropout)\ndef nanogpt_attn_fwd_fusion(\n fd: FusionDefinition, dtype: DataType, head_size: int, dropout_p: float\n):\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, 1, -1, -1],\n contiguity=[None, None, False, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n\n S2 = fd.define_scalar(1 / head_size**0.5, dtype=DataType.Double)\n T3 = fd.ops.mul(T0, S2)\n S4 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T5 = fd.ops.eq(T1, S4)\n V10 = T0.shape()\n T11 = fd.ops.broadcast_in_dim(T5, shape=V10, broadcast_dims=[0, 1, 2, 3])\n S12 = fd.define_scalar(float(\"-inf\"), dtype=DataType.Double)\n T13 = fd.ops.where(T11, S12, T3)\n T14 = fd.ops.max(T13, dims=[3], keepdim=False, dtype=DataType.Null)\n T20 = fd.ops.broadcast_in_dim(\n T14, shape=[T0.size(0), T0.size(1), T0.size(2), 1], broadcast_dims=[0, 1, 2]\n )\n T26 = fd.ops.broadcast_in_dim(T20, shape=V10, broadcast_dims=[0, 1, 2, 3])\n T27 = fd.ops.sub(T13, T26)\n T28 = fd.ops.exp(T27)\n T29 = fd.ops.sum(T28, dims=[3], keepdim=False, dtype=DataType.Null)\n T35 = fd.ops.broadcast_in_dim(\n T29, shape=[T0.size(0), T0.size(1), T0.size(2), 1], broadcast_dims=[0, 1, 2]\n )\n T41 = fd.ops.broadcast_in_dim(T35, shape=V10, broadcast_dims=[0, 1, 2, 3])\n T42 = fd.ops.reciprocal(T41)\n T43 = fd.ops.mul(T28, T42)\n S44 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S45 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T51 = fd.ops.uniform(S44, S45, shape=V10, dtype=DataType.Float)\n S52 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T53 = fd.ops.lt(T51, S52)\n T55 = fd.ops.mul(T43, T53)\n S56 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T57 = fd.ops.mul(T55, S56)\n\n if dtype in PROMOTE_DTYPES:\n T57 = fd.ops.cast(T57, dtype=dtype)\n T43 = fd.ops.cast(T43, dtype=dtype)\n\n fd.add_output(T57)\n fd.add_output(T53)\n fd.add_output(T43)\n fd.add_output(T11)\n\n\ndef nanogpt_attn_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs (out, dropout_mask, attn, bias_mask) differ from baseline outputs (out).\n\n # Total IO bytes = in_tensor ([bs, nh, seq_len, seq_len], dtype) + bias ([seq_len, seq_len], float) +\n # output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs, nh, seq_len, seq_len], dtype) + dropout_mask ([bs, nh, seq_len, seq_len], bool) + bias_mask ([bs, nh, seq_len, seq_len], bool)\n\n bs, seq_len, nh, n_embd = size\n\n return int(\n bs * nh * seq_len * seq_len * (3 * dtype.itemsize + 2 * torch.bool.itemsize)\n + seq_len * seq_len * torch.float.itemsize\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n dropout_p = 0.2\n inputs = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len\n )\n\n bias_mask = bias[:, :, :seq_len, :seq_len] == 0\n bias_mask = bias_mask.broadcast_to(batch_size, nh, seq_len, seq_len)\n\n if not disable_validation:\n # For validating use a fusion definition with dropout_p=0.0\n with FusionDefinition() as val_fd:\n nanogpt_attn_fwd_fusion(\n val_fd, torch_dtype_to_nvfuser_dtype(dtype), hs, dropout_p=0.0\n )\n attn = inputs / (hs**0.5)\n dropout_mask = torch.ones(\n batch_size, nh, seq_len, seq_len, dtype=torch.bool, device=\"cuda\"\n )\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = torch.nn.functional.softmax(attn, dim=-1)\n out = torch.nn.functional.dropout(attn, p=0.0)\n\n val_fd.validate([inputs, bias], [out, dropout_mask, attn, bias_mask])\n\n if not disable_benchmarking:\n with FusionDefinition() as fd:\n nanogpt_attn_fwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), hs, dropout_p\n )\n run_benchmark(benchmark, fd.execute, [inputs, bias])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len\n )\n\n benchmark_fn = with_executor(executor, nanogpt_attn)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, bias, size, dropout_p],\n iobytes=nanogpt_attn_fwd_iobytes(size, dtype),\n )","source_hash":"470558566fe4a4618b42aa671de8b565da8e0fd83d22c8d950e3c966112e799a","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_fwd.nanogpt_attn_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_nanogpt_attn_fwd.nanogpt_attn_fwd_fusion#L15-L72","kind":"function","name":"nanogpt_attn_fwd_fusion","path":"benchmarks/python/test_nanogpt_attn_fwd.py","language":"python","start_line":15,"end_line":72,"context_start_line":1,"context_end_line":92,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import nanogpt_attn\n\n\n# Fusion from nanogpt attention module\n# The nvFuser defintion only includes the non-matmul computation (masked_fill + softmax + dropout)\ndef nanogpt_attn_fwd_fusion(\n fd: FusionDefinition, dtype: DataType, head_size: int, dropout_p: float\n):\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[1, 1, -1, -1],\n contiguity=[None, None, False, True],\n dtype=DataType.Float,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n\n S2 = fd.define_scalar(1 / head_size**0.5, dtype=DataType.Double)\n T3 = fd.ops.mul(T0, S2)\n S4 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T5 = fd.ops.eq(T1, S4)\n V10 = T0.shape()\n T11 = fd.ops.broadcast_in_dim(T5, shape=V10, broadcast_dims=[0, 1, 2, 3])\n S12 = fd.define_scalar(float(\"-inf\"), dtype=DataType.Double)\n T13 = fd.ops.where(T11, S12, T3)\n T14 = fd.ops.max(T13, dims=[3], keepdim=False, dtype=DataType.Null)\n T20 = fd.ops.broadcast_in_dim(\n T14, shape=[T0.size(0), T0.size(1), T0.size(2), 1], broadcast_dims=[0, 1, 2]\n )\n T26 = fd.ops.broadcast_in_dim(T20, shape=V10, broadcast_dims=[0, 1, 2, 3])\n T27 = fd.ops.sub(T13, T26)\n T28 = fd.ops.exp(T27)\n T29 = fd.ops.sum(T28, dims=[3], keepdim=False, dtype=DataType.Null)\n T35 = fd.ops.broadcast_in_dim(\n T29, shape=[T0.size(0), T0.size(1), T0.size(2), 1], broadcast_dims=[0, 1, 2]\n )\n T41 = fd.ops.broadcast_in_dim(T35, shape=V10, broadcast_dims=[0, 1, 2, 3])\n T42 = fd.ops.reciprocal(T41)\n T43 = fd.ops.mul(T28, T42)\n S44 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S45 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T51 = fd.ops.uniform(S44, S45, shape=V10, dtype=DataType.Float)\n S52 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T53 = fd.ops.lt(T51, S52)\n T55 = fd.ops.mul(T43, T53)\n S56 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T57 = fd.ops.mul(T55, S56)\n\n if dtype in PROMOTE_DTYPES:\n T57 = fd.ops.cast(T57, dtype=dtype)\n T43 = fd.ops.cast(T43, dtype=dtype)\n\n fd.add_output(T57)\n fd.add_output(T53)\n fd.add_output(T43)\n fd.add_output(T11)\n\n\ndef nanogpt_attn_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs (out, dropout_mask, attn, bias_mask) differ from baseline outputs (out).\n\n # Total IO bytes = in_tensor ([bs, nh, seq_len, seq_len], dtype) + bias ([seq_len, seq_len], float) +\n # output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs, nh, seq_len, seq_len], dtype) + dropout_mask ([bs, nh, seq_len, seq_len], bool) + bias_mask ([bs, nh, seq_len, seq_len], bool)\n\n bs, seq_len, nh, n_embd = size\n\n return int(\n bs * nh * seq_len * seq_len * (3 * dtype.itemsize + 2 * torch.bool.itemsize)\n + seq_len * seq_len * torch.float.itemsize\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_fwd_nvf_benchmark(","source_hash":"470558566fe4a4618b42aa671de8b565da8e0fd83d22c8d950e3c966112e799a","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_fwd.nanogpt_attn_fwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_nanogpt_attn_fwd.nanogpt_attn_fwd_iobytes#L75-L86","kind":"function","name":"nanogpt_attn_fwd_iobytes","path":"benchmarks/python/test_nanogpt_attn_fwd.py","language":"python","start_line":75,"end_line":86,"context_start_line":55,"context_end_line":106,"code":" T43 = fd.ops.mul(T28, T42)\n S44 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S45 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T51 = fd.ops.uniform(S44, S45, shape=V10, dtype=DataType.Float)\n S52 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T53 = fd.ops.lt(T51, S52)\n T55 = fd.ops.mul(T43, T53)\n S56 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T57 = fd.ops.mul(T55, S56)\n\n if dtype in PROMOTE_DTYPES:\n T57 = fd.ops.cast(T57, dtype=dtype)\n T43 = fd.ops.cast(T43, dtype=dtype)\n\n fd.add_output(T57)\n fd.add_output(T53)\n fd.add_output(T43)\n fd.add_output(T11)\n\n\ndef nanogpt_attn_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs (out, dropout_mask, attn, bias_mask) differ from baseline outputs (out).\n\n # Total IO bytes = in_tensor ([bs, nh, seq_len, seq_len], dtype) + bias ([seq_len, seq_len], float) +\n # output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs, nh, seq_len, seq_len], dtype) + dropout_mask ([bs, nh, seq_len, seq_len], bool) + bias_mask ([bs, nh, seq_len, seq_len], bool)\n\n bs, seq_len, nh, n_embd = size\n\n return int(\n bs * nh * seq_len * seq_len * (3 * dtype.itemsize + 2 * torch.bool.itemsize)\n + seq_len * seq_len * torch.float.itemsize\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n dropout_p = 0.2\n inputs = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len\n )\n","source_hash":"470558566fe4a4618b42aa671de8b565da8e0fd83d22c8d950e3c966112e799a","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_fwd.test_nanogpt_attn_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_nanogpt_attn_fwd.test_nanogpt_attn_fwd_nvf_benchmark#L92-L131","kind":"function","name":"test_nanogpt_attn_fwd_nvf_benchmark","path":"benchmarks/python/test_nanogpt_attn_fwd.py","language":"python","start_line":92,"end_line":131,"context_start_line":72,"context_end_line":151,"code":" fd.add_output(T11)\n\n\ndef nanogpt_attn_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs (out, dropout_mask, attn, bias_mask) differ from baseline outputs (out).\n\n # Total IO bytes = in_tensor ([bs, nh, seq_len, seq_len], dtype) + bias ([seq_len, seq_len], float) +\n # output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs, nh, seq_len, seq_len], dtype) + dropout_mask ([bs, nh, seq_len, seq_len], bool) + bias_mask ([bs, nh, seq_len, seq_len], bool)\n\n bs, seq_len, nh, n_embd = size\n\n return int(\n bs * nh * seq_len * seq_len * (3 * dtype.itemsize + 2 * torch.bool.itemsize)\n + seq_len * seq_len * torch.float.itemsize\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n dropout_p = 0.2\n inputs = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len\n )\n\n bias_mask = bias[:, :, :seq_len, :seq_len] == 0\n bias_mask = bias_mask.broadcast_to(batch_size, nh, seq_len, seq_len)\n\n if not disable_validation:\n # For validating use a fusion definition with dropout_p=0.0\n with FusionDefinition() as val_fd:\n nanogpt_attn_fwd_fusion(\n val_fd, torch_dtype_to_nvfuser_dtype(dtype), hs, dropout_p=0.0\n )\n attn = inputs / (hs**0.5)\n dropout_mask = torch.ones(\n batch_size, nh, seq_len, seq_len, dtype=torch.bool, device=\"cuda\"\n )\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = torch.nn.functional.softmax(attn, dim=-1)\n out = torch.nn.functional.dropout(attn, p=0.0)\n\n val_fd.validate([inputs, bias], [out, dropout_mask, attn, bias_mask])\n\n if not disable_benchmarking:\n with FusionDefinition() as fd:\n nanogpt_attn_fwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), hs, dropout_p\n )\n run_benchmark(benchmark, fd.execute, [inputs, bias])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(","source_hash":"470558566fe4a4618b42aa671de8b565da8e0fd83d22c8d950e3c966112e799a","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_fwd.test_nanogpt_attn_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_nanogpt_attn_fwd.test_nanogpt_attn_fwd_baseline_benchmark#L138-L163","kind":"function","name":"test_nanogpt_attn_fwd_baseline_benchmark","path":"benchmarks/python/test_nanogpt_attn_fwd.py","language":"python","start_line":138,"end_line":163,"context_start_line":118,"context_end_line":163,"code":" batch_size, nh, seq_len, seq_len, dtype=torch.bool, device=\"cuda\"\n )\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = torch.nn.functional.softmax(attn, dim=-1)\n out = torch.nn.functional.dropout(attn, p=0.0)\n\n val_fd.validate([inputs, bias], [out, dropout_mask, attn, bias_mask])\n\n if not disable_benchmarking:\n with FusionDefinition() as fd:\n nanogpt_attn_fwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), hs, dropout_p\n )\n run_benchmark(benchmark, fd.execute, [inputs, bias])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len\n )\n\n benchmark_fn = with_executor(executor, nanogpt_attn)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, bias, size, dropout_p],\n iobytes=nanogpt_attn_fwd_iobytes(size, dtype),\n )","source_hash":"470558566fe4a4618b42aa671de8b565da8e0fd83d22c8d950e3c966112e799a","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_fwd","uri":"program://Fuser/module/benchmarks.python.test_huggingface_attn_fwd#L1-L177","kind":"module","name":"benchmarks.python.test_huggingface_attn_fwd","path":"benchmarks/python/test_huggingface_attn_fwd.py","language":"python","start_line":1,"end_line":177,"context_start_line":1,"context_end_line":177,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import huggingface_attn\n\n\n# Fusion from huggingface attention implementation.\n# The nvFuser defintion only includes the non-matmul computation (add + reshape + softmax + dropout)\ndef huggingface_attn_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n dropout_p: float,\n):\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n\n T4 = fd.ops.add(T1, T0)\n\n T10 = fd.ops.reshape(\n T4, new_shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), T0.size(3)]\n )\n T12 = fd.ops.max(T10, dims=[2], keepdim=False, dtype=DataType.Null)\n\n T17 = fd.ops.broadcast_in_dim(\n T12,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), 1],\n broadcast_dims=[0, 1],\n )\n T22 = fd.ops.broadcast_in_dim(\n T17,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), T0.size(3)],\n broadcast_dims=[0, 1, 2],\n )\n T23 = fd.ops.sub(T10, T22)\n T24 = fd.ops.exp(T23)\n T25 = fd.ops.sum(T24, dims=[2], keepdim=False, dtype=DataType.Null)\n\n T30 = fd.ops.broadcast_in_dim(\n T25,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), 1],\n broadcast_dims=[0, 1],\n )\n T35 = fd.ops.broadcast_in_dim(\n T30,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), T0.size(3)],\n broadcast_dims=[0, 1, 2],\n )\n\n T36 = fd.ops.reciprocal(T35)\n T37 = fd.ops.mul(T24, T36)\n\n S39 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S40 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T45 = fd.ops.uniform(\n S39,\n S40,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), T0.size(3)],\n dtype=DataType.Float,\n )\n S46 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T47 = fd.ops.lt(T45, S46)\n\n T48 = fd.ops.cast(T47, dtype=DataType.Float)\n T49 = fd.ops.mul(T37, T48)\n S50 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T51 = fd.ops.mul(T49, S50)\n\n if dtype in PROMOTE_DTYPES:\n T37 = fd.ops.cast(T37, dtype=dtype)\n T51 = fd.ops.cast(T51, dtype=dtype)\n\n fd.add_output(T51)\n fd.add_output(T37)\n fd.add_output(T47)\n\n\ndef huggingface_attn_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs (output, attn, dropout_mask) differ from baseline outputs (output).\n\n # Total IO bytes = attention_mask ([bs, nh, seq_len, seq_len], dtype) + in_tensor ([bs, nh, seq_len, seq_len], dtype) +\n # output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs * nh, seq_len, seq_len], dtype) + dropout_mask ([bs * nh, seq_len, seq_len], bool)\n\n bs, seq_len, nh, n_embd = size\n return int(bs * nh * seq_len * seq_len * (dtype.itemsize * 4 + torch.bool.itemsize))\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n attention_mask = torch.zeros(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype\n )\n\n if not disable_validation:\n # For validating use a fusion definition with dropout_p=0.0\n with FusionDefinition() as val_fd:\n huggingface_attn_fwd_fusion(\n val_fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p=0.0\n )\n\n dropout_mask = torch.ones(\n batch_size * nh, seq_len, seq_len, dtype=torch.bool, device=\"cuda\"\n )\n attn = (inputs + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = torch.nn.functional.softmax(attn, dim=-1)\n out = torch.nn.functional.dropout(attn, p=0.0)\n val_fd.validate([attention_mask, inputs], [out, attn, dropout_mask])\n\n if not disable_benchmarking:\n with FusionDefinition() as fd:\n huggingface_attn_fwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p\n )\n run_benchmark(benchmark, fd.execute, [attention_mask, inputs])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n attention_mask = torch.zeros(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype\n )\n\n benchmark_fn = with_executor(executor, huggingface_attn)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, attention_mask, size, dropout_p],\n iobytes=huggingface_attn_fwd_iobytes(size, dtype),\n )","source_hash":"0d01be5f53aac64f021291ead4360f3bdf6168c867851746817444639c36284d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_fwd.huggingface_attn_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_huggingface_attn_fwd.huggingface_attn_fwd_fusion#L15-L94","kind":"function","name":"huggingface_attn_fwd_fusion","path":"benchmarks/python/test_huggingface_attn_fwd.py","language":"python","start_line":15,"end_line":94,"context_start_line":1,"context_end_line":114,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import huggingface_attn\n\n\n# Fusion from huggingface attention implementation.\n# The nvFuser defintion only includes the non-matmul computation (add + reshape + softmax + dropout)\ndef huggingface_attn_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n dropout_p: float,\n):\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n\n T4 = fd.ops.add(T1, T0)\n\n T10 = fd.ops.reshape(\n T4, new_shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), T0.size(3)]\n )\n T12 = fd.ops.max(T10, dims=[2], keepdim=False, dtype=DataType.Null)\n\n T17 = fd.ops.broadcast_in_dim(\n T12,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), 1],\n broadcast_dims=[0, 1],\n )\n T22 = fd.ops.broadcast_in_dim(\n T17,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), T0.size(3)],\n broadcast_dims=[0, 1, 2],\n )\n T23 = fd.ops.sub(T10, T22)\n T24 = fd.ops.exp(T23)\n T25 = fd.ops.sum(T24, dims=[2], keepdim=False, dtype=DataType.Null)\n\n T30 = fd.ops.broadcast_in_dim(\n T25,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), 1],\n broadcast_dims=[0, 1],\n )\n T35 = fd.ops.broadcast_in_dim(\n T30,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), T0.size(3)],\n broadcast_dims=[0, 1, 2],\n )\n\n T36 = fd.ops.reciprocal(T35)\n T37 = fd.ops.mul(T24, T36)\n\n S39 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S40 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T45 = fd.ops.uniform(\n S39,\n S40,\n shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), T0.size(3)],\n dtype=DataType.Float,\n )\n S46 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T47 = fd.ops.lt(T45, S46)\n\n T48 = fd.ops.cast(T47, dtype=DataType.Float)\n T49 = fd.ops.mul(T37, T48)\n S50 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T51 = fd.ops.mul(T49, S50)\n\n if dtype in PROMOTE_DTYPES:\n T37 = fd.ops.cast(T37, dtype=dtype)\n T51 = fd.ops.cast(T51, dtype=dtype)\n\n fd.add_output(T51)\n fd.add_output(T37)\n fd.add_output(T47)\n\n\ndef huggingface_attn_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs (output, attn, dropout_mask) differ from baseline outputs (output).\n\n # Total IO bytes = attention_mask ([bs, nh, seq_len, seq_len], dtype) + in_tensor ([bs, nh, seq_len, seq_len], dtype) +\n # output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs * nh, seq_len, seq_len], dtype) + dropout_mask ([bs * nh, seq_len, seq_len], bool)\n\n bs, seq_len, nh, n_embd = size\n return int(bs * nh * seq_len * seq_len * (dtype.itemsize * 4 + torch.bool.itemsize))\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,","source_hash":"0d01be5f53aac64f021291ead4360f3bdf6168c867851746817444639c36284d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_fwd.huggingface_attn_fwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_huggingface_attn_fwd.huggingface_attn_fwd_iobytes#L97-L104","kind":"function","name":"huggingface_attn_fwd_iobytes","path":"benchmarks/python/test_huggingface_attn_fwd.py","language":"python","start_line":97,"end_line":104,"context_start_line":77,"context_end_line":124,"code":" shape=[fd.ops.mul(T0.size(0), T0.size(1)), T0.size(2), T0.size(3)],\n dtype=DataType.Float,\n )\n S46 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T47 = fd.ops.lt(T45, S46)\n\n T48 = fd.ops.cast(T47, dtype=DataType.Float)\n T49 = fd.ops.mul(T37, T48)\n S50 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T51 = fd.ops.mul(T49, S50)\n\n if dtype in PROMOTE_DTYPES:\n T37 = fd.ops.cast(T37, dtype=dtype)\n T51 = fd.ops.cast(T51, dtype=dtype)\n\n fd.add_output(T51)\n fd.add_output(T37)\n fd.add_output(T47)\n\n\ndef huggingface_attn_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs (output, attn, dropout_mask) differ from baseline outputs (output).\n\n # Total IO bytes = attention_mask ([bs, nh, seq_len, seq_len], dtype) + in_tensor ([bs, nh, seq_len, seq_len], dtype) +\n # output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs * nh, seq_len, seq_len], dtype) + dropout_mask ([bs * nh, seq_len, seq_len], bool)\n\n bs, seq_len, nh, n_embd = size\n return int(bs * nh * seq_len * seq_len * (dtype.itemsize * 4 + torch.bool.itemsize))\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n attention_mask = torch.zeros(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype\n )\n","source_hash":"0d01be5f53aac64f021291ead4360f3bdf6168c867851746817444639c36284d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_fwd.test_huggingface_attn_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_huggingface_attn_fwd.test_huggingface_attn_fwd_nvf_benchmark#L110-L145","kind":"function","name":"test_huggingface_attn_fwd_nvf_benchmark","path":"benchmarks/python/test_huggingface_attn_fwd.py","language":"python","start_line":110,"end_line":145,"context_start_line":90,"context_end_line":165,"code":" T51 = fd.ops.cast(T51, dtype=dtype)\n\n fd.add_output(T51)\n fd.add_output(T37)\n fd.add_output(T47)\n\n\ndef huggingface_attn_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs (output, attn, dropout_mask) differ from baseline outputs (output).\n\n # Total IO bytes = attention_mask ([bs, nh, seq_len, seq_len], dtype) + in_tensor ([bs, nh, seq_len, seq_len], dtype) +\n # output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs * nh, seq_len, seq_len], dtype) + dropout_mask ([bs * nh, seq_len, seq_len], bool)\n\n bs, seq_len, nh, n_embd = size\n return int(bs * nh * seq_len * seq_len * (dtype.itemsize * 4 + torch.bool.itemsize))\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n attention_mask = torch.zeros(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype\n )\n\n if not disable_validation:\n # For validating use a fusion definition with dropout_p=0.0\n with FusionDefinition() as val_fd:\n huggingface_attn_fwd_fusion(\n val_fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p=0.0\n )\n\n dropout_mask = torch.ones(\n batch_size * nh, seq_len, seq_len, dtype=torch.bool, device=\"cuda\"\n )\n attn = (inputs + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = torch.nn.functional.softmax(attn, dim=-1)\n out = torch.nn.functional.dropout(attn, p=0.0)\n val_fd.validate([attention_mask, inputs], [out, attn, dropout_mask])\n\n if not disable_benchmarking:\n with FusionDefinition() as fd:\n huggingface_attn_fwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p\n )\n run_benchmark(benchmark, fd.execute, [attention_mask, inputs])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n attention_mask = torch.zeros(","source_hash":"0d01be5f53aac64f021291ead4360f3bdf6168c867851746817444639c36284d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_fwd.test_huggingface_attn_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_huggingface_attn_fwd.test_huggingface_attn_fwd_baseline_benchmark#L152-L177","kind":"function","name":"test_huggingface_attn_fwd_baseline_benchmark","path":"benchmarks/python/test_huggingface_attn_fwd.py","language":"python","start_line":152,"end_line":177,"context_start_line":132,"context_end_line":177,"code":" dropout_mask = torch.ones(\n batch_size * nh, seq_len, seq_len, dtype=torch.bool, device=\"cuda\"\n )\n attn = (inputs + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = torch.nn.functional.softmax(attn, dim=-1)\n out = torch.nn.functional.dropout(attn, p=0.0)\n val_fd.validate([attention_mask, inputs], [out, attn, dropout_mask])\n\n if not disable_benchmarking:\n with FusionDefinition() as fd:\n huggingface_attn_fwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p\n )\n run_benchmark(benchmark, fd.execute, [attention_mask, inputs])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n attention_mask = torch.zeros(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype\n )\n\n benchmark_fn = with_executor(executor, huggingface_attn)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, attention_mask, size, dropout_p],\n iobytes=huggingface_attn_fwd_iobytes(size, dtype),\n )","source_hash":"0d01be5f53aac64f021291ead4360f3bdf6168c867851746817444639c36284d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction_epilogue","uri":"program://Fuser/module/benchmarks.python.test_reduction_epilogue#L1-L95","kind":"module","name":"benchmarks.python.test_reduction_epilogue","path":"benchmarks/python/test_reduction_epilogue.py","language":"python","start_line":1,"end_line":95,"context_start_line":1,"context_end_line":95,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n# test the influence of epilogue on the performance of reduction.\n# current reduction scheduler only allows epilogue to be fused with outer reduction without post reduction broadcast.\n# So, in this test, only outer reduction is tested. [reduction_axis] is kept to allow the extension to inner reduction.\n\n\ndef reduction_epilogue_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n reduction_axis: int,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.sum(T0, dims=[reduction_axis], keepdim=False)\n T3 = fd.ops.add(T2, T1)\n if dtype in PROMOTE_DTYPES:\n T3 = fd.ops.cast(T3, dtype=dtype)\n fd.add_output(T3)\n\n\ndef reduction_epilogue_fwd_fn(\n inputs: list,\n): # in_tensor, epilogue_tensor, reduction_axis\n return torch.sum(inputs[0], dim=inputs[2]) + inputs[1]\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0])\n@pytest.mark.reduction\ndef test_reduction_epilogue_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n epilogue = torch.randn(size[reduction_axis - 1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n reduction_epilogue_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis\n )\n\n if not disable_validation:\n eager_output = reduction_epilogue_fwd_fn(\n [x.to(torch.double), epilogue.to(torch.double), reduction_axis]\n )\n fd.validate([x, epilogue], [eager_output.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [x, epilogue])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0])\n@pytest.mark.reduction\ndef test_reduction_epilogue_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n epilogue = torch.randn(size[reduction_axis - 1], device=\"cuda\", dtype=dtype)\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n\n benchmark_fn = with_executor(executor, reduction_epilogue_fwd_fn)\n\n run_benchmark(\n benchmark,\n benchmark_fn,\n [x, epilogue, reduction_axis],\n )","source_hash":"c32c13e741d9ce12b3389ad13cb452c3059307cfd179e47c8dfdcaade4eaaa96","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction_epilogue.reduction_epilogue_fusion","uri":"program://Fuser/function/benchmarks.python.test_reduction_epilogue.reduction_epilogue_fusion#L17-L33","kind":"function","name":"reduction_epilogue_fusion","path":"benchmarks/python/test_reduction_epilogue.py","language":"python","start_line":17,"end_line":33,"context_start_line":1,"context_end_line":53,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n# test the influence of epilogue on the performance of reduction.\n# current reduction scheduler only allows epilogue to be fused with outer reduction without post reduction broadcast.\n# So, in this test, only outer reduction is tested. [reduction_axis] is kept to allow the extension to inner reduction.\n\n\ndef reduction_epilogue_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n reduction_axis: int,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.sum(T0, dims=[reduction_axis], keepdim=False)\n T3 = fd.ops.add(T2, T1)\n if dtype in PROMOTE_DTYPES:\n T3 = fd.ops.cast(T3, dtype=dtype)\n fd.add_output(T3)\n\n\ndef reduction_epilogue_fwd_fn(\n inputs: list,\n): # in_tensor, epilogue_tensor, reduction_axis\n return torch.sum(inputs[0], dim=inputs[2]) + inputs[1]\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0])\n@pytest.mark.reduction\ndef test_reduction_epilogue_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):","source_hash":"c32c13e741d9ce12b3389ad13cb452c3059307cfd179e47c8dfdcaade4eaaa96","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction_epilogue.reduction_epilogue_fwd_fn","uri":"program://Fuser/function/benchmarks.python.test_reduction_epilogue.reduction_epilogue_fwd_fn#L36-L39","kind":"function","name":"reduction_epilogue_fwd_fn","path":"benchmarks/python/test_reduction_epilogue.py","language":"python","start_line":36,"end_line":39,"context_start_line":16,"context_end_line":59,"code":"\ndef reduction_epilogue_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n reduction_axis: int,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.sum(T0, dims=[reduction_axis], keepdim=False)\n T3 = fd.ops.add(T2, T1)\n if dtype in PROMOTE_DTYPES:\n T3 = fd.ops.cast(T3, dtype=dtype)\n fd.add_output(T3)\n\n\ndef reduction_epilogue_fwd_fn(\n inputs: list,\n): # in_tensor, epilogue_tensor, reduction_axis\n return torch.sum(inputs[0], dim=inputs[2]) + inputs[1]\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0])\n@pytest.mark.reduction\ndef test_reduction_epilogue_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n epilogue = torch.randn(size[reduction_axis - 1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n reduction_epilogue_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis\n )","source_hash":"c32c13e741d9ce12b3389ad13cb452c3059307cfd179e47c8dfdcaade4eaaa96","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction_epilogue.test_reduction_epilogue_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_reduction_epilogue.test_reduction_epilogue_nvf_benchmark#L46-L68","kind":"function","name":"test_reduction_epilogue_nvf_benchmark","path":"benchmarks/python/test_reduction_epilogue.py","language":"python","start_line":46,"end_line":68,"context_start_line":26,"context_end_line":88,"code":" if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.sum(T0, dims=[reduction_axis], keepdim=False)\n T3 = fd.ops.add(T2, T1)\n if dtype in PROMOTE_DTYPES:\n T3 = fd.ops.cast(T3, dtype=dtype)\n fd.add_output(T3)\n\n\ndef reduction_epilogue_fwd_fn(\n inputs: list,\n): # in_tensor, epilogue_tensor, reduction_axis\n return torch.sum(inputs[0], dim=inputs[2]) + inputs[1]\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0])\n@pytest.mark.reduction\ndef test_reduction_epilogue_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n epilogue = torch.randn(size[reduction_axis - 1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n reduction_epilogue_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis\n )\n\n if not disable_validation:\n eager_output = reduction_epilogue_fwd_fn(\n [x.to(torch.double), epilogue.to(torch.double), reduction_axis]\n )\n fd.validate([x, epilogue], [eager_output.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [x, epilogue])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0])\n@pytest.mark.reduction\ndef test_reduction_epilogue_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n epilogue = torch.randn(size[reduction_axis - 1], device=\"cuda\", dtype=dtype)\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n","source_hash":"c32c13e741d9ce12b3389ad13cb452c3059307cfd179e47c8dfdcaade4eaaa96","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction_epilogue.test_reduction_epilogue_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_reduction_epilogue.test_reduction_epilogue_baseline_benchmark#L76-L95","kind":"function","name":"test_reduction_epilogue_baseline_benchmark","path":"benchmarks/python/test_reduction_epilogue.py","language":"python","start_line":76,"end_line":95,"context_start_line":56,"context_end_line":95,"code":" with FusionDefinition() as fd:\n reduction_epilogue_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis\n )\n\n if not disable_validation:\n eager_output = reduction_epilogue_fwd_fn(\n [x.to(torch.double), epilogue.to(torch.double), reduction_axis]\n )\n fd.validate([x, epilogue], [eager_output.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [x, epilogue])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0])\n@pytest.mark.reduction\ndef test_reduction_epilogue_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n epilogue = torch.randn(size[reduction_axis - 1], device=\"cuda\", dtype=dtype)\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n\n benchmark_fn = with_executor(executor, reduction_epilogue_fwd_fn)\n\n run_benchmark(\n benchmark,\n benchmark_fn,\n [x, epilogue, reduction_axis],\n )","source_hash":"c32c13e741d9ce12b3389ad13cb452c3059307cfd179e47c8dfdcaade4eaaa96","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_fwd","uri":"program://Fuser/module/benchmarks.python.test_rmsnorm_fwd#L1-L106","kind":"module","name":"benchmarks.python.test_rmsnorm_fwd","path":"benchmarks/python/test_rmsnorm_fwd.py","language":"python","start_line":1,"end_line":106,"context_start_line":1,"context_end_line":106,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import rmsnorm\n\n\ndef rmsnorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n eps: float = 1e-5,\n):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n S3 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T4 = fd.ops.pow(T0, S3)\n T5 = fd.ops.sum(T4, dims=[1], keepdim=False, dtype=DataType.Null)\n T9 = fd.ops.broadcast_in_dim(T5, shape=[T0.size(0), 1], broadcast_dims=[0])\n S11 = fd.ops.reciprocal(T0.size(1))\n T12 = fd.ops.mul(T9, S11)\n S13 = fd.define_scalar(eps, dtype=DataType.Double)\n T14 = fd.ops.add(T12, S13)\n T15 = fd.ops.sqrt(T14)\n\n T20 = fd.ops.broadcast_in_dim(T15, shape=T0.shape(), broadcast_dims=[0, 1])\n T22 = fd.ops.reciprocal(T20)\n T23 = fd.ops.mul(T0, T22)\n T27 = fd.ops.broadcast_in_dim(T1, shape=T0.shape(), broadcast_dims=[1])\n T29 = fd.ops.mul(T27, T23)\n if dtype in PROMOTE_DTYPES:\n T29 = fd.ops.cast(T29, dtype=dtype)\n\n fd.add_output(T29)\n fd.add_output(T15)\n\n\ndef rmsnorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation required since nvFuser outputs (out, rms) differs from baselines (out)\n # Total IO bytes = in_tensor (size, dtype) + weights (size[1], dtype) +\n # rms_eps (size[0], float) + outputs (size, dtype)\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[1]) + torch.float.itemsize * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n\n with FusionDefinition() as fd:\n rmsnorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n squared_mean = (inputs.to(torch.float) ** 2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + eps)\n eager_output = weights * (inputs / rms_eps)\n fd.validate([inputs, weights], [eager_output.to(dtype), rms_eps])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n benchmark_fn = with_executor(executor, rmsnorm)\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, weights],\n iobytes=rmsnorm_fwd_iobytes(size, dtype),\n )","source_hash":"49c1adfee1ea3f57d1f67febcf2445c2eadb21648bf20267e6565d40d6961910","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_fwd.rmsnorm_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_fwd.rmsnorm_fwd_fusion#L14-L45","kind":"function","name":"rmsnorm_fwd_fusion","path":"benchmarks/python/test_rmsnorm_fwd.py","language":"python","start_line":14,"end_line":45,"context_start_line":1,"context_end_line":65,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import rmsnorm\n\n\ndef rmsnorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n eps: float = 1e-5,\n):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n S3 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T4 = fd.ops.pow(T0, S3)\n T5 = fd.ops.sum(T4, dims=[1], keepdim=False, dtype=DataType.Null)\n T9 = fd.ops.broadcast_in_dim(T5, shape=[T0.size(0), 1], broadcast_dims=[0])\n S11 = fd.ops.reciprocal(T0.size(1))\n T12 = fd.ops.mul(T9, S11)\n S13 = fd.define_scalar(eps, dtype=DataType.Double)\n T14 = fd.ops.add(T12, S13)\n T15 = fd.ops.sqrt(T14)\n\n T20 = fd.ops.broadcast_in_dim(T15, shape=T0.shape(), broadcast_dims=[0, 1])\n T22 = fd.ops.reciprocal(T20)\n T23 = fd.ops.mul(T0, T22)\n T27 = fd.ops.broadcast_in_dim(T1, shape=T0.shape(), broadcast_dims=[1])\n T29 = fd.ops.mul(T27, T23)\n if dtype in PROMOTE_DTYPES:\n T29 = fd.ops.cast(T29, dtype=dtype)\n\n fd.add_output(T29)\n fd.add_output(T15)\n\n\ndef rmsnorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation required since nvFuser outputs (out, rms) differs from baselines (out)\n # Total IO bytes = in_tensor (size, dtype) + weights (size[1], dtype) +\n # rms_eps (size[0], float) + outputs (size, dtype)\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[1]) + torch.float.itemsize * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,","source_hash":"49c1adfee1ea3f57d1f67febcf2445c2eadb21648bf20267e6565d40d6961910","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_fwd.rmsnorm_fwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_fwd.rmsnorm_fwd_iobytes#L48-L54","kind":"function","name":"rmsnorm_fwd_iobytes","path":"benchmarks/python/test_rmsnorm_fwd.py","language":"python","start_line":48,"end_line":54,"context_start_line":28,"context_end_line":74,"code":" T5 = fd.ops.sum(T4, dims=[1], keepdim=False, dtype=DataType.Null)\n T9 = fd.ops.broadcast_in_dim(T5, shape=[T0.size(0), 1], broadcast_dims=[0])\n S11 = fd.ops.reciprocal(T0.size(1))\n T12 = fd.ops.mul(T9, S11)\n S13 = fd.define_scalar(eps, dtype=DataType.Double)\n T14 = fd.ops.add(T12, S13)\n T15 = fd.ops.sqrt(T14)\n\n T20 = fd.ops.broadcast_in_dim(T15, shape=T0.shape(), broadcast_dims=[0, 1])\n T22 = fd.ops.reciprocal(T20)\n T23 = fd.ops.mul(T0, T22)\n T27 = fd.ops.broadcast_in_dim(T1, shape=T0.shape(), broadcast_dims=[1])\n T29 = fd.ops.mul(T27, T23)\n if dtype in PROMOTE_DTYPES:\n T29 = fd.ops.cast(T29, dtype=dtype)\n\n fd.add_output(T29)\n fd.add_output(T15)\n\n\ndef rmsnorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation required since nvFuser outputs (out, rms) differs from baselines (out)\n # Total IO bytes = in_tensor (size, dtype) + weights (size[1], dtype) +\n # rms_eps (size[0], float) + outputs (size, dtype)\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[1]) + torch.float.itemsize * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n\n with FusionDefinition() as fd:\n rmsnorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:","source_hash":"49c1adfee1ea3f57d1f67febcf2445c2eadb21648bf20267e6565d40d6961910","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_fwd.test_rmsnorm_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_fwd.test_rmsnorm_fwd_nvf_benchmark#L60-L81","kind":"function","name":"test_rmsnorm_fwd_nvf_benchmark","path":"benchmarks/python/test_rmsnorm_fwd.py","language":"python","start_line":60,"end_line":81,"context_start_line":40,"context_end_line":101,"code":" T29 = fd.ops.mul(T27, T23)\n if dtype in PROMOTE_DTYPES:\n T29 = fd.ops.cast(T29, dtype=dtype)\n\n fd.add_output(T29)\n fd.add_output(T15)\n\n\ndef rmsnorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation required since nvFuser outputs (out, rms) differs from baselines (out)\n # Total IO bytes = in_tensor (size, dtype) + weights (size[1], dtype) +\n # rms_eps (size[0], float) + outputs (size, dtype)\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[1]) + torch.float.itemsize * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n\n with FusionDefinition() as fd:\n rmsnorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n squared_mean = (inputs.to(torch.float) ** 2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + eps)\n eager_output = weights * (inputs / rms_eps)\n fd.validate([inputs, weights], [eager_output.to(dtype), rms_eps])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n benchmark_fn = with_executor(executor, rmsnorm)\n # Manually compute IOBytes: See PR #1725\n run_benchmark(","source_hash":"49c1adfee1ea3f57d1f67febcf2445c2eadb21648bf20267e6565d40d6961910","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_fwd.test_rmsnorm_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_fwd.test_rmsnorm_fwd_baseline_benchmark#L88-L106","kind":"function","name":"test_rmsnorm_fwd_baseline_benchmark","path":"benchmarks/python/test_rmsnorm_fwd.py","language":"python","start_line":88,"end_line":106,"context_start_line":68,"context_end_line":106,"code":" inputs = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n\n with FusionDefinition() as fd:\n rmsnorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n squared_mean = (inputs.to(torch.float) ** 2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + eps)\n eager_output = weights * (inputs / rms_eps)\n fd.validate([inputs, weights], [eager_output.to(dtype), rms_eps])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_rmsnorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n benchmark_fn = with_executor(executor, rmsnorm)\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, weights],\n iobytes=rmsnorm_fwd_iobytes(size, dtype),\n )","source_hash":"49c1adfee1ea3f57d1f67febcf2445c2eadb21648bf20267e6565d40d6961910","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops","uri":"program://Fuser/module/benchmarks.python.torch_ops#L1-L123","kind":"module","name":"benchmarks.python.torch_ops","path":"benchmarks/python/torch_ops.py","language":"python","start_line":1,"end_line":123,"context_start_line":1,"context_end_line":123,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\nimport torch.nn.functional as F\n\n\ndef dropout_layernorm(inputs: list):\n inp1, inp2, weights, bias, dropout_p = inputs\n return F.layer_norm(\n inp2 + torch.nn.functional.dropout(inp1, p=dropout_p),\n normalized_shape=inp1.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef dropout_rmsnorm(inputs: list):\n inp1, inp2, weights, dropout_p = inputs\n x = inp2 + F.dropout(inp1, p=dropout_p)\n output = weights * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-5)\n return output\n\n\ndef gelu(inputs: list):\n inp, bias = inputs\n return F.gelu(inp + bias, approximate=\"tanh\")\n\n\ndef huggingface_attn(inputs: list):\n # Reference implementation in Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/888b46324462fba70f93d5017bc0d99025f05091/thunder/tests/hf_bart_self_attn.py#L73-L83\n inp, attention_mask, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n attn = (inp + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef layernorm(inputs: list):\n inp, weights, bias = inputs\n return F.layer_norm(\n inp,\n inp.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef nanogpt_attn(inputs: list):\n # Reference implementation from Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/d3da8517bff02a913fd149b4d6559f6b5a4c6c7f/thunder/tests/nanogpt_model.py#L102-L106\n inp, bias, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n attn = inp / (hs**0.5)\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef rmsnorm(inputs: list):\n inp, weights = inputs\n squared_mean = (inp**2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + 1e-5)\n output = weights * (inp / rms_eps)\n return output\n\n\n# reference implementation from TRT-LLM\n# https://github.com/NVIDIA/TensorRT-LLM/blob/334e2cab0d6ca186b98c6c15faeb0336d84a027f/tensorrt_llm/_torch/modules/rms_norm.py#L92\n# inputs: x, w, r\n# return rmsnorm(x+r, weight), x+r\n# different ways to implement rmsnorm, here we use rsqrt based used in TRT-LLM\ndef rmsnorm_add(inputs: list):\n hidden_states, weight, residual = inputs\n hidden_states = hidden_states + residual\n residual = hidden_states\n variance = hidden_states.pow(2).mean(-1, keepdim=True)\n hidden_states = hidden_states * torch.rsqrt(variance + 1e-5)\n hidden_states = weight * hidden_states\n return hidden_states, residual\n\n\ndef scale_bias_relu(inputs: list):\n inp, scale, bias = inputs\n return F.relu(inp * scale + bias)\n\n\ndef silu_mul(inputs: list):\n x, y = inputs\n return F.silu(x) * y\n\n\ndef softmax(inputs: list):\n inp, reduction_axis = inputs\n return F.softmax(inp, dim=reduction_axis)\n\n\ndef embedding(inputs: list):\n indices, embedding_table = inputs\n return F.embedding(indices, embedding_table)\n\n\n# deepseek v3 moe scatter\n# commit e815299\n# https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L599-L607\ndef scatter_reduce(inputs: list):\n bmm_out: torch.Tensor # [seq*top_k, hidden]\n idxs: torch.Tensor # [seq*top_k]\n topk_weight: torch.Tensor # [seq , top_k]]\n bmm_out, idxs, topk_weight = inputs\n out = bmm_out.index_put([idxs], bmm_out) # [seq*top_k, hidden]\n out = out.reshape(*topk_weight.shape, -1) # [seq, top_k, hidden]\n out = out * topk_weight.unsqueeze(-1) # [seq, top_k, hidden]\n return out.sum(dim=1) # [seq, hidden]\n\n\n# simply cross entropy to benchmark quack cross entropy\ndef cross_entropy(inputs: list):\n logits, labels = inputs\n return F.cross_entropy(logits, labels, reduction=\"none\")","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.dropout_layernorm","uri":"program://Fuser/function/benchmarks.python.torch_ops.dropout_layernorm#L9-L16","kind":"function","name":"dropout_layernorm","path":"benchmarks/python/torch_ops.py","language":"python","start_line":9,"end_line":16,"context_start_line":1,"context_end_line":36,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\nimport torch.nn.functional as F\n\n\ndef dropout_layernorm(inputs: list):\n inp1, inp2, weights, bias, dropout_p = inputs\n return F.layer_norm(\n inp2 + torch.nn.functional.dropout(inp1, p=dropout_p),\n normalized_shape=inp1.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef dropout_rmsnorm(inputs: list):\n inp1, inp2, weights, dropout_p = inputs\n x = inp2 + F.dropout(inp1, p=dropout_p)\n output = weights * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-5)\n return output\n\n\ndef gelu(inputs: list):\n inp, bias = inputs\n return F.gelu(inp + bias, approximate=\"tanh\")\n\n\ndef huggingface_attn(inputs: list):\n # Reference implementation in Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/888b46324462fba70f93d5017bc0d99025f05091/thunder/tests/hf_bart_self_attn.py#L73-L83\n inp, attention_mask, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n attn = (inp + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = F.softmax(attn, dim=-1)","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.dropout_rmsnorm","uri":"program://Fuser/function/benchmarks.python.torch_ops.dropout_rmsnorm#L19-L23","kind":"function","name":"dropout_rmsnorm","path":"benchmarks/python/torch_ops.py","language":"python","start_line":19,"end_line":23,"context_start_line":1,"context_end_line":43,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\nimport torch.nn.functional as F\n\n\ndef dropout_layernorm(inputs: list):\n inp1, inp2, weights, bias, dropout_p = inputs\n return F.layer_norm(\n inp2 + torch.nn.functional.dropout(inp1, p=dropout_p),\n normalized_shape=inp1.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef dropout_rmsnorm(inputs: list):\n inp1, inp2, weights, dropout_p = inputs\n x = inp2 + F.dropout(inp1, p=dropout_p)\n output = weights * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-5)\n return output\n\n\ndef gelu(inputs: list):\n inp, bias = inputs\n return F.gelu(inp + bias, approximate=\"tanh\")\n\n\ndef huggingface_attn(inputs: list):\n # Reference implementation in Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/888b46324462fba70f93d5017bc0d99025f05091/thunder/tests/hf_bart_self_attn.py#L73-L83\n inp, attention_mask, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n attn = (inp + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef layernorm(inputs: list):\n inp, weights, bias = inputs\n return F.layer_norm(","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.gelu","uri":"program://Fuser/function/benchmarks.python.torch_ops.gelu#L26-L28","kind":"function","name":"gelu","path":"benchmarks/python/torch_ops.py","language":"python","start_line":26,"end_line":28,"context_start_line":6,"context_end_line":48,"code":"import torch.nn.functional as F\n\n\ndef dropout_layernorm(inputs: list):\n inp1, inp2, weights, bias, dropout_p = inputs\n return F.layer_norm(\n inp2 + torch.nn.functional.dropout(inp1, p=dropout_p),\n normalized_shape=inp1.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef dropout_rmsnorm(inputs: list):\n inp1, inp2, weights, dropout_p = inputs\n x = inp2 + F.dropout(inp1, p=dropout_p)\n output = weights * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-5)\n return output\n\n\ndef gelu(inputs: list):\n inp, bias = inputs\n return F.gelu(inp + bias, approximate=\"tanh\")\n\n\ndef huggingface_attn(inputs: list):\n # Reference implementation in Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/888b46324462fba70f93d5017bc0d99025f05091/thunder/tests/hf_bart_self_attn.py#L73-L83\n inp, attention_mask, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n attn = (inp + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef layernorm(inputs: list):\n inp, weights, bias = inputs\n return F.layer_norm(\n inp,\n inp.shape[1:],\n weight=weights,\n bias=bias,\n )","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.huggingface_attn","uri":"program://Fuser/function/benchmarks.python.torch_ops.huggingface_attn#L31-L38","kind":"function","name":"huggingface_attn","path":"benchmarks/python/torch_ops.py","language":"python","start_line":31,"end_line":38,"context_start_line":11,"context_end_line":58,"code":" return F.layer_norm(\n inp2 + torch.nn.functional.dropout(inp1, p=dropout_p),\n normalized_shape=inp1.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef dropout_rmsnorm(inputs: list):\n inp1, inp2, weights, dropout_p = inputs\n x = inp2 + F.dropout(inp1, p=dropout_p)\n output = weights * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-5)\n return output\n\n\ndef gelu(inputs: list):\n inp, bias = inputs\n return F.gelu(inp + bias, approximate=\"tanh\")\n\n\ndef huggingface_attn(inputs: list):\n # Reference implementation in Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/888b46324462fba70f93d5017bc0d99025f05091/thunder/tests/hf_bart_self_attn.py#L73-L83\n inp, attention_mask, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n attn = (inp + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef layernorm(inputs: list):\n inp, weights, bias = inputs\n return F.layer_norm(\n inp,\n inp.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef nanogpt_attn(inputs: list):\n # Reference implementation from Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/d3da8517bff02a913fd149b4d6559f6b5a4c6c7f/thunder/tests/nanogpt_model.py#L102-L106\n inp, bias, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n attn = inp / (hs**0.5)\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = F.softmax(attn, dim=-1)","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.layernorm","uri":"program://Fuser/function/benchmarks.python.torch_ops.layernorm#L41-L48","kind":"function","name":"layernorm","path":"benchmarks/python/torch_ops.py","language":"python","start_line":41,"end_line":48,"context_start_line":21,"context_end_line":68,"code":" x = inp2 + F.dropout(inp1, p=dropout_p)\n output = weights * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-5)\n return output\n\n\ndef gelu(inputs: list):\n inp, bias = inputs\n return F.gelu(inp + bias, approximate=\"tanh\")\n\n\ndef huggingface_attn(inputs: list):\n # Reference implementation in Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/888b46324462fba70f93d5017bc0d99025f05091/thunder/tests/hf_bart_self_attn.py#L73-L83\n inp, attention_mask, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n attn = (inp + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef layernorm(inputs: list):\n inp, weights, bias = inputs\n return F.layer_norm(\n inp,\n inp.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef nanogpt_attn(inputs: list):\n # Reference implementation from Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/d3da8517bff02a913fd149b4d6559f6b5a4c6c7f/thunder/tests/nanogpt_model.py#L102-L106\n inp, bias, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n attn = inp / (hs**0.5)\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef rmsnorm(inputs: list):\n inp, weights = inputs\n squared_mean = (inp**2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + 1e-5)\n output = weights * (inp / rms_eps)\n return output","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.nanogpt_attn","uri":"program://Fuser/function/benchmarks.python.torch_ops.nanogpt_attn#L51-L60","kind":"function","name":"nanogpt_attn","path":"benchmarks/python/torch_ops.py","language":"python","start_line":51,"end_line":60,"context_start_line":31,"context_end_line":80,"code":"def huggingface_attn(inputs: list):\n # Reference implementation in Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/888b46324462fba70f93d5017bc0d99025f05091/thunder/tests/hf_bart_self_attn.py#L73-L83\n inp, attention_mask, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n attn = (inp + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef layernorm(inputs: list):\n inp, weights, bias = inputs\n return F.layer_norm(\n inp,\n inp.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef nanogpt_attn(inputs: list):\n # Reference implementation from Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/d3da8517bff02a913fd149b4d6559f6b5a4c6c7f/thunder/tests/nanogpt_model.py#L102-L106\n inp, bias, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n attn = inp / (hs**0.5)\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef rmsnorm(inputs: list):\n inp, weights = inputs\n squared_mean = (inp**2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + 1e-5)\n output = weights * (inp / rms_eps)\n return output\n\n\n# reference implementation from TRT-LLM\n# https://github.com/NVIDIA/TensorRT-LLM/blob/334e2cab0d6ca186b98c6c15faeb0336d84a027f/tensorrt_llm/_torch/modules/rms_norm.py#L92\n# inputs: x, w, r\n# return rmsnorm(x+r, weight), x+r\n# different ways to implement rmsnorm, here we use rsqrt based used in TRT-LLM\ndef rmsnorm_add(inputs: list):\n hidden_states, weight, residual = inputs\n hidden_states = hidden_states + residual\n residual = hidden_states\n variance = hidden_states.pow(2).mean(-1, keepdim=True)","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.rmsnorm","uri":"program://Fuser/function/benchmarks.python.torch_ops.rmsnorm#L63-L68","kind":"function","name":"rmsnorm","path":"benchmarks/python/torch_ops.py","language":"python","start_line":63,"end_line":68,"context_start_line":43,"context_end_line":88,"code":" return F.layer_norm(\n inp,\n inp.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef nanogpt_attn(inputs: list):\n # Reference implementation from Thunder: https://github.com/Lightning-AI/lightning-thunder/blob/d3da8517bff02a913fd149b4d6559f6b5a4c6c7f/thunder/tests/nanogpt_model.py#L102-L106\n inp, bias, size, dropout_p = inputs\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n attn = inp / (hs**0.5)\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef rmsnorm(inputs: list):\n inp, weights = inputs\n squared_mean = (inp**2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + 1e-5)\n output = weights * (inp / rms_eps)\n return output\n\n\n# reference implementation from TRT-LLM\n# https://github.com/NVIDIA/TensorRT-LLM/blob/334e2cab0d6ca186b98c6c15faeb0336d84a027f/tensorrt_llm/_torch/modules/rms_norm.py#L92\n# inputs: x, w, r\n# return rmsnorm(x+r, weight), x+r\n# different ways to implement rmsnorm, here we use rsqrt based used in TRT-LLM\ndef rmsnorm_add(inputs: list):\n hidden_states, weight, residual = inputs\n hidden_states = hidden_states + residual\n residual = hidden_states\n variance = hidden_states.pow(2).mean(-1, keepdim=True)\n hidden_states = hidden_states * torch.rsqrt(variance + 1e-5)\n hidden_states = weight * hidden_states\n return hidden_states, residual\n\n\ndef scale_bias_relu(inputs: list):\n inp, scale, bias = inputs\n return F.relu(inp * scale + bias)","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.rmsnorm_add","uri":"program://Fuser/function/benchmarks.python.torch_ops.rmsnorm_add#L76-L83","kind":"function","name":"rmsnorm_add","path":"benchmarks/python/torch_ops.py","language":"python","start_line":76,"end_line":83,"context_start_line":56,"context_end_line":103,"code":" attn = inp / (hs**0.5)\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = F.softmax(attn, dim=-1)\n output = F.dropout(attn, p=dropout_p)\n return output\n\n\ndef rmsnorm(inputs: list):\n inp, weights = inputs\n squared_mean = (inp**2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + 1e-5)\n output = weights * (inp / rms_eps)\n return output\n\n\n# reference implementation from TRT-LLM\n# https://github.com/NVIDIA/TensorRT-LLM/blob/334e2cab0d6ca186b98c6c15faeb0336d84a027f/tensorrt_llm/_torch/modules/rms_norm.py#L92\n# inputs: x, w, r\n# return rmsnorm(x+r, weight), x+r\n# different ways to implement rmsnorm, here we use rsqrt based used in TRT-LLM\ndef rmsnorm_add(inputs: list):\n hidden_states, weight, residual = inputs\n hidden_states = hidden_states + residual\n residual = hidden_states\n variance = hidden_states.pow(2).mean(-1, keepdim=True)\n hidden_states = hidden_states * torch.rsqrt(variance + 1e-5)\n hidden_states = weight * hidden_states\n return hidden_states, residual\n\n\ndef scale_bias_relu(inputs: list):\n inp, scale, bias = inputs\n return F.relu(inp * scale + bias)\n\n\ndef silu_mul(inputs: list):\n x, y = inputs\n return F.silu(x) * y\n\n\ndef softmax(inputs: list):\n inp, reduction_axis = inputs\n return F.softmax(inp, dim=reduction_axis)\n\n\ndef embedding(inputs: list):\n indices, embedding_table = inputs\n return F.embedding(indices, embedding_table)","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.scale_bias_relu","uri":"program://Fuser/function/benchmarks.python.torch_ops.scale_bias_relu#L86-L88","kind":"function","name":"scale_bias_relu","path":"benchmarks/python/torch_ops.py","language":"python","start_line":86,"end_line":88,"context_start_line":66,"context_end_line":108,"code":" rms_eps = torch.sqrt(squared_mean + 1e-5)\n output = weights * (inp / rms_eps)\n return output\n\n\n# reference implementation from TRT-LLM\n# https://github.com/NVIDIA/TensorRT-LLM/blob/334e2cab0d6ca186b98c6c15faeb0336d84a027f/tensorrt_llm/_torch/modules/rms_norm.py#L92\n# inputs: x, w, r\n# return rmsnorm(x+r, weight), x+r\n# different ways to implement rmsnorm, here we use rsqrt based used in TRT-LLM\ndef rmsnorm_add(inputs: list):\n hidden_states, weight, residual = inputs\n hidden_states = hidden_states + residual\n residual = hidden_states\n variance = hidden_states.pow(2).mean(-1, keepdim=True)\n hidden_states = hidden_states * torch.rsqrt(variance + 1e-5)\n hidden_states = weight * hidden_states\n return hidden_states, residual\n\n\ndef scale_bias_relu(inputs: list):\n inp, scale, bias = inputs\n return F.relu(inp * scale + bias)\n\n\ndef silu_mul(inputs: list):\n x, y = inputs\n return F.silu(x) * y\n\n\ndef softmax(inputs: list):\n inp, reduction_axis = inputs\n return F.softmax(inp, dim=reduction_axis)\n\n\ndef embedding(inputs: list):\n indices, embedding_table = inputs\n return F.embedding(indices, embedding_table)\n\n\n# deepseek v3 moe scatter\n# commit e815299\n# https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L599-L607","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.silu_mul","uri":"program://Fuser/function/benchmarks.python.torch_ops.silu_mul#L91-L93","kind":"function","name":"silu_mul","path":"benchmarks/python/torch_ops.py","language":"python","start_line":91,"end_line":93,"context_start_line":71,"context_end_line":113,"code":"# reference implementation from TRT-LLM\n# https://github.com/NVIDIA/TensorRT-LLM/blob/334e2cab0d6ca186b98c6c15faeb0336d84a027f/tensorrt_llm/_torch/modules/rms_norm.py#L92\n# inputs: x, w, r\n# return rmsnorm(x+r, weight), x+r\n# different ways to implement rmsnorm, here we use rsqrt based used in TRT-LLM\ndef rmsnorm_add(inputs: list):\n hidden_states, weight, residual = inputs\n hidden_states = hidden_states + residual\n residual = hidden_states\n variance = hidden_states.pow(2).mean(-1, keepdim=True)\n hidden_states = hidden_states * torch.rsqrt(variance + 1e-5)\n hidden_states = weight * hidden_states\n return hidden_states, residual\n\n\ndef scale_bias_relu(inputs: list):\n inp, scale, bias = inputs\n return F.relu(inp * scale + bias)\n\n\ndef silu_mul(inputs: list):\n x, y = inputs\n return F.silu(x) * y\n\n\ndef softmax(inputs: list):\n inp, reduction_axis = inputs\n return F.softmax(inp, dim=reduction_axis)\n\n\ndef embedding(inputs: list):\n indices, embedding_table = inputs\n return F.embedding(indices, embedding_table)\n\n\n# deepseek v3 moe scatter\n# commit e815299\n# https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L599-L607\ndef scatter_reduce(inputs: list):\n bmm_out: torch.Tensor # [seq*top_k, hidden]\n idxs: torch.Tensor # [seq*top_k]\n topk_weight: torch.Tensor # [seq , top_k]]\n bmm_out, idxs, topk_weight = inputs","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.softmax","uri":"program://Fuser/function/benchmarks.python.torch_ops.softmax#L96-L98","kind":"function","name":"softmax","path":"benchmarks/python/torch_ops.py","language":"python","start_line":96,"end_line":98,"context_start_line":76,"context_end_line":118,"code":"def rmsnorm_add(inputs: list):\n hidden_states, weight, residual = inputs\n hidden_states = hidden_states + residual\n residual = hidden_states\n variance = hidden_states.pow(2).mean(-1, keepdim=True)\n hidden_states = hidden_states * torch.rsqrt(variance + 1e-5)\n hidden_states = weight * hidden_states\n return hidden_states, residual\n\n\ndef scale_bias_relu(inputs: list):\n inp, scale, bias = inputs\n return F.relu(inp * scale + bias)\n\n\ndef silu_mul(inputs: list):\n x, y = inputs\n return F.silu(x) * y\n\n\ndef softmax(inputs: list):\n inp, reduction_axis = inputs\n return F.softmax(inp, dim=reduction_axis)\n\n\ndef embedding(inputs: list):\n indices, embedding_table = inputs\n return F.embedding(indices, embedding_table)\n\n\n# deepseek v3 moe scatter\n# commit e815299\n# https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L599-L607\ndef scatter_reduce(inputs: list):\n bmm_out: torch.Tensor # [seq*top_k, hidden]\n idxs: torch.Tensor # [seq*top_k]\n topk_weight: torch.Tensor # [seq , top_k]]\n bmm_out, idxs, topk_weight = inputs\n out = bmm_out.index_put([idxs], bmm_out) # [seq*top_k, hidden]\n out = out.reshape(*topk_weight.shape, -1) # [seq, top_k, hidden]\n out = out * topk_weight.unsqueeze(-1) # [seq, top_k, hidden]\n return out.sum(dim=1) # [seq, hidden]\n","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.embedding","uri":"program://Fuser/function/benchmarks.python.torch_ops.embedding#L101-L103","kind":"function","name":"embedding","path":"benchmarks/python/torch_ops.py","language":"python","start_line":101,"end_line":103,"context_start_line":81,"context_end_line":123,"code":" hidden_states = hidden_states * torch.rsqrt(variance + 1e-5)\n hidden_states = weight * hidden_states\n return hidden_states, residual\n\n\ndef scale_bias_relu(inputs: list):\n inp, scale, bias = inputs\n return F.relu(inp * scale + bias)\n\n\ndef silu_mul(inputs: list):\n x, y = inputs\n return F.silu(x) * y\n\n\ndef softmax(inputs: list):\n inp, reduction_axis = inputs\n return F.softmax(inp, dim=reduction_axis)\n\n\ndef embedding(inputs: list):\n indices, embedding_table = inputs\n return F.embedding(indices, embedding_table)\n\n\n# deepseek v3 moe scatter\n# commit e815299\n# https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L599-L607\ndef scatter_reduce(inputs: list):\n bmm_out: torch.Tensor # [seq*top_k, hidden]\n idxs: torch.Tensor # [seq*top_k]\n topk_weight: torch.Tensor # [seq , top_k]]\n bmm_out, idxs, topk_weight = inputs\n out = bmm_out.index_put([idxs], bmm_out) # [seq*top_k, hidden]\n out = out.reshape(*topk_weight.shape, -1) # [seq, top_k, hidden]\n out = out * topk_weight.unsqueeze(-1) # [seq, top_k, hidden]\n return out.sum(dim=1) # [seq, hidden]\n\n\n# simply cross entropy to benchmark quack cross entropy\ndef cross_entropy(inputs: list):\n logits, labels = inputs\n return F.cross_entropy(logits, labels, reduction=\"none\")","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.scatter_reduce","uri":"program://Fuser/function/benchmarks.python.torch_ops.scatter_reduce#L109-L117","kind":"function","name":"scatter_reduce","path":"benchmarks/python/torch_ops.py","language":"python","start_line":109,"end_line":117,"context_start_line":89,"context_end_line":123,"code":"\n\ndef silu_mul(inputs: list):\n x, y = inputs\n return F.silu(x) * y\n\n\ndef softmax(inputs: list):\n inp, reduction_axis = inputs\n return F.softmax(inp, dim=reduction_axis)\n\n\ndef embedding(inputs: list):\n indices, embedding_table = inputs\n return F.embedding(indices, embedding_table)\n\n\n# deepseek v3 moe scatter\n# commit e815299\n# https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L599-L607\ndef scatter_reduce(inputs: list):\n bmm_out: torch.Tensor # [seq*top_k, hidden]\n idxs: torch.Tensor # [seq*top_k]\n topk_weight: torch.Tensor # [seq , top_k]]\n bmm_out, idxs, topk_weight = inputs\n out = bmm_out.index_put([idxs], bmm_out) # [seq*top_k, hidden]\n out = out.reshape(*topk_weight.shape, -1) # [seq, top_k, hidden]\n out = out * topk_weight.unsqueeze(-1) # [seq, top_k, hidden]\n return out.sum(dim=1) # [seq, hidden]\n\n\n# simply cross entropy to benchmark quack cross entropy\ndef cross_entropy(inputs: list):\n logits, labels = inputs\n return F.cross_entropy(logits, labels, reduction=\"none\")","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.torch_ops.cross_entropy","uri":"program://Fuser/function/benchmarks.python.torch_ops.cross_entropy#L121-L123","kind":"function","name":"cross_entropy","path":"benchmarks/python/torch_ops.py","language":"python","start_line":121,"end_line":123,"context_start_line":101,"context_end_line":123,"code":"def embedding(inputs: list):\n indices, embedding_table = inputs\n return F.embedding(indices, embedding_table)\n\n\n# deepseek v3 moe scatter\n# commit e815299\n# https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py#L599-L607\ndef scatter_reduce(inputs: list):\n bmm_out: torch.Tensor # [seq*top_k, hidden]\n idxs: torch.Tensor # [seq*top_k]\n topk_weight: torch.Tensor # [seq , top_k]]\n bmm_out, idxs, topk_weight = inputs\n out = bmm_out.index_put([idxs], bmm_out) # [seq*top_k, hidden]\n out = out.reshape(*topk_weight.shape, -1) # [seq, top_k, hidden]\n out = out * topk_weight.unsqueeze(-1) # [seq, top_k, hidden]\n return out.sum(dim=1) # [seq, hidden]\n\n\n# simply cross entropy to benchmark quack cross entropy\ndef cross_entropy(inputs: list):\n logits, labels = inputs\n return F.cross_entropy(logits, labels, reduction=\"none\")","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rope","uri":"program://Fuser/module/benchmarks.python.test_rope#L1-L110","kind":"module","name":"benchmarks.python.test_rope","path":"benchmarks/python/test_rope.py","language":"python","start_line":1,"end_line":110,"context_start_line":1,"context_end_line":110,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .core import run_benchmark, with_executor, unary_bwd_torch, clear_dynamo_cache\n\nfrom .rope_ops import rope_setup, SEQ_LENGTHS\n\n\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"llama_2_7b_hf\",\n \"llama_3_8B\",\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n \"litgpt-gemma-2-9b\",\n \"litgpt-mistral-7b\",\n \"litgpt-meta-llama-3-8B\",\n \"litgpt-phi3.5-mini\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.resize\ndef test_rope_fwd_benchmark(\n benchmark,\n variation: str,\n executor: str,\n seq_length: int | None,\n):\n kwargs = {}\n if executor == \"thunder\":\n kwargs[\"nv_enable_matmul\"] = True\n elif executor == \"torchcompile\":\n clear_dynamo_cache()\n\n model, gen_inputs, _, _ = rope_setup[variation](seq_length)\n inputs = gen_inputs()\n\n def fwd_call(inp):\n return model(*inp)\n\n # Compile the fwd fn for torchcompile\n benchmark_fn = with_executor(executor, fwd_call, **kwargs)\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"llama_2_7b_hf\",\n \"llama_3_8B\",\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n \"litgpt-gemma-2-9b\",\n \"litgpt-mistral-7b\",\n \"litgpt-meta-llama-3-8B\",\n \"litgpt-phi3.5-mini\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.resize\ndef test_rope_bwd_benchmark(\n benchmark,\n variation: str,\n executor: str,\n seq_length: int | None,\n):\n kwargs = {}\n if executor == \"thunder\":\n kwargs[\"nv_enable_matmul\"] = True\n elif executor == \"torchcompile\":\n clear_dynamo_cache()\n elif executor == \"thunder-torchcompile\" and variation in [\n \"llama_2_7b_hf\",\n \"llama_3_8B\",\n ]:\n # See https://github.com/Lightning-AI/lightning-thunder/issues/2297\n pytest.skip(\n \"torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors\"\n )\n\n model, gen_inputs, grad, iobytes = rope_setup[variation](seq_length)\n fwd_inputs = gen_inputs()\n\n def fwd_call(inp):\n return model(*inp)\n\n # execute the compiled fwd fn\n fwd_fn = with_executor(executor, fwd_call, **kwargs)\n outputs = fwd_fn(fwd_inputs)\n\n # accumulate all output, so we can feed a single grad and use the unary bwd function\n output = outputs[0]\n for i in range(1, len(outputs)):\n output += outputs[i]\n\n # NOTE: the iobytes is computed based on how thunder autograd worked. So this is just\n # a reference point for torchcompile and eager executor for comparison.\n run_benchmark(\n benchmark, unary_bwd_torch, [output, grad(), *fwd_inputs], iobytes=iobytes()\n )","source_hash":"635d88ff25e8a065f4d4efd219afbbfa00bc3439f2ce81001eea217e59f6e502","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rope.test_rope_fwd_benchmark","uri":"program://Fuser/function/benchmarks.python.test_rope.test_rope_fwd_benchmark#L29-L49","kind":"function","name":"test_rope_fwd_benchmark","path":"benchmarks/python/test_rope.py","language":"python","start_line":29,"end_line":49,"context_start_line":9,"context_end_line":69,"code":"\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"llama_2_7b_hf\",\n \"llama_3_8B\",\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n \"litgpt-gemma-2-9b\",\n \"litgpt-mistral-7b\",\n \"litgpt-meta-llama-3-8B\",\n \"litgpt-phi3.5-mini\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.resize\ndef test_rope_fwd_benchmark(\n benchmark,\n variation: str,\n executor: str,\n seq_length: int | None,\n):\n kwargs = {}\n if executor == \"thunder\":\n kwargs[\"nv_enable_matmul\"] = True\n elif executor == \"torchcompile\":\n clear_dynamo_cache()\n\n model, gen_inputs, _, _ = rope_setup[variation](seq_length)\n inputs = gen_inputs()\n\n def fwd_call(inp):\n return model(*inp)\n\n # Compile the fwd fn for torchcompile\n benchmark_fn = with_executor(executor, fwd_call, **kwargs)\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"llama_2_7b_hf\",\n \"llama_3_8B\",\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n \"litgpt-gemma-2-9b\",\n \"litgpt-mistral-7b\",\n \"litgpt-meta-llama-3-8B\",\n \"litgpt-phi3.5-mini\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)","source_hash":"635d88ff25e8a065f4d4efd219afbbfa00bc3439f2ce81001eea217e59f6e502","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rope.test_rope_bwd_benchmark","uri":"program://Fuser/function/benchmarks.python.test_rope.test_rope_bwd_benchmark#L71-L110","kind":"function","name":"test_rope_bwd_benchmark","path":"benchmarks/python/test_rope.py","language":"python","start_line":71,"end_line":110,"context_start_line":51,"context_end_line":110,"code":"\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"llama_2_7b_hf\",\n \"llama_3_8B\",\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n \"litgpt-gemma-2-9b\",\n \"litgpt-mistral-7b\",\n \"litgpt-meta-llama-3-8B\",\n \"litgpt-phi3.5-mini\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"seq_length\", SEQ_LENGTHS)\n@pytest.mark.resize\ndef test_rope_bwd_benchmark(\n benchmark,\n variation: str,\n executor: str,\n seq_length: int | None,\n):\n kwargs = {}\n if executor == \"thunder\":\n kwargs[\"nv_enable_matmul\"] = True\n elif executor == \"torchcompile\":\n clear_dynamo_cache()\n elif executor == \"thunder-torchcompile\" and variation in [\n \"llama_2_7b_hf\",\n \"llama_3_8B\",\n ]:\n # See https://github.com/Lightning-AI/lightning-thunder/issues/2297\n pytest.skip(\n \"torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors\"\n )\n\n model, gen_inputs, grad, iobytes = rope_setup[variation](seq_length)\n fwd_inputs = gen_inputs()\n\n def fwd_call(inp):\n return model(*inp)\n\n # execute the compiled fwd fn\n fwd_fn = with_executor(executor, fwd_call, **kwargs)\n outputs = fwd_fn(fwd_inputs)\n\n # accumulate all output, so we can feed a single grad and use the unary bwd function\n output = outputs[0]\n for i in range(1, len(outputs)):\n output += outputs[i]\n\n # NOTE: the iobytes is computed based on how thunder autograd worked. So this is just\n # a reference point for torchcompile and eager executor for comparison.\n run_benchmark(\n benchmark, unary_bwd_torch, [output, grad(), *fwd_inputs], iobytes=iobytes()\n )","source_hash":"635d88ff25e8a065f4d4efd219afbbfa00bc3439f2ce81001eea217e59f6e502","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rope.fwd_call","uri":"program://Fuser/function/benchmarks.python.test_rope.fwd_call#L94-L95","kind":"function","name":"fwd_call","path":"benchmarks/python/test_rope.py","language":"python","start_line":94,"end_line":95,"context_start_line":74,"context_end_line":110,"code":" executor: str,\n seq_length: int | None,\n):\n kwargs = {}\n if executor == \"thunder\":\n kwargs[\"nv_enable_matmul\"] = True\n elif executor == \"torchcompile\":\n clear_dynamo_cache()\n elif executor == \"thunder-torchcompile\" and variation in [\n \"llama_2_7b_hf\",\n \"llama_3_8B\",\n ]:\n # See https://github.com/Lightning-AI/lightning-thunder/issues/2297\n pytest.skip(\n \"torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors\"\n )\n\n model, gen_inputs, grad, iobytes = rope_setup[variation](seq_length)\n fwd_inputs = gen_inputs()\n\n def fwd_call(inp):\n return model(*inp)\n\n # execute the compiled fwd fn\n fwd_fn = with_executor(executor, fwd_call, **kwargs)\n outputs = fwd_fn(fwd_inputs)\n\n # accumulate all output, so we can feed a single grad and use the unary bwd function\n output = outputs[0]\n for i in range(1, len(outputs)):\n output += outputs[i]\n\n # NOTE: the iobytes is computed based on how thunder autograd worked. So this is just\n # a reference point for torchcompile and eager executor for comparison.\n run_benchmark(\n benchmark, unary_bwd_torch, [output, grad(), *fwd_inputs], iobytes=iobytes()\n )","source_hash":"635d88ff25e8a065f4d4efd219afbbfa00bc3439f2ce81001eea217e59f6e502","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_bwd","uri":"program://Fuser/module/benchmarks.python.test_scale_bias_relu_bwd#L1-L117","kind":"module","name":"benchmarks.python.test_scale_bias_relu_bwd","path":"benchmarks/python/test_scale_bias_relu_bwd.py","language":"python","start_line":1,"end_line":117,"context_start_line":1,"context_end_line":117,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import scale_bias_relu\n\n\ndef sbr_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n):\n T0 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n V7 = T2.shape()\n T8 = fd.ops.broadcast_in_dim(T0, shape=V7, broadcast_dims=[1])\n\n S10 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T11 = fd.ops.where(T1, T2, S10)\n T15 = fd.ops.mul(T11, T8)\n\n if dtype in PROMOTE_DTYPES:\n T15 = fd.ops.cast(T15, dtype=dtype)\n fd.add_output(T15)\n\n\ndef sbr_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = grad_out (dtype, size)+ scale (dtype, size[-1])+ bool_mask (bool, size) + grad_in (dtype, size)\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[-1])\n + torch.bool.itemsize * np.prod(size)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bool_mask = torch.gt(inputs * scale + bias, 0.0)\n\n with FusionDefinition() as fd:\n sbr_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.nn.functional.relu(inputs * scale + bias)\n eager_output.backward(grads)\n fd.validate([scale, bool_mask, grads], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [scale, bool_mask, grads])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, scale_bias_relu)\n fwd_inputs = [inputs, scale, bias]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=sbr_bwd_iobytes(size, dtype),\n )","source_hash":"396d0a23fa9dd6a57e7f20b6e7a2799ceb94ebb6a6392502ada22e3338c60657","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_bwd.sbr_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_scale_bias_relu_bwd.sbr_bwd_fusion#L20-L51","kind":"function","name":"sbr_bwd_fusion","path":"benchmarks/python/test_scale_bias_relu_bwd.py","language":"python","start_line":20,"end_line":51,"context_start_line":1,"context_end_line":71,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import scale_bias_relu\n\n\ndef sbr_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n):\n T0 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n V7 = T2.shape()\n T8 = fd.ops.broadcast_in_dim(T0, shape=V7, broadcast_dims=[1])\n\n S10 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T11 = fd.ops.where(T1, T2, S10)\n T15 = fd.ops.mul(T11, T8)\n\n if dtype in PROMOTE_DTYPES:\n T15 = fd.ops.cast(T15, dtype=dtype)\n fd.add_output(T15)\n\n\ndef sbr_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = grad_out (dtype, size)+ scale (dtype, size[-1])+ bool_mask (bool, size) + grad_in (dtype, size)\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[-1])\n + torch.bool.itemsize * np.prod(size)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):","source_hash":"396d0a23fa9dd6a57e7f20b6e7a2799ceb94ebb6a6392502ada22e3338c60657","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_bwd.sbr_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_scale_bias_relu_bwd.sbr_bwd_iobytes#L54-L59","kind":"function","name":"sbr_bwd_iobytes","path":"benchmarks/python/test_scale_bias_relu_bwd.py","language":"python","start_line":54,"end_line":59,"context_start_line":34,"context_end_line":79,"code":" dtype=dtype,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n V7 = T2.shape()\n T8 = fd.ops.broadcast_in_dim(T0, shape=V7, broadcast_dims=[1])\n\n S10 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T11 = fd.ops.where(T1, T2, S10)\n T15 = fd.ops.mul(T11, T8)\n\n if dtype in PROMOTE_DTYPES:\n T15 = fd.ops.cast(T15, dtype=dtype)\n fd.add_output(T15)\n\n\ndef sbr_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = grad_out (dtype, size)+ scale (dtype, size[-1])+ bool_mask (bool, size) + grad_in (dtype, size)\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[-1])\n + torch.bool.itemsize * np.prod(size)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bool_mask = torch.gt(inputs * scale + bias, 0.0)\n\n with FusionDefinition() as fd:\n sbr_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))","source_hash":"396d0a23fa9dd6a57e7f20b6e7a2799ceb94ebb6a6392502ada22e3338c60657","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_bwd.test_sbr_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_scale_bias_relu_bwd.test_sbr_bwd_nvf_benchmark#L65-L87","kind":"function","name":"test_sbr_bwd_nvf_benchmark","path":"benchmarks/python/test_scale_bias_relu_bwd.py","language":"python","start_line":65,"end_line":87,"context_start_line":45,"context_end_line":107,"code":" S10 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T11 = fd.ops.where(T1, T2, S10)\n T15 = fd.ops.mul(T11, T8)\n\n if dtype in PROMOTE_DTYPES:\n T15 = fd.ops.cast(T15, dtype=dtype)\n fd.add_output(T15)\n\n\ndef sbr_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = grad_out (dtype, size)+ scale (dtype, size[-1])+ bool_mask (bool, size) + grad_in (dtype, size)\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[-1])\n + torch.bool.itemsize * np.prod(size)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bool_mask = torch.gt(inputs * scale + bias, 0.0)\n\n with FusionDefinition() as fd:\n sbr_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.nn.functional.relu(inputs * scale + bias)\n eager_output.backward(grads)\n fd.validate([scale, bool_mask, grads], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [scale, bool_mask, grads])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n # Compile the fwd fn for torchcompile","source_hash":"396d0a23fa9dd6a57e7f20b6e7a2799ceb94ebb6a6392502ada22e3338c60657","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_bwd.test_sbr_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_scale_bias_relu_bwd.test_sbr_bwd_baseline_benchmark#L94-L117","kind":"function","name":"test_sbr_bwd_baseline_benchmark","path":"benchmarks/python/test_scale_bias_relu_bwd.py","language":"python","start_line":94,"end_line":117,"context_start_line":74,"context_end_line":117,"code":" scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bool_mask = torch.gt(inputs * scale + bias, 0.0)\n\n with FusionDefinition() as fd:\n sbr_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.nn.functional.relu(inputs * scale + bias)\n eager_output.backward(grads)\n fd.validate([scale, bool_mask, grads], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [scale, bool_mask, grads])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, scale_bias_relu)\n fwd_inputs = [inputs, scale, bias]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=sbr_bwd_iobytes(size, dtype),\n )","source_hash":"396d0a23fa9dd6a57e7f20b6e7a2799ceb94ebb6a6392502ada22e3338c60657","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_silu_mul_bwd","uri":"program://Fuser/module/benchmarks.python.test_silu_mul_bwd#L1-L116","kind":"module","name":"benchmarks.python.test_silu_mul_bwd","path":"benchmarks/python/test_silu_mul_bwd.py","language":"python","start_line":1,"end_line":116,"context_start_line":1,"context_end_line":116,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import silu_mul\n\n\ndef silu_mul_bwd_fusion(fd: FusionDefinition, dtype: DataType):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T2 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n T3 = fd.ops.neg(T1)\n T4 = fd.ops.exp(T3)\n S5 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T6 = fd.ops.add(S5, T4)\n T7 = fd.ops.reciprocal(T6)\n T8 = fd.ops.mul(T1, T7)\n T9 = fd.ops.mul(T0, T2)\n T10 = fd.ops.mul(T0, T8)\n T11 = fd.ops.mul(T9, T7)\n T12 = fd.ops.mul(T9, T1)\n T13 = fd.ops.neg(T12)\n T14 = fd.ops.mul(T13, T7)\n T15 = fd.ops.mul(T14, T7)\n S16 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T17 = fd.ops.mul(S16, T15)\n T18 = fd.ops.mul(T17, T4)\n T19 = fd.ops.neg(T18)\n T20 = fd.ops.add(T11, T19)\n if dtype in PROMOTE_DTYPES:\n T10 = fd.ops.cast(T10, dtype=dtype)\n T20 = fd.ops.cast(T20, dtype=dtype)\n fd.add_output(T10)\n fd.add_output(T20)\n\n\ndef silu_mul_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = grad_out, x, y, grad_x, grad_y\n return int(dtype.itemsize * np.prod(size) * 5)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n x = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n y = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n silu_mul_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = torch.nn.functional.silu(x) * y\n eager_output.backward(grads)\n fd.validate([grads, x, y], [y.grad, x.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [grads, x, y])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n x = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n y = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, silu_mul)\n fwd_inputs = [x, y]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=silu_mul_bwd_iobytes(size, dtype),\n )","source_hash":"ae56be6ded2c9ee256475b1ad8f6bc2934524add3313616fab9eeb1fb7da5109","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_silu_mul_bwd.silu_mul_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_silu_mul_bwd.silu_mul_bwd_fusion#L20-L58","kind":"function","name":"silu_mul_bwd_fusion","path":"benchmarks/python/test_silu_mul_bwd.py","language":"python","start_line":20,"end_line":58,"context_start_line":1,"context_end_line":78,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import silu_mul\n\n\ndef silu_mul_bwd_fusion(fd: FusionDefinition, dtype: DataType):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T2 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n T3 = fd.ops.neg(T1)\n T4 = fd.ops.exp(T3)\n S5 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T6 = fd.ops.add(S5, T4)\n T7 = fd.ops.reciprocal(T6)\n T8 = fd.ops.mul(T1, T7)\n T9 = fd.ops.mul(T0, T2)\n T10 = fd.ops.mul(T0, T8)\n T11 = fd.ops.mul(T9, T7)\n T12 = fd.ops.mul(T9, T1)\n T13 = fd.ops.neg(T12)\n T14 = fd.ops.mul(T13, T7)\n T15 = fd.ops.mul(T14, T7)\n S16 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T17 = fd.ops.mul(S16, T15)\n T18 = fd.ops.mul(T17, T4)\n T19 = fd.ops.neg(T18)\n T20 = fd.ops.add(T11, T19)\n if dtype in PROMOTE_DTYPES:\n T10 = fd.ops.cast(T10, dtype=dtype)\n T20 = fd.ops.cast(T20, dtype=dtype)\n fd.add_output(T10)\n fd.add_output(T20)\n\n\ndef silu_mul_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = grad_out, x, y, grad_x, grad_y\n return int(dtype.itemsize * np.prod(size) * 5)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n x = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n y = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)","source_hash":"ae56be6ded2c9ee256475b1ad8f6bc2934524add3313616fab9eeb1fb7da5109","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_silu_mul_bwd.silu_mul_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_silu_mul_bwd.silu_mul_bwd_iobytes#L61-L63","kind":"function","name":"silu_mul_bwd_iobytes","path":"benchmarks/python/test_silu_mul_bwd.py","language":"python","start_line":61,"end_line":63,"context_start_line":41,"context_end_line":83,"code":" T8 = fd.ops.mul(T1, T7)\n T9 = fd.ops.mul(T0, T2)\n T10 = fd.ops.mul(T0, T8)\n T11 = fd.ops.mul(T9, T7)\n T12 = fd.ops.mul(T9, T1)\n T13 = fd.ops.neg(T12)\n T14 = fd.ops.mul(T13, T7)\n T15 = fd.ops.mul(T14, T7)\n S16 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T17 = fd.ops.mul(S16, T15)\n T18 = fd.ops.mul(T17, T4)\n T19 = fd.ops.neg(T18)\n T20 = fd.ops.add(T11, T19)\n if dtype in PROMOTE_DTYPES:\n T10 = fd.ops.cast(T10, dtype=dtype)\n T20 = fd.ops.cast(T20, dtype=dtype)\n fd.add_output(T10)\n fd.add_output(T20)\n\n\ndef silu_mul_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = grad_out, x, y, grad_x, grad_y\n return int(dtype.itemsize * np.prod(size) * 5)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n x = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n y = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n silu_mul_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = torch.nn.functional.silu(x) * y\n eager_output.backward(grads)","source_hash":"ae56be6ded2c9ee256475b1ad8f6bc2934524add3313616fab9eeb1fb7da5109","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_silu_mul_bwd.test_silu_mul_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_silu_mul_bwd.test_silu_mul_bwd_nvf_benchmark#L69-L87","kind":"function","name":"test_silu_mul_bwd_nvf_benchmark","path":"benchmarks/python/test_silu_mul_bwd.py","language":"python","start_line":69,"end_line":87,"context_start_line":49,"context_end_line":107,"code":" S16 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T17 = fd.ops.mul(S16, T15)\n T18 = fd.ops.mul(T17, T4)\n T19 = fd.ops.neg(T18)\n T20 = fd.ops.add(T11, T19)\n if dtype in PROMOTE_DTYPES:\n T10 = fd.ops.cast(T10, dtype=dtype)\n T20 = fd.ops.cast(T20, dtype=dtype)\n fd.add_output(T10)\n fd.add_output(T20)\n\n\ndef silu_mul_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = grad_out, x, y, grad_x, grad_y\n return int(dtype.itemsize * np.prod(size) * 5)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n x = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n y = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n silu_mul_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = torch.nn.functional.silu(x) * y\n eager_output.backward(grads)\n fd.validate([grads, x, y], [y.grad, x.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [grads, x, y])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n x = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n y = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, silu_mul)","source_hash":"ae56be6ded2c9ee256475b1ad8f6bc2934524add3313616fab9eeb1fb7da5109","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_silu_mul_bwd.test_silu_mul_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_silu_mul_bwd.test_silu_mul_bwd_baseline_benchmark#L94-L116","kind":"function","name":"test_silu_mul_bwd_baseline_benchmark","path":"benchmarks/python/test_silu_mul_bwd.py","language":"python","start_line":94,"end_line":116,"context_start_line":74,"context_end_line":116,"code":" disable_benchmarking: bool,\n):\n x = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n y = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n silu_mul_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = torch.nn.functional.silu(x) * y\n eager_output.backward(grads)\n fd.validate([grads, x, y], [y.grad, x.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [grads, x, y])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_silu_mul_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n x = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n y = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, silu_mul)\n fwd_inputs = [x, y]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=silu_mul_bwd_iobytes(size, dtype),\n )","source_hash":"ae56be6ded2c9ee256475b1ad8f6bc2934524add3313616fab9eeb1fb7da5109","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core","uri":"program://Fuser/module/benchmarks.python.core#L1-L344","kind":"module","name":"benchmarks.python.core","path":"benchmarks/python/core.py","language":"python","start_line":1,"end_line":344,"context_start_line":1,"context_end_line":344,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom collections.abc import Iterable\nimport pytest_benchmark\nimport torch\nfrom typing import List, Callable, Union\nimport numpy as np\nfrom nvfuser_direct import FusionDefinition, PythonProfiler\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\nfrom nvfuser_direct.benchmark_utils import FusionProfileTimer, CuptiTimer\nimport warnings\nimport thunder\nfrom thunder.executors.nvfuserex import nvfuserex\nimport importlib.util\n\n# These variables can be overwritten through CLI commands\n# --benchmark-rounds=rounds --benchmark-warmup-rounds=warmup_rounds\n# --benchmark-num-inputs=num_inputs\nBENCHMARK_CONFIG = {\n \"rounds\": 10,\n \"warmup_rounds\": 1,\n \"num_inputs\": None,\n \"with_nsys\": False,\n}\n\nL2_CACHE_SIZE = DEVICE_PROPERTIES[\"gpu_l2_bytes\"]\nPEAK_BANDWIDTH_GBPS = DEVICE_PROPERTIES[\"gpu_peak_bandwidth_gbps\"]\n\nDEFAULT_EXECUTORS = [\"eager\", \"torchcompile\"]\n\n\ndef check_module_available(module_name):\n # If spec is not None, the module can be imported.\n spec = importlib.util.find_spec(module_name)\n return spec is not None\n\n\ndef clear_l2_cache() -> None:\n \"\"\"\n Flushes the L2 cache by creating a buffer of the same size.\n \"\"\"\n n_elements = L2_CACHE_SIZE // 4\n x = torch.empty(n_elements, dtype=torch.float32, device=\"cuda\", requires_grad=False)\n y = torch.clone(x)\n\n\ndef clear_dynamo_cache() -> None:\n \"\"\"\n Utility function to enforce re-compilation to avoid different results between\n running a serials of tests and a standalone test due to kernel re-use.\n It slows down the test but ensures the correctness of the benchmark results.\n Ref: https://github.com/pytorch/pytorch/issues/107444\n \"\"\"\n torch._dynamo.reset()\n\n\n# Backward function for torch baseline benchmarks.\n# The first two inputs are expected to be out and grad_out. The remaining are inputs of the forward pass used to clear grad between subsequent runs to avoid grad accumulation. See setup() in run_benchmark().\ndef unary_bwd_torch(inputs: List): # [output, grad_out, fwd_inputs]\n inputs[0].backward(inputs[1], retain_graph=True)\n\n\ndef with_executor(executor: str, fwd_fn: Callable, **kwargs) -> Callable:\n assert executor in [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n if executor == \"eager\":\n return fwd_fn\n if executor == \"torchcompile\":\n return torch.compile(fwd_fn, **kwargs)\n if executor == \"thunder\":\n return thunder.jit(\n fwd_fn, nv_enable_bookend=False, executors=[nvfuserex], **kwargs\n )\n if executor == \"thunder-torchcompile\":\n return thunder.jit(fwd_fn, executors=[\"torchcompile\"], **kwargs)\n\n\ndef compute_total_iobytes(\n tensor_props: dict[str, tuple[int | tuple[int, ...], torch.dtype]],\n):\n \"\"\"\n Compute IObytes for baselines from given description:\n Tensor_props has entries of the form: {'tensor_id': (size: tuple, dtype: torch.dtype)}\n \"\"\"\n iobytes = 0\n for _, tensor_prop in tensor_props.items():\n size, dtype = tensor_prop[0], tensor_prop[1]\n if isinstance(size, tuple):\n iobytes += np.prod(size) * dtype.itemsize\n else:\n iobytes += size * dtype.itemsize\n return int(iobytes)\n\n\nclass NVFBenchmark:\n \"\"\"\n A wrapper class around pytest-benchmark to support\n torchprofiler-based timer and metric computation.\n \"\"\"\n\n def __init__(\n self, benchmark_fixture, device: str = \"cuda\", precision: float = 1e-6\n ):\n \"\"\"\n Arguments:\n benchmark_fixture: pytest-benchmark fixture passed to every\n function intended to be run as a benchmark by pytest\n precision: Precision for the torchprofiler-based timer used.\n Set explicitly to avoid timer calibration.\n\n Class members:\n self.device: Device type -- \"cuda\" or \"host\"\n self.benchmark: Underlying pytest-benchmark fixture\n \"\"\"\n self.device = device\n self._setup_timer(benchmark_fixture, device, precision)\n self.benchmark = benchmark_fixture\n\n def _setup_timer(self, benchmark_fixture, device: str, precision: float):\n \"\"\"Setup the appropriate timer based on device type.\"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n warnings.warn(\n \"NSYS is enabled. No profiler will be used and pytest will report wall-clock time. \"\n \"Please refer to the nsys report for accurate timings.\"\n )\n return\n\n # Timer selection based on device\n timer_class = CuptiTimer if device == \"cuda\" else FusionProfileTimer\n benchmark_fixture._timer = timer_class()\n # Externally set the precision to avoid timer calibration. Since the timer uses CUDA times,\n # calibration using subsequent timer calls produces invalid results.\n # https://github.com/ionelmc/pytest-benchmark/blob/728752d2976ef53fde7e40beb3e55f09cf4d4736/src/pytest_benchmark/timers.py#L15\n benchmark_fixture._precisions[benchmark_fixture._timer] = precision\n\n def __call__(self, function_to_benchmark: Callable, *args, **kwargs):\n return self.benchmark(function_to_benchmark, *args, **kwargs)\n\n def __getattr__(self, attr):\n if attr not in self.__dict__:\n return getattr(self.benchmark, attr)\n return super().__getattr__(attr)\n\n def set_fd(self, fd):\n \"\"\"\n Set the fd object for fusion profiling.\n fd is returned by setup() for host benchmarking.\n \"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n return\n assert isinstance(self._timer, FusionProfileTimer)\n self._timer.set_fd(fd)\n\n def cleanup(self):\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n self._timer.cleanup()\n\n def set_metrics(\n self,\n inputs: Union[torch.Tensor, List],\n outputs: Union[torch.Tensor, List],\n iobytes: int = None,\n ) -> None:\n \"\"\"\n Compute metrics for the target function when device = \"cuda\".\n\n Args:\n inputs: Inputs to the target function\n outputs: Outputs of the target function\n iobytes (Optional): When given, IO bytes computation is skipped\n and this is used to compute the metrics.\n\n Current metrics:\n IOBytes: Total bytes in inputs + outputs\n BytesPerSecond: IOBytes * total_rounds / total_time\n Bandwdith (GBps): BytesPerSecond / 1e9\n % Peak Bandwidth (SOL): 100 * Bandwidth /PEAK_BANDWIDTH\n \"\"\"\n if not iobytes:\n if not isinstance(inputs, Iterable) or isinstance(inputs, torch.Tensor):\n inputs = [inputs]\n if not isinstance(outputs, Iterable) or isinstance(outputs, torch.Tensor):\n outputs = [outputs]\n\n iobytes = 0\n for inp in inputs:\n if isinstance(inp, torch.Tensor):\n iobytes += inp.element_size() * inp.numel()\n\n for out in outputs:\n if isinstance(out, torch.Tensor):\n iobytes += out.element_size() * out.numel()\n\n self.benchmark.extra_info[\"IOBytes\"] = iobytes\n bandwidth_bps = (\n iobytes * self.benchmark.stats[\"rounds\"]\n ) / self.benchmark.stats[\"total\"]\n self.benchmark.extra_info[\"Bandwidth (Bps)\"] = bandwidth_bps\n self.benchmark.extra_info[\"Bandwidth (GBps)\"] = bandwidth_bps / 1e9\n self.benchmark.extra_info[\"% Peak Bandwidth (SOL)\"] = (\n 100 * (bandwidth_bps / 1e9) / PEAK_BANDWIDTH_GBPS\n )\n\n\ndef run_benchmark(\n benchmark: pytest_benchmark.fixture.BenchmarkFixture,\n benchmark_fn: Callable | None,\n inputs: Union[torch.Tensor, List],\n iobytes: int = None,\n device: str = \"cuda\",\n fusion_fn: Callable = None,\n) -> Union[torch.Tensor, List]:\n \"\"\"\n Benchmarks the target function using torchprofiler and stores metrics as extra information.\n\n Arguments:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Target function\n inputs: Inputs to the target function\n iobytes (Optional): When given, IO bytes computation is skipped\n and this is used to compute SOL and bandwidth.\n device (Optional): Default: CUDA, Possible values: [\"cuda\", \"host\"].\n Using device=\"host\" is only allowed with nvFuser FusionDefinition.\n fusion_fn (Optional): Must be provided if device = \"host\".\n fusion_fn should only require FusionDefinition() as the input.\n Use functools.partial if fusion_fn accepts additional arguments.\n See test_many_pointwise_ops.py for example.\n\n Returns:\n outputs: Output of the target function\n \"\"\"\n\n # Check that the device is `cuda` or `host:{compile/steady/dynamic}`.\n assert device.split(\":\")[0] in [\n \"cuda\",\n \"host\",\n ], f'Unsupported device type: {device.split(\":\")[0]}. Use one of cuda/host.'\n\n host_bench_mode = None\n\n # Store warmup rounds locally to modify for host:steady/dynamic cases.\n warmup_rounds = BENCHMARK_CONFIG[\"warmup_rounds\"]\n\n if device.split(\":\")[0] == \"host\":\n # Host benchmarking expects a fusion function to generate fusion definitions everytime FusionCache is reset.\n assert fusion_fn is not None and benchmark_fn is None\n\n # device = 'host:compile', 'host:steady', 'host:dyanamic'\n # Set the host_bench_mode -- The 3 modes require different setup calls.\n host_bench_mode = device.split(\":\")[-1]\n device = device.split(\":\")[0] # device = 'host'\n\n # Set the warmup rounds if required for `steady/dynamic` host latency measurement.\n if (\n host_bench_mode in [\"steady\", \"dynamic\"]\n and BENCHMARK_CONFIG[\"warmup_rounds\"] == 0\n ):\n # By default, warmup_rounds=1. If BENCHMARK_CONFIG['warmup_rounds'] == 0 through --benchmark-warmup-rounds, raise a warning that it was ignored.\n warnings.warn(\n \"--benchmark-warmup-rounds=0 is ignored for host:steady/dynamic benchmarking. Setting warmup_rounds=1.\"\n )\n warmup_rounds = 1\n\n \"\"\"\n Setup function: This is called before each benchmarking round. This function is used to:\n 1. Clear L2 cache.\n 2. For host latency benchmarks, the 3 modes use different setups.\n a) 'compile': FusionCache is reset at every round to measure the first time overhead before instantiating fd.\n b) 'steady': Nothing additional is required. The warmup round avoids including the first time overhead in the measurements.\n c) 'dynamic': We maintain a global counter to track which input is executed. Once all the inputs have been executed once,\n the FusionCache is reset again and we execute fd for the first input to avoid including the first time compile overhead in the dynamic measurement.\n \"\"\"\n\n # Counter used in `dynamic` host latency benchmarking, unused in other cases.\n global counter\n counter = 0\n\n def setup():\n clear_l2_cache()\n if device == \"cuda\":\n for inp in inputs:\n if isinstance(inp, torch.Tensor):\n inp.grad = None\n return [inputs], {}\n\n # Device = 'host'\n # For device='host', we use the host_benchmark_fn below. It expects a list of fusion inputs, and the fd object.\n assert host_bench_mode in [\n \"compile\",\n \"steady\",\n \"dynamic\",\n ], f\"Expected host benchmark mode to be one of compile, steady, or dynamic, found {host_bench_mode}\"\n\n # Instantiate the fusion definition\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n if host_bench_mode in [\"compile\"]:\n return [inputs], {\"fd\": fd}\n\n if host_bench_mode in [\"steady\"]:\n # Run once to compile FusionExecutorCache and avoid measuring first time overhead.\n fd.execute(inputs)\n return [inputs], {\"fd\": fd}\n\n # For dynamic host latency benchmarking, return a particular input shape, and reset FusionCache if all inputs have been executed.\n global counter\n counter += 1\n # The current input is counter % len(inputs). Execute fd with next input\n # to avoid measuring first time overhead but avoid cache hit with current input.\n fd.execute(inputs[(counter + 1) % len(inputs)])\n return [inputs[counter % len(inputs)]], {\"fd\": fd}\n\n # Create an instance of NVFBenchmark\n nvf_benchmark = NVFBenchmark(benchmark, device=device)\n\n # The host_benchmark_fn uses the `fd` object returned from setup function.\n def host_benchmark_fn(inputs, fd):\n # Set the fd variable used to query the profile object\n nvf_benchmark.set_fd(fd)\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n with PythonProfiler() as prof:\n return fd.execute(inputs)\n return fd.execute(inputs)\n\n benchmark_fn = benchmark_fn if benchmark_fn is not None else host_benchmark_fn\n\n try:\n outputs = nvf_benchmark.pedantic(\n benchmark_fn,\n setup=setup,\n rounds=BENCHMARK_CONFIG[\"rounds\"],\n warmup_rounds=warmup_rounds,\n )\n if device == \"cuda\":\n # Record additional metrics (IOBytes, Bandwidth)\n nvf_benchmark.set_metrics(inputs, outputs, iobytes)\n return outputs\n except Exception as e:\n raise RuntimeError(\n f\"Exception when running {benchmark_fn.__name__}: {e}\"\n ) from e\n finally:\n nvf_benchmark.cleanup()","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.check_module_available","uri":"program://Fuser/function/benchmarks.python.core.check_module_available#L33-L36","kind":"function","name":"check_module_available","path":"benchmarks/python/core.py","language":"python","start_line":33,"end_line":36,"context_start_line":13,"context_end_line":56,"code":"import thunder\nfrom thunder.executors.nvfuserex import nvfuserex\nimport importlib.util\n\n# These variables can be overwritten through CLI commands\n# --benchmark-rounds=rounds --benchmark-warmup-rounds=warmup_rounds\n# --benchmark-num-inputs=num_inputs\nBENCHMARK_CONFIG = {\n \"rounds\": 10,\n \"warmup_rounds\": 1,\n \"num_inputs\": None,\n \"with_nsys\": False,\n}\n\nL2_CACHE_SIZE = DEVICE_PROPERTIES[\"gpu_l2_bytes\"]\nPEAK_BANDWIDTH_GBPS = DEVICE_PROPERTIES[\"gpu_peak_bandwidth_gbps\"]\n\nDEFAULT_EXECUTORS = [\"eager\", \"torchcompile\"]\n\n\ndef check_module_available(module_name):\n # If spec is not None, the module can be imported.\n spec = importlib.util.find_spec(module_name)\n return spec is not None\n\n\ndef clear_l2_cache() -> None:\n \"\"\"\n Flushes the L2 cache by creating a buffer of the same size.\n \"\"\"\n n_elements = L2_CACHE_SIZE // 4\n x = torch.empty(n_elements, dtype=torch.float32, device=\"cuda\", requires_grad=False)\n y = torch.clone(x)\n\n\ndef clear_dynamo_cache() -> None:\n \"\"\"\n Utility function to enforce re-compilation to avoid different results between\n running a serials of tests and a standalone test due to kernel re-use.\n It slows down the test but ensures the correctness of the benchmark results.\n Ref: https://github.com/pytorch/pytorch/issues/107444\n \"\"\"\n torch._dynamo.reset()\n","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.clear_l2_cache","uri":"program://Fuser/function/benchmarks.python.core.clear_l2_cache#L39-L45","kind":"function","name":"clear_l2_cache","path":"benchmarks/python/core.py","language":"python","start_line":39,"end_line":45,"context_start_line":19,"context_end_line":65,"code":"# --benchmark-num-inputs=num_inputs\nBENCHMARK_CONFIG = {\n \"rounds\": 10,\n \"warmup_rounds\": 1,\n \"num_inputs\": None,\n \"with_nsys\": False,\n}\n\nL2_CACHE_SIZE = DEVICE_PROPERTIES[\"gpu_l2_bytes\"]\nPEAK_BANDWIDTH_GBPS = DEVICE_PROPERTIES[\"gpu_peak_bandwidth_gbps\"]\n\nDEFAULT_EXECUTORS = [\"eager\", \"torchcompile\"]\n\n\ndef check_module_available(module_name):\n # If spec is not None, the module can be imported.\n spec = importlib.util.find_spec(module_name)\n return spec is not None\n\n\ndef clear_l2_cache() -> None:\n \"\"\"\n Flushes the L2 cache by creating a buffer of the same size.\n \"\"\"\n n_elements = L2_CACHE_SIZE // 4\n x = torch.empty(n_elements, dtype=torch.float32, device=\"cuda\", requires_grad=False)\n y = torch.clone(x)\n\n\ndef clear_dynamo_cache() -> None:\n \"\"\"\n Utility function to enforce re-compilation to avoid different results between\n running a serials of tests and a standalone test due to kernel re-use.\n It slows down the test but ensures the correctness of the benchmark results.\n Ref: https://github.com/pytorch/pytorch/issues/107444\n \"\"\"\n torch._dynamo.reset()\n\n\n# Backward function for torch baseline benchmarks.\n# The first two inputs are expected to be out and grad_out. The remaining are inputs of the forward pass used to clear grad between subsequent runs to avoid grad accumulation. See setup() in run_benchmark().\ndef unary_bwd_torch(inputs: List): # [output, grad_out, fwd_inputs]\n inputs[0].backward(inputs[1], retain_graph=True)\n\n\ndef with_executor(executor: str, fwd_fn: Callable, **kwargs) -> Callable:\n assert executor in [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.clear_dynamo_cache","uri":"program://Fuser/function/benchmarks.python.core.clear_dynamo_cache#L48-L55","kind":"function","name":"clear_dynamo_cache","path":"benchmarks/python/core.py","language":"python","start_line":48,"end_line":55,"context_start_line":28,"context_end_line":75,"code":"PEAK_BANDWIDTH_GBPS = DEVICE_PROPERTIES[\"gpu_peak_bandwidth_gbps\"]\n\nDEFAULT_EXECUTORS = [\"eager\", \"torchcompile\"]\n\n\ndef check_module_available(module_name):\n # If spec is not None, the module can be imported.\n spec = importlib.util.find_spec(module_name)\n return spec is not None\n\n\ndef clear_l2_cache() -> None:\n \"\"\"\n Flushes the L2 cache by creating a buffer of the same size.\n \"\"\"\n n_elements = L2_CACHE_SIZE // 4\n x = torch.empty(n_elements, dtype=torch.float32, device=\"cuda\", requires_grad=False)\n y = torch.clone(x)\n\n\ndef clear_dynamo_cache() -> None:\n \"\"\"\n Utility function to enforce re-compilation to avoid different results between\n running a serials of tests and a standalone test due to kernel re-use.\n It slows down the test but ensures the correctness of the benchmark results.\n Ref: https://github.com/pytorch/pytorch/issues/107444\n \"\"\"\n torch._dynamo.reset()\n\n\n# Backward function for torch baseline benchmarks.\n# The first two inputs are expected to be out and grad_out. The remaining are inputs of the forward pass used to clear grad between subsequent runs to avoid grad accumulation. See setup() in run_benchmark().\ndef unary_bwd_torch(inputs: List): # [output, grad_out, fwd_inputs]\n inputs[0].backward(inputs[1], retain_graph=True)\n\n\ndef with_executor(executor: str, fwd_fn: Callable, **kwargs) -> Callable:\n assert executor in [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n if executor == \"eager\":\n return fwd_fn\n if executor == \"torchcompile\":\n return torch.compile(fwd_fn, **kwargs)\n if executor == \"thunder\":\n return thunder.jit(\n fwd_fn, nv_enable_bookend=False, executors=[nvfuserex], **kwargs\n )\n if executor == \"thunder-torchcompile\":\n return thunder.jit(fwd_fn, executors=[\"torchcompile\"], **kwargs)","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.unary_bwd_torch","uri":"program://Fuser/function/benchmarks.python.core.unary_bwd_torch#L60-L61","kind":"function","name":"unary_bwd_torch","path":"benchmarks/python/core.py","language":"python","start_line":60,"end_line":61,"context_start_line":40,"context_end_line":81,"code":" \"\"\"\n Flushes the L2 cache by creating a buffer of the same size.\n \"\"\"\n n_elements = L2_CACHE_SIZE // 4\n x = torch.empty(n_elements, dtype=torch.float32, device=\"cuda\", requires_grad=False)\n y = torch.clone(x)\n\n\ndef clear_dynamo_cache() -> None:\n \"\"\"\n Utility function to enforce re-compilation to avoid different results between\n running a serials of tests and a standalone test due to kernel re-use.\n It slows down the test but ensures the correctness of the benchmark results.\n Ref: https://github.com/pytorch/pytorch/issues/107444\n \"\"\"\n torch._dynamo.reset()\n\n\n# Backward function for torch baseline benchmarks.\n# The first two inputs are expected to be out and grad_out. The remaining are inputs of the forward pass used to clear grad between subsequent runs to avoid grad accumulation. See setup() in run_benchmark().\ndef unary_bwd_torch(inputs: List): # [output, grad_out, fwd_inputs]\n inputs[0].backward(inputs[1], retain_graph=True)\n\n\ndef with_executor(executor: str, fwd_fn: Callable, **kwargs) -> Callable:\n assert executor in [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n if executor == \"eager\":\n return fwd_fn\n if executor == \"torchcompile\":\n return torch.compile(fwd_fn, **kwargs)\n if executor == \"thunder\":\n return thunder.jit(\n fwd_fn, nv_enable_bookend=False, executors=[nvfuserex], **kwargs\n )\n if executor == \"thunder-torchcompile\":\n return thunder.jit(fwd_fn, executors=[\"torchcompile\"], **kwargs)\n\n\ndef compute_total_iobytes(\n tensor_props: dict[str, tuple[int | tuple[int, ...], torch.dtype]],\n):\n \"\"\"","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.with_executor","uri":"program://Fuser/function/benchmarks.python.core.with_executor#L64-L75","kind":"function","name":"with_executor","path":"benchmarks/python/core.py","language":"python","start_line":64,"end_line":75,"context_start_line":44,"context_end_line":95,"code":" x = torch.empty(n_elements, dtype=torch.float32, device=\"cuda\", requires_grad=False)\n y = torch.clone(x)\n\n\ndef clear_dynamo_cache() -> None:\n \"\"\"\n Utility function to enforce re-compilation to avoid different results between\n running a serials of tests and a standalone test due to kernel re-use.\n It slows down the test but ensures the correctness of the benchmark results.\n Ref: https://github.com/pytorch/pytorch/issues/107444\n \"\"\"\n torch._dynamo.reset()\n\n\n# Backward function for torch baseline benchmarks.\n# The first two inputs are expected to be out and grad_out. The remaining are inputs of the forward pass used to clear grad between subsequent runs to avoid grad accumulation. See setup() in run_benchmark().\ndef unary_bwd_torch(inputs: List): # [output, grad_out, fwd_inputs]\n inputs[0].backward(inputs[1], retain_graph=True)\n\n\ndef with_executor(executor: str, fwd_fn: Callable, **kwargs) -> Callable:\n assert executor in [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n if executor == \"eager\":\n return fwd_fn\n if executor == \"torchcompile\":\n return torch.compile(fwd_fn, **kwargs)\n if executor == \"thunder\":\n return thunder.jit(\n fwd_fn, nv_enable_bookend=False, executors=[nvfuserex], **kwargs\n )\n if executor == \"thunder-torchcompile\":\n return thunder.jit(fwd_fn, executors=[\"torchcompile\"], **kwargs)\n\n\ndef compute_total_iobytes(\n tensor_props: dict[str, tuple[int | tuple[int, ...], torch.dtype]],\n):\n \"\"\"\n Compute IObytes for baselines from given description:\n Tensor_props has entries of the form: {'tensor_id': (size: tuple, dtype: torch.dtype)}\n \"\"\"\n iobytes = 0\n for _, tensor_prop in tensor_props.items():\n size, dtype = tensor_prop[0], tensor_prop[1]\n if isinstance(size, tuple):\n iobytes += np.prod(size) * dtype.itemsize\n else:\n iobytes += size * dtype.itemsize\n return int(iobytes)\n\n\nclass NVFBenchmark:","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.compute_total_iobytes","uri":"program://Fuser/function/benchmarks.python.core.compute_total_iobytes#L78-L92","kind":"function","name":"compute_total_iobytes","path":"benchmarks/python/core.py","language":"python","start_line":78,"end_line":92,"context_start_line":58,"context_end_line":112,"code":"# Backward function for torch baseline benchmarks.\n# The first two inputs are expected to be out and grad_out. The remaining are inputs of the forward pass used to clear grad between subsequent runs to avoid grad accumulation. See setup() in run_benchmark().\ndef unary_bwd_torch(inputs: List): # [output, grad_out, fwd_inputs]\n inputs[0].backward(inputs[1], retain_graph=True)\n\n\ndef with_executor(executor: str, fwd_fn: Callable, **kwargs) -> Callable:\n assert executor in [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n if executor == \"eager\":\n return fwd_fn\n if executor == \"torchcompile\":\n return torch.compile(fwd_fn, **kwargs)\n if executor == \"thunder\":\n return thunder.jit(\n fwd_fn, nv_enable_bookend=False, executors=[nvfuserex], **kwargs\n )\n if executor == \"thunder-torchcompile\":\n return thunder.jit(fwd_fn, executors=[\"torchcompile\"], **kwargs)\n\n\ndef compute_total_iobytes(\n tensor_props: dict[str, tuple[int | tuple[int, ...], torch.dtype]],\n):\n \"\"\"\n Compute IObytes for baselines from given description:\n Tensor_props has entries of the form: {'tensor_id': (size: tuple, dtype: torch.dtype)}\n \"\"\"\n iobytes = 0\n for _, tensor_prop in tensor_props.items():\n size, dtype = tensor_prop[0], tensor_prop[1]\n if isinstance(size, tuple):\n iobytes += np.prod(size) * dtype.itemsize\n else:\n iobytes += size * dtype.itemsize\n return int(iobytes)\n\n\nclass NVFBenchmark:\n \"\"\"\n A wrapper class around pytest-benchmark to support\n torchprofiler-based timer and metric computation.\n \"\"\"\n\n def __init__(\n self, benchmark_fixture, device: str = \"cuda\", precision: float = 1e-6\n ):\n \"\"\"\n Arguments:\n benchmark_fixture: pytest-benchmark fixture passed to every\n function intended to be run as a benchmark by pytest\n precision: Precision for the torchprofiler-based timer used.\n Set explicitly to avoid timer calibration.\n\n Class members:\n self.device: Device type -- \"cuda\" or \"host\"","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.NVFBenchmark","uri":"program://Fuser/class/benchmarks.python.core.NVFBenchmark#L95-L202","kind":"class","name":"NVFBenchmark","path":"benchmarks/python/core.py","language":"python","start_line":95,"end_line":202,"context_start_line":75,"context_end_line":222,"code":" return thunder.jit(fwd_fn, executors=[\"torchcompile\"], **kwargs)\n\n\ndef compute_total_iobytes(\n tensor_props: dict[str, tuple[int | tuple[int, ...], torch.dtype]],\n):\n \"\"\"\n Compute IObytes for baselines from given description:\n Tensor_props has entries of the form: {'tensor_id': (size: tuple, dtype: torch.dtype)}\n \"\"\"\n iobytes = 0\n for _, tensor_prop in tensor_props.items():\n size, dtype = tensor_prop[0], tensor_prop[1]\n if isinstance(size, tuple):\n iobytes += np.prod(size) * dtype.itemsize\n else:\n iobytes += size * dtype.itemsize\n return int(iobytes)\n\n\nclass NVFBenchmark:\n \"\"\"\n A wrapper class around pytest-benchmark to support\n torchprofiler-based timer and metric computation.\n \"\"\"\n\n def __init__(\n self, benchmark_fixture, device: str = \"cuda\", precision: float = 1e-6\n ):\n \"\"\"\n Arguments:\n benchmark_fixture: pytest-benchmark fixture passed to every\n function intended to be run as a benchmark by pytest\n precision: Precision for the torchprofiler-based timer used.\n Set explicitly to avoid timer calibration.\n\n Class members:\n self.device: Device type -- \"cuda\" or \"host\"\n self.benchmark: Underlying pytest-benchmark fixture\n \"\"\"\n self.device = device\n self._setup_timer(benchmark_fixture, device, precision)\n self.benchmark = benchmark_fixture\n\n def _setup_timer(self, benchmark_fixture, device: str, precision: float):\n \"\"\"Setup the appropriate timer based on device type.\"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n warnings.warn(\n \"NSYS is enabled. No profiler will be used and pytest will report wall-clock time. \"\n \"Please refer to the nsys report for accurate timings.\"\n )\n return\n\n # Timer selection based on device\n timer_class = CuptiTimer if device == \"cuda\" else FusionProfileTimer\n benchmark_fixture._timer = timer_class()\n # Externally set the precision to avoid timer calibration. Since the timer uses CUDA times,\n # calibration using subsequent timer calls produces invalid results.\n # https://github.com/ionelmc/pytest-benchmark/blob/728752d2976ef53fde7e40beb3e55f09cf4d4736/src/pytest_benchmark/timers.py#L15\n benchmark_fixture._precisions[benchmark_fixture._timer] = precision\n\n def __call__(self, function_to_benchmark: Callable, *args, **kwargs):\n return self.benchmark(function_to_benchmark, *args, **kwargs)\n\n def __getattr__(self, attr):\n if attr not in self.__dict__:\n return getattr(self.benchmark, attr)\n return super().__getattr__(attr)\n\n def set_fd(self, fd):\n \"\"\"\n Set the fd object for fusion profiling.\n fd is returned by setup() for host benchmarking.\n \"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n return\n assert isinstance(self._timer, FusionProfileTimer)\n self._timer.set_fd(fd)\n\n def cleanup(self):\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n self._timer.cleanup()\n\n def set_metrics(\n self,\n inputs: Union[torch.Tensor, List],\n outputs: Union[torch.Tensor, List],\n iobytes: int = None,\n ) -> None:\n \"\"\"\n Compute metrics for the target function when device = \"cuda\".\n\n Args:\n inputs: Inputs to the target function\n outputs: Outputs of the target function\n iobytes (Optional): When given, IO bytes computation is skipped\n and this is used to compute the metrics.\n\n Current metrics:\n IOBytes: Total bytes in inputs + outputs\n BytesPerSecond: IOBytes * total_rounds / total_time\n Bandwdith (GBps): BytesPerSecond / 1e9\n % Peak Bandwidth (SOL): 100 * Bandwidth /PEAK_BANDWIDTH\n \"\"\"\n if not iobytes:\n if not isinstance(inputs, Iterable) or isinstance(inputs, torch.Tensor):\n inputs = [inputs]\n if not isinstance(outputs, Iterable) or isinstance(outputs, torch.Tensor):\n outputs = [outputs]\n\n iobytes = 0\n for inp in inputs:\n if isinstance(inp, torch.Tensor):\n iobytes += inp.element_size() * inp.numel()\n\n for out in outputs:\n if isinstance(out, torch.Tensor):\n iobytes += out.element_size() * out.numel()\n\n self.benchmark.extra_info[\"IOBytes\"] = iobytes\n bandwidth_bps = (\n iobytes * self.benchmark.stats[\"rounds\"]\n ) / self.benchmark.stats[\"total\"]\n self.benchmark.extra_info[\"Bandwidth (Bps)\"] = bandwidth_bps\n self.benchmark.extra_info[\"Bandwidth (GBps)\"] = bandwidth_bps / 1e9\n self.benchmark.extra_info[\"% Peak Bandwidth (SOL)\"] = (\n 100 * (bandwidth_bps / 1e9) / PEAK_BANDWIDTH_GBPS\n )\n\n\ndef run_benchmark(\n benchmark: pytest_benchmark.fixture.BenchmarkFixture,\n benchmark_fn: Callable | None,\n inputs: Union[torch.Tensor, List],\n iobytes: int = None,\n device: str = \"cuda\",\n fusion_fn: Callable = None,\n) -> Union[torch.Tensor, List]:\n \"\"\"\n Benchmarks the target function using torchprofiler and stores metrics as extra information.\n\n Arguments:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Target function\n inputs: Inputs to the target function\n iobytes (Optional): When given, IO bytes computation is skipped\n and this is used to compute SOL and bandwidth.\n device (Optional): Default: CUDA, Possible values: [\"cuda\", \"host\"].","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.run_benchmark","uri":"program://Fuser/function/benchmarks.python.core.run_benchmark#L205-L344","kind":"function","name":"run_benchmark","path":"benchmarks/python/core.py","language":"python","start_line":205,"end_line":344,"context_start_line":185,"context_end_line":344,"code":" iobytes = 0\n for inp in inputs:\n if isinstance(inp, torch.Tensor):\n iobytes += inp.element_size() * inp.numel()\n\n for out in outputs:\n if isinstance(out, torch.Tensor):\n iobytes += out.element_size() * out.numel()\n\n self.benchmark.extra_info[\"IOBytes\"] = iobytes\n bandwidth_bps = (\n iobytes * self.benchmark.stats[\"rounds\"]\n ) / self.benchmark.stats[\"total\"]\n self.benchmark.extra_info[\"Bandwidth (Bps)\"] = bandwidth_bps\n self.benchmark.extra_info[\"Bandwidth (GBps)\"] = bandwidth_bps / 1e9\n self.benchmark.extra_info[\"% Peak Bandwidth (SOL)\"] = (\n 100 * (bandwidth_bps / 1e9) / PEAK_BANDWIDTH_GBPS\n )\n\n\ndef run_benchmark(\n benchmark: pytest_benchmark.fixture.BenchmarkFixture,\n benchmark_fn: Callable | None,\n inputs: Union[torch.Tensor, List],\n iobytes: int = None,\n device: str = \"cuda\",\n fusion_fn: Callable = None,\n) -> Union[torch.Tensor, List]:\n \"\"\"\n Benchmarks the target function using torchprofiler and stores metrics as extra information.\n\n Arguments:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Target function\n inputs: Inputs to the target function\n iobytes (Optional): When given, IO bytes computation is skipped\n and this is used to compute SOL and bandwidth.\n device (Optional): Default: CUDA, Possible values: [\"cuda\", \"host\"].\n Using device=\"host\" is only allowed with nvFuser FusionDefinition.\n fusion_fn (Optional): Must be provided if device = \"host\".\n fusion_fn should only require FusionDefinition() as the input.\n Use functools.partial if fusion_fn accepts additional arguments.\n See test_many_pointwise_ops.py for example.\n\n Returns:\n outputs: Output of the target function\n \"\"\"\n\n # Check that the device is `cuda` or `host:{compile/steady/dynamic}`.\n assert device.split(\":\")[0] in [\n \"cuda\",\n \"host\",\n ], f'Unsupported device type: {device.split(\":\")[0]}. Use one of cuda/host.'\n\n host_bench_mode = None\n\n # Store warmup rounds locally to modify for host:steady/dynamic cases.\n warmup_rounds = BENCHMARK_CONFIG[\"warmup_rounds\"]\n\n if device.split(\":\")[0] == \"host\":\n # Host benchmarking expects a fusion function to generate fusion definitions everytime FusionCache is reset.\n assert fusion_fn is not None and benchmark_fn is None\n\n # device = 'host:compile', 'host:steady', 'host:dyanamic'\n # Set the host_bench_mode -- The 3 modes require different setup calls.\n host_bench_mode = device.split(\":\")[-1]\n device = device.split(\":\")[0] # device = 'host'\n\n # Set the warmup rounds if required for `steady/dynamic` host latency measurement.\n if (\n host_bench_mode in [\"steady\", \"dynamic\"]\n and BENCHMARK_CONFIG[\"warmup_rounds\"] == 0\n ):\n # By default, warmup_rounds=1. If BENCHMARK_CONFIG['warmup_rounds'] == 0 through --benchmark-warmup-rounds, raise a warning that it was ignored.\n warnings.warn(\n \"--benchmark-warmup-rounds=0 is ignored for host:steady/dynamic benchmarking. Setting warmup_rounds=1.\"\n )\n warmup_rounds = 1\n\n \"\"\"\n Setup function: This is called before each benchmarking round. This function is used to:\n 1. Clear L2 cache.\n 2. For host latency benchmarks, the 3 modes use different setups.\n a) 'compile': FusionCache is reset at every round to measure the first time overhead before instantiating fd.\n b) 'steady': Nothing additional is required. The warmup round avoids including the first time overhead in the measurements.\n c) 'dynamic': We maintain a global counter to track which input is executed. Once all the inputs have been executed once,\n the FusionCache is reset again and we execute fd for the first input to avoid including the first time compile overhead in the dynamic measurement.\n \"\"\"\n\n # Counter used in `dynamic` host latency benchmarking, unused in other cases.\n global counter\n counter = 0\n\n def setup():\n clear_l2_cache()\n if device == \"cuda\":\n for inp in inputs:\n if isinstance(inp, torch.Tensor):\n inp.grad = None\n return [inputs], {}\n\n # Device = 'host'\n # For device='host', we use the host_benchmark_fn below. It expects a list of fusion inputs, and the fd object.\n assert host_bench_mode in [\n \"compile\",\n \"steady\",\n \"dynamic\",\n ], f\"Expected host benchmark mode to be one of compile, steady, or dynamic, found {host_bench_mode}\"\n\n # Instantiate the fusion definition\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n if host_bench_mode in [\"compile\"]:\n return [inputs], {\"fd\": fd}\n\n if host_bench_mode in [\"steady\"]:\n # Run once to compile FusionExecutorCache and avoid measuring first time overhead.\n fd.execute(inputs)\n return [inputs], {\"fd\": fd}\n\n # For dynamic host latency benchmarking, return a particular input shape, and reset FusionCache if all inputs have been executed.\n global counter\n counter += 1\n # The current input is counter % len(inputs). Execute fd with next input\n # to avoid measuring first time overhead but avoid cache hit with current input.\n fd.execute(inputs[(counter + 1) % len(inputs)])\n return [inputs[counter % len(inputs)]], {\"fd\": fd}\n\n # Create an instance of NVFBenchmark\n nvf_benchmark = NVFBenchmark(benchmark, device=device)\n\n # The host_benchmark_fn uses the `fd` object returned from setup function.\n def host_benchmark_fn(inputs, fd):\n # Set the fd variable used to query the profile object\n nvf_benchmark.set_fd(fd)\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n with PythonProfiler() as prof:\n return fd.execute(inputs)\n return fd.execute(inputs)\n\n benchmark_fn = benchmark_fn if benchmark_fn is not None else host_benchmark_fn\n\n try:\n outputs = nvf_benchmark.pedantic(\n benchmark_fn,\n setup=setup,\n rounds=BENCHMARK_CONFIG[\"rounds\"],\n warmup_rounds=warmup_rounds,\n )\n if device == \"cuda\":\n # Record additional metrics (IOBytes, Bandwidth)\n nvf_benchmark.set_metrics(inputs, outputs, iobytes)\n return outputs\n except Exception as e:\n raise RuntimeError(\n f\"Exception when running {benchmark_fn.__name__}: {e}\"\n ) from e\n finally:\n nvf_benchmark.cleanup()","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.__init__","uri":"program://Fuser/function/benchmarks.python.core.__init__#L101-L117","kind":"function","name":"__init__","path":"benchmarks/python/core.py","language":"python","start_line":101,"end_line":117,"context_start_line":81,"context_end_line":137,"code":" \"\"\"\n Compute IObytes for baselines from given description:\n Tensor_props has entries of the form: {'tensor_id': (size: tuple, dtype: torch.dtype)}\n \"\"\"\n iobytes = 0\n for _, tensor_prop in tensor_props.items():\n size, dtype = tensor_prop[0], tensor_prop[1]\n if isinstance(size, tuple):\n iobytes += np.prod(size) * dtype.itemsize\n else:\n iobytes += size * dtype.itemsize\n return int(iobytes)\n\n\nclass NVFBenchmark:\n \"\"\"\n A wrapper class around pytest-benchmark to support\n torchprofiler-based timer and metric computation.\n \"\"\"\n\n def __init__(\n self, benchmark_fixture, device: str = \"cuda\", precision: float = 1e-6\n ):\n \"\"\"\n Arguments:\n benchmark_fixture: pytest-benchmark fixture passed to every\n function intended to be run as a benchmark by pytest\n precision: Precision for the torchprofiler-based timer used.\n Set explicitly to avoid timer calibration.\n\n Class members:\n self.device: Device type -- \"cuda\" or \"host\"\n self.benchmark: Underlying pytest-benchmark fixture\n \"\"\"\n self.device = device\n self._setup_timer(benchmark_fixture, device, precision)\n self.benchmark = benchmark_fixture\n\n def _setup_timer(self, benchmark_fixture, device: str, precision: float):\n \"\"\"Setup the appropriate timer based on device type.\"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n warnings.warn(\n \"NSYS is enabled. No profiler will be used and pytest will report wall-clock time. \"\n \"Please refer to the nsys report for accurate timings.\"\n )\n return\n\n # Timer selection based on device\n timer_class = CuptiTimer if device == \"cuda\" else FusionProfileTimer\n benchmark_fixture._timer = timer_class()\n # Externally set the precision to avoid timer calibration. Since the timer uses CUDA times,\n # calibration using subsequent timer calls produces invalid results.\n # https://github.com/ionelmc/pytest-benchmark/blob/728752d2976ef53fde7e40beb3e55f09cf4d4736/src/pytest_benchmark/timers.py#L15\n benchmark_fixture._precisions[benchmark_fixture._timer] = precision\n\n def __call__(self, function_to_benchmark: Callable, *args, **kwargs):\n return self.benchmark(function_to_benchmark, *args, **kwargs)","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core._setup_timer","uri":"program://Fuser/function/benchmarks.python.core._setup_timer#L119-L134","kind":"function","name":"_setup_timer","path":"benchmarks/python/core.py","language":"python","start_line":119,"end_line":134,"context_start_line":99,"context_end_line":154,"code":" \"\"\"\n\n def __init__(\n self, benchmark_fixture, device: str = \"cuda\", precision: float = 1e-6\n ):\n \"\"\"\n Arguments:\n benchmark_fixture: pytest-benchmark fixture passed to every\n function intended to be run as a benchmark by pytest\n precision: Precision for the torchprofiler-based timer used.\n Set explicitly to avoid timer calibration.\n\n Class members:\n self.device: Device type -- \"cuda\" or \"host\"\n self.benchmark: Underlying pytest-benchmark fixture\n \"\"\"\n self.device = device\n self._setup_timer(benchmark_fixture, device, precision)\n self.benchmark = benchmark_fixture\n\n def _setup_timer(self, benchmark_fixture, device: str, precision: float):\n \"\"\"Setup the appropriate timer based on device type.\"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n warnings.warn(\n \"NSYS is enabled. No profiler will be used and pytest will report wall-clock time. \"\n \"Please refer to the nsys report for accurate timings.\"\n )\n return\n\n # Timer selection based on device\n timer_class = CuptiTimer if device == \"cuda\" else FusionProfileTimer\n benchmark_fixture._timer = timer_class()\n # Externally set the precision to avoid timer calibration. Since the timer uses CUDA times,\n # calibration using subsequent timer calls produces invalid results.\n # https://github.com/ionelmc/pytest-benchmark/blob/728752d2976ef53fde7e40beb3e55f09cf4d4736/src/pytest_benchmark/timers.py#L15\n benchmark_fixture._precisions[benchmark_fixture._timer] = precision\n\n def __call__(self, function_to_benchmark: Callable, *args, **kwargs):\n return self.benchmark(function_to_benchmark, *args, **kwargs)\n\n def __getattr__(self, attr):\n if attr not in self.__dict__:\n return getattr(self.benchmark, attr)\n return super().__getattr__(attr)\n\n def set_fd(self, fd):\n \"\"\"\n Set the fd object for fusion profiling.\n fd is returned by setup() for host benchmarking.\n \"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n return\n assert isinstance(self._timer, FusionProfileTimer)\n self._timer.set_fd(fd)\n\n def cleanup(self):","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.__call__","uri":"program://Fuser/function/benchmarks.python.core.__call__#L136-L137","kind":"function","name":"__call__","path":"benchmarks/python/core.py","language":"python","start_line":136,"end_line":137,"context_start_line":116,"context_end_line":157,"code":" self._setup_timer(benchmark_fixture, device, precision)\n self.benchmark = benchmark_fixture\n\n def _setup_timer(self, benchmark_fixture, device: str, precision: float):\n \"\"\"Setup the appropriate timer based on device type.\"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n warnings.warn(\n \"NSYS is enabled. No profiler will be used and pytest will report wall-clock time. \"\n \"Please refer to the nsys report for accurate timings.\"\n )\n return\n\n # Timer selection based on device\n timer_class = CuptiTimer if device == \"cuda\" else FusionProfileTimer\n benchmark_fixture._timer = timer_class()\n # Externally set the precision to avoid timer calibration. Since the timer uses CUDA times,\n # calibration using subsequent timer calls produces invalid results.\n # https://github.com/ionelmc/pytest-benchmark/blob/728752d2976ef53fde7e40beb3e55f09cf4d4736/src/pytest_benchmark/timers.py#L15\n benchmark_fixture._precisions[benchmark_fixture._timer] = precision\n\n def __call__(self, function_to_benchmark: Callable, *args, **kwargs):\n return self.benchmark(function_to_benchmark, *args, **kwargs)\n\n def __getattr__(self, attr):\n if attr not in self.__dict__:\n return getattr(self.benchmark, attr)\n return super().__getattr__(attr)\n\n def set_fd(self, fd):\n \"\"\"\n Set the fd object for fusion profiling.\n fd is returned by setup() for host benchmarking.\n \"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n return\n assert isinstance(self._timer, FusionProfileTimer)\n self._timer.set_fd(fd)\n\n def cleanup(self):\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n self._timer.cleanup()\n","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.__getattr__","uri":"program://Fuser/function/benchmarks.python.core.__getattr__#L139-L142","kind":"function","name":"__getattr__","path":"benchmarks/python/core.py","language":"python","start_line":139,"end_line":142,"context_start_line":119,"context_end_line":162,"code":" def _setup_timer(self, benchmark_fixture, device: str, precision: float):\n \"\"\"Setup the appropriate timer based on device type.\"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n warnings.warn(\n \"NSYS is enabled. No profiler will be used and pytest will report wall-clock time. \"\n \"Please refer to the nsys report for accurate timings.\"\n )\n return\n\n # Timer selection based on device\n timer_class = CuptiTimer if device == \"cuda\" else FusionProfileTimer\n benchmark_fixture._timer = timer_class()\n # Externally set the precision to avoid timer calibration. Since the timer uses CUDA times,\n # calibration using subsequent timer calls produces invalid results.\n # https://github.com/ionelmc/pytest-benchmark/blob/728752d2976ef53fde7e40beb3e55f09cf4d4736/src/pytest_benchmark/timers.py#L15\n benchmark_fixture._precisions[benchmark_fixture._timer] = precision\n\n def __call__(self, function_to_benchmark: Callable, *args, **kwargs):\n return self.benchmark(function_to_benchmark, *args, **kwargs)\n\n def __getattr__(self, attr):\n if attr not in self.__dict__:\n return getattr(self.benchmark, attr)\n return super().__getattr__(attr)\n\n def set_fd(self, fd):\n \"\"\"\n Set the fd object for fusion profiling.\n fd is returned by setup() for host benchmarking.\n \"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n return\n assert isinstance(self._timer, FusionProfileTimer)\n self._timer.set_fd(fd)\n\n def cleanup(self):\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n self._timer.cleanup()\n\n def set_metrics(\n self,\n inputs: Union[torch.Tensor, List],\n outputs: Union[torch.Tensor, List],\n iobytes: int = None,","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.set_fd","uri":"program://Fuser/function/benchmarks.python.core.set_fd#L144-L152","kind":"function","name":"set_fd","path":"benchmarks/python/core.py","language":"python","start_line":144,"end_line":152,"context_start_line":124,"context_end_line":172,"code":" \"Please refer to the nsys report for accurate timings.\"\n )\n return\n\n # Timer selection based on device\n timer_class = CuptiTimer if device == \"cuda\" else FusionProfileTimer\n benchmark_fixture._timer = timer_class()\n # Externally set the precision to avoid timer calibration. Since the timer uses CUDA times,\n # calibration using subsequent timer calls produces invalid results.\n # https://github.com/ionelmc/pytest-benchmark/blob/728752d2976ef53fde7e40beb3e55f09cf4d4736/src/pytest_benchmark/timers.py#L15\n benchmark_fixture._precisions[benchmark_fixture._timer] = precision\n\n def __call__(self, function_to_benchmark: Callable, *args, **kwargs):\n return self.benchmark(function_to_benchmark, *args, **kwargs)\n\n def __getattr__(self, attr):\n if attr not in self.__dict__:\n return getattr(self.benchmark, attr)\n return super().__getattr__(attr)\n\n def set_fd(self, fd):\n \"\"\"\n Set the fd object for fusion profiling.\n fd is returned by setup() for host benchmarking.\n \"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n return\n assert isinstance(self._timer, FusionProfileTimer)\n self._timer.set_fd(fd)\n\n def cleanup(self):\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n self._timer.cleanup()\n\n def set_metrics(\n self,\n inputs: Union[torch.Tensor, List],\n outputs: Union[torch.Tensor, List],\n iobytes: int = None,\n ) -> None:\n \"\"\"\n Compute metrics for the target function when device = \"cuda\".\n\n Args:\n inputs: Inputs to the target function\n outputs: Outputs of the target function\n iobytes (Optional): When given, IO bytes computation is skipped\n and this is used to compute the metrics.\n","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.cleanup","uri":"program://Fuser/function/benchmarks.python.core.cleanup#L154-L156","kind":"function","name":"cleanup","path":"benchmarks/python/core.py","language":"python","start_line":154,"end_line":156,"context_start_line":134,"context_end_line":176,"code":" benchmark_fixture._precisions[benchmark_fixture._timer] = precision\n\n def __call__(self, function_to_benchmark: Callable, *args, **kwargs):\n return self.benchmark(function_to_benchmark, *args, **kwargs)\n\n def __getattr__(self, attr):\n if attr not in self.__dict__:\n return getattr(self.benchmark, attr)\n return super().__getattr__(attr)\n\n def set_fd(self, fd):\n \"\"\"\n Set the fd object for fusion profiling.\n fd is returned by setup() for host benchmarking.\n \"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n return\n assert isinstance(self._timer, FusionProfileTimer)\n self._timer.set_fd(fd)\n\n def cleanup(self):\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n self._timer.cleanup()\n\n def set_metrics(\n self,\n inputs: Union[torch.Tensor, List],\n outputs: Union[torch.Tensor, List],\n iobytes: int = None,\n ) -> None:\n \"\"\"\n Compute metrics for the target function when device = \"cuda\".\n\n Args:\n inputs: Inputs to the target function\n outputs: Outputs of the target function\n iobytes (Optional): When given, IO bytes computation is skipped\n and this is used to compute the metrics.\n\n Current metrics:\n IOBytes: Total bytes in inputs + outputs\n BytesPerSecond: IOBytes * total_rounds / total_time\n Bandwdith (GBps): BytesPerSecond / 1e9","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.set_metrics","uri":"program://Fuser/function/benchmarks.python.core.set_metrics#L158-L202","kind":"function","name":"set_metrics","path":"benchmarks/python/core.py","language":"python","start_line":158,"end_line":202,"context_start_line":138,"context_end_line":222,"code":"\n def __getattr__(self, attr):\n if attr not in self.__dict__:\n return getattr(self.benchmark, attr)\n return super().__getattr__(attr)\n\n def set_fd(self, fd):\n \"\"\"\n Set the fd object for fusion profiling.\n fd is returned by setup() for host benchmarking.\n \"\"\"\n if BENCHMARK_CONFIG[\"with_nsys\"]:\n return\n assert isinstance(self._timer, FusionProfileTimer)\n self._timer.set_fd(fd)\n\n def cleanup(self):\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n self._timer.cleanup()\n\n def set_metrics(\n self,\n inputs: Union[torch.Tensor, List],\n outputs: Union[torch.Tensor, List],\n iobytes: int = None,\n ) -> None:\n \"\"\"\n Compute metrics for the target function when device = \"cuda\".\n\n Args:\n inputs: Inputs to the target function\n outputs: Outputs of the target function\n iobytes (Optional): When given, IO bytes computation is skipped\n and this is used to compute the metrics.\n\n Current metrics:\n IOBytes: Total bytes in inputs + outputs\n BytesPerSecond: IOBytes * total_rounds / total_time\n Bandwdith (GBps): BytesPerSecond / 1e9\n % Peak Bandwidth (SOL): 100 * Bandwidth /PEAK_BANDWIDTH\n \"\"\"\n if not iobytes:\n if not isinstance(inputs, Iterable) or isinstance(inputs, torch.Tensor):\n inputs = [inputs]\n if not isinstance(outputs, Iterable) or isinstance(outputs, torch.Tensor):\n outputs = [outputs]\n\n iobytes = 0\n for inp in inputs:\n if isinstance(inp, torch.Tensor):\n iobytes += inp.element_size() * inp.numel()\n\n for out in outputs:\n if isinstance(out, torch.Tensor):\n iobytes += out.element_size() * out.numel()\n\n self.benchmark.extra_info[\"IOBytes\"] = iobytes\n bandwidth_bps = (\n iobytes * self.benchmark.stats[\"rounds\"]\n ) / self.benchmark.stats[\"total\"]\n self.benchmark.extra_info[\"Bandwidth (Bps)\"] = bandwidth_bps\n self.benchmark.extra_info[\"Bandwidth (GBps)\"] = bandwidth_bps / 1e9\n self.benchmark.extra_info[\"% Peak Bandwidth (SOL)\"] = (\n 100 * (bandwidth_bps / 1e9) / PEAK_BANDWIDTH_GBPS\n )\n\n\ndef run_benchmark(\n benchmark: pytest_benchmark.fixture.BenchmarkFixture,\n benchmark_fn: Callable | None,\n inputs: Union[torch.Tensor, List],\n iobytes: int = None,\n device: str = \"cuda\",\n fusion_fn: Callable = None,\n) -> Union[torch.Tensor, List]:\n \"\"\"\n Benchmarks the target function using torchprofiler and stores metrics as extra information.\n\n Arguments:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Target function\n inputs: Inputs to the target function\n iobytes (Optional): When given, IO bytes computation is skipped\n and this is used to compute SOL and bandwidth.\n device (Optional): Default: CUDA, Possible values: [\"cuda\", \"host\"].","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.setup","uri":"program://Fuser/function/benchmarks.python.core.setup#L278-L312","kind":"function","name":"setup","path":"benchmarks/python/core.py","language":"python","start_line":278,"end_line":312,"context_start_line":258,"context_end_line":332,"code":" # By default, warmup_rounds=1. If BENCHMARK_CONFIG['warmup_rounds'] == 0 through --benchmark-warmup-rounds, raise a warning that it was ignored.\n warnings.warn(\n \"--benchmark-warmup-rounds=0 is ignored for host:steady/dynamic benchmarking. Setting warmup_rounds=1.\"\n )\n warmup_rounds = 1\n\n \"\"\"\n Setup function: This is called before each benchmarking round. This function is used to:\n 1. Clear L2 cache.\n 2. For host latency benchmarks, the 3 modes use different setups.\n a) 'compile': FusionCache is reset at every round to measure the first time overhead before instantiating fd.\n b) 'steady': Nothing additional is required. The warmup round avoids including the first time overhead in the measurements.\n c) 'dynamic': We maintain a global counter to track which input is executed. Once all the inputs have been executed once,\n the FusionCache is reset again and we execute fd for the first input to avoid including the first time compile overhead in the dynamic measurement.\n \"\"\"\n\n # Counter used in `dynamic` host latency benchmarking, unused in other cases.\n global counter\n counter = 0\n\n def setup():\n clear_l2_cache()\n if device == \"cuda\":\n for inp in inputs:\n if isinstance(inp, torch.Tensor):\n inp.grad = None\n return [inputs], {}\n\n # Device = 'host'\n # For device='host', we use the host_benchmark_fn below. It expects a list of fusion inputs, and the fd object.\n assert host_bench_mode in [\n \"compile\",\n \"steady\",\n \"dynamic\",\n ], f\"Expected host benchmark mode to be one of compile, steady, or dynamic, found {host_bench_mode}\"\n\n # Instantiate the fusion definition\n with FusionDefinition() as fd:\n fusion_fn(fd)\n\n if host_bench_mode in [\"compile\"]:\n return [inputs], {\"fd\": fd}\n\n if host_bench_mode in [\"steady\"]:\n # Run once to compile FusionExecutorCache and avoid measuring first time overhead.\n fd.execute(inputs)\n return [inputs], {\"fd\": fd}\n\n # For dynamic host latency benchmarking, return a particular input shape, and reset FusionCache if all inputs have been executed.\n global counter\n counter += 1\n # The current input is counter % len(inputs). Execute fd with next input\n # to avoid measuring first time overhead but avoid cache hit with current input.\n fd.execute(inputs[(counter + 1) % len(inputs)])\n return [inputs[counter % len(inputs)]], {\"fd\": fd}\n\n # Create an instance of NVFBenchmark\n nvf_benchmark = NVFBenchmark(benchmark, device=device)\n\n # The host_benchmark_fn uses the `fd` object returned from setup function.\n def host_benchmark_fn(inputs, fd):\n # Set the fd variable used to query the profile object\n nvf_benchmark.set_fd(fd)\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n with PythonProfiler() as prof:\n return fd.execute(inputs)\n return fd.execute(inputs)\n\n benchmark_fn = benchmark_fn if benchmark_fn is not None else host_benchmark_fn\n\n try:\n outputs = nvf_benchmark.pedantic(\n benchmark_fn,\n setup=setup,\n rounds=BENCHMARK_CONFIG[\"rounds\"],","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.core.host_benchmark_fn","uri":"program://Fuser/function/benchmarks.python.core.host_benchmark_fn#L318-L324","kind":"function","name":"host_benchmark_fn","path":"benchmarks/python/core.py","language":"python","start_line":318,"end_line":324,"context_start_line":298,"context_end_line":344,"code":" if host_bench_mode in [\"compile\"]:\n return [inputs], {\"fd\": fd}\n\n if host_bench_mode in [\"steady\"]:\n # Run once to compile FusionExecutorCache and avoid measuring first time overhead.\n fd.execute(inputs)\n return [inputs], {\"fd\": fd}\n\n # For dynamic host latency benchmarking, return a particular input shape, and reset FusionCache if all inputs have been executed.\n global counter\n counter += 1\n # The current input is counter % len(inputs). Execute fd with next input\n # to avoid measuring first time overhead but avoid cache hit with current input.\n fd.execute(inputs[(counter + 1) % len(inputs)])\n return [inputs[counter % len(inputs)]], {\"fd\": fd}\n\n # Create an instance of NVFBenchmark\n nvf_benchmark = NVFBenchmark(benchmark, device=device)\n\n # The host_benchmark_fn uses the `fd` object returned from setup function.\n def host_benchmark_fn(inputs, fd):\n # Set the fd variable used to query the profile object\n nvf_benchmark.set_fd(fd)\n if not BENCHMARK_CONFIG[\"with_nsys\"]:\n with PythonProfiler() as prof:\n return fd.execute(inputs)\n return fd.execute(inputs)\n\n benchmark_fn = benchmark_fn if benchmark_fn is not None else host_benchmark_fn\n\n try:\n outputs = nvf_benchmark.pedantic(\n benchmark_fn,\n setup=setup,\n rounds=BENCHMARK_CONFIG[\"rounds\"],\n warmup_rounds=warmup_rounds,\n )\n if device == \"cuda\":\n # Record additional metrics (IOBytes, Bandwidth)\n nvf_benchmark.set_metrics(inputs, outputs, iobytes)\n return outputs\n except Exception as e:\n raise RuntimeError(\n f\"Exception when running {benchmark_fn.__name__}: {e}\"\n ) from e\n finally:\n nvf_benchmark.cleanup()","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_bwd","uri":"program://Fuser/module/benchmarks.python.test_softmax_bwd#L1-L139","kind":"module","name":"benchmarks.python.test_softmax_bwd","path":"benchmarks/python/test_softmax_bwd.py","language":"python","start_line":1,"end_line":139,"context_start_line":1,"context_end_line":139,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nimport numpy as np\nfrom .torch_ops import softmax\n\n\ndef softmax_bwd_fusion(\n fd: FusionDefinition, dtype: DataType, reduction_axis: int\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n\n if dtype is not DataType.Float:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n\n T4 = fd.ops.mul(T0, T1)\n T5 = fd.ops.sum(T4, dims=[reduction_axis], keepdim=False, dtype=DataType.Null)\n\n if reduction_axis:\n shape_v9 = [T0.size(0), 1]\n else:\n shape_v9 = [1, T0.size(1)]\n bcast_dim = 1 - reduction_axis\n\n T10 = fd.ops.broadcast_in_dim(T5, shape=shape_v9, broadcast_dims=[bcast_dim])\n\n if dtype is not DataType.Float:\n T10 = fd.ops.cast(T10, dtype=dtype)\n\n T16 = fd.ops.broadcast_in_dim(\n T10, shape=[T0.size(0), T0.size(1)], broadcast_dims=[0, 1]\n )\n\n if dtype is not DataType.Float:\n T16 = fd.ops.cast(T16, dtype=DataType.Float)\n\n T18 = fd.ops.sub(T1, T16)\n T19 = fd.ops.mul(T0, T18)\n\n if dtype is not DataType.Float:\n T19 = fd.ops.cast(T19, dtype=dtype)\n fd.add_output(T19)\n\n\ndef softmax_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = output + grad_out + grad_input\n return int(np.prod(size) * dtype.itemsize * 3)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(size, device=\"cuda\", dtype=dtype),\n ]\n\n with FusionDefinition() as fd:\n softmax_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis)\n\n if not disable_validation:\n eager_output = torch.nn.functional.softmax(inputs[0], dim=reduction_axis)\n eager_output.backward(inputs[1])\n fd.validate([eager_output, inputs[1]], [inputs[0].grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n fwd_fn = with_executor(executor, softmax)\n fwd_inputs = [inputs, reduction_axis]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=softmax_bwd_iobytes(size, dtype),\n )","source_hash":"e1c6c85334ae83b4451a8ece69991d26b0fc42a3243aeb6477c4c06eeaca957d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_bwd.softmax_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_softmax_bwd.softmax_bwd_fusion#L20-L66","kind":"function","name":"softmax_bwd_fusion","path":"benchmarks/python/test_softmax_bwd.py","language":"python","start_line":20,"end_line":66,"context_start_line":1,"context_end_line":86,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nimport numpy as np\nfrom .torch_ops import softmax\n\n\ndef softmax_bwd_fusion(\n fd: FusionDefinition, dtype: DataType, reduction_axis: int\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n\n if dtype is not DataType.Float:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n\n T4 = fd.ops.mul(T0, T1)\n T5 = fd.ops.sum(T4, dims=[reduction_axis], keepdim=False, dtype=DataType.Null)\n\n if reduction_axis:\n shape_v9 = [T0.size(0), 1]\n else:\n shape_v9 = [1, T0.size(1)]\n bcast_dim = 1 - reduction_axis\n\n T10 = fd.ops.broadcast_in_dim(T5, shape=shape_v9, broadcast_dims=[bcast_dim])\n\n if dtype is not DataType.Float:\n T10 = fd.ops.cast(T10, dtype=dtype)\n\n T16 = fd.ops.broadcast_in_dim(\n T10, shape=[T0.size(0), T0.size(1)], broadcast_dims=[0, 1]\n )\n\n if dtype is not DataType.Float:\n T16 = fd.ops.cast(T16, dtype=DataType.Float)\n\n T18 = fd.ops.sub(T1, T16)\n T19 = fd.ops.mul(T0, T18)\n\n if dtype is not DataType.Float:\n T19 = fd.ops.cast(T19, dtype=dtype)\n fd.add_output(T19)\n\n\ndef softmax_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = output + grad_out + grad_input\n return int(np.prod(size) * dtype.itemsize * 3)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,","source_hash":"e1c6c85334ae83b4451a8ece69991d26b0fc42a3243aeb6477c4c06eeaca957d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_bwd.softmax_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_softmax_bwd.softmax_bwd_iobytes#L69-L71","kind":"function","name":"softmax_bwd_iobytes","path":"benchmarks/python/test_softmax_bwd.py","language":"python","start_line":69,"end_line":71,"context_start_line":49,"context_end_line":91,"code":" T10 = fd.ops.broadcast_in_dim(T5, shape=shape_v9, broadcast_dims=[bcast_dim])\n\n if dtype is not DataType.Float:\n T10 = fd.ops.cast(T10, dtype=dtype)\n\n T16 = fd.ops.broadcast_in_dim(\n T10, shape=[T0.size(0), T0.size(1)], broadcast_dims=[0, 1]\n )\n\n if dtype is not DataType.Float:\n T16 = fd.ops.cast(T16, dtype=DataType.Float)\n\n T18 = fd.ops.sub(T1, T16)\n T19 = fd.ops.mul(T0, T18)\n\n if dtype is not DataType.Float:\n T19 = fd.ops.cast(T19, dtype=dtype)\n fd.add_output(T19)\n\n\ndef softmax_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = output + grad_out + grad_input\n return int(np.prod(size) * dtype.itemsize * 3)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [","source_hash":"e1c6c85334ae83b4451a8ece69991d26b0fc42a3243aeb6477c4c06eeaca957d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_bwd.test_softmax_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_softmax_bwd.test_softmax_bwd_nvf_benchmark#L83-L105","kind":"function","name":"test_softmax_bwd_nvf_benchmark","path":"benchmarks/python/test_softmax_bwd.py","language":"python","start_line":83,"end_line":105,"context_start_line":63,"context_end_line":125,"code":"\n if dtype is not DataType.Float:\n T19 = fd.ops.cast(T19, dtype=dtype)\n fd.add_output(T19)\n\n\ndef softmax_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = output + grad_out + grad_input\n return int(np.prod(size) * dtype.itemsize * 3)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(size, device=\"cuda\", dtype=dtype),\n ]\n\n with FusionDefinition() as fd:\n softmax_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis)\n\n if not disable_validation:\n eager_output = torch.nn.functional.softmax(inputs[0], dim=reduction_axis)\n eager_output.backward(inputs[1])\n fd.validate([eager_output, inputs[1]], [inputs[0].grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":","source_hash":"e1c6c85334ae83b4451a8ece69991d26b0fc42a3243aeb6477c4c06eeaca957d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_bwd.test_softmax_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_softmax_bwd.test_softmax_bwd_baseline_benchmark#L118-L139","kind":"function","name":"test_softmax_bwd_baseline_benchmark","path":"benchmarks/python/test_softmax_bwd.py","language":"python","start_line":118,"end_line":139,"context_start_line":98,"context_end_line":139,"code":"\n if not disable_validation:\n eager_output = torch.nn.functional.softmax(inputs[0], dim=reduction_axis)\n eager_output.backward(inputs[1])\n fd.validate([eager_output, inputs[1]], [inputs[0].grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n fwd_fn = with_executor(executor, softmax)\n fwd_inputs = [inputs, reduction_axis]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=softmax_bwd_iobytes(size, dtype),\n )","source_hash":"e1c6c85334ae83b4451a8ece69991d26b0fc42a3243aeb6477c4c06eeaca957d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss","uri":"program://Fuser/module/benchmarks.python.test_cross_entropy_loss#L1-L268","kind":"module","name":"benchmarks.python.test_cross_entropy_loss","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":1,"end_line":268,"context_start_line":1,"context_end_line":268,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\n\nimport torch\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom .core import (\n run_benchmark,\n with_executor,\n unary_bwd_torch,\n clear_dynamo_cache,\n check_module_available,\n)\nfrom .cross_entropy_loss import (\n cross_entropy_loss_setup,\n SyntheticMiniModel,\n)\nfrom .torch_ops import cross_entropy as torch_cross_entropy_fwd\n\n\nif check_module_available(\"quack\"):\n from quack.cross_entropy import cross_entropy_fwd as quack_cross_entropy_fwd\n\n\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\ndef test_cross_entropy_fwd_benchmark(\n benchmark,\n variation: str,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n test_case = cross_entropy_loss_setup[variation](dtype=torch.bfloat16)\n inputs = test_case.inputs()\n model = test_case.model()\n\n def fwd_call(inp):\n return model(**inp)\n\n # Compile the fwd fn for torchcompile\n benchmark_fn = with_executor(executor, fwd_call, **kwargs)\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\ndef test_cross_entropy_bwd_benchmark(\n benchmark,\n variation: str,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n test_case = cross_entropy_loss_setup[variation](dtype=torch.bfloat16)\n fwd_inputs = test_case.inputs()\n model = test_case.model()\n\n def fwd_call(inp):\n return model(**inp)\n\n # execute the compiled fwd fn\n fwd_fn = with_executor(executor, fwd_call, **kwargs)\n outputs = fwd_fn(fwd_inputs)\n\n assert len(outputs) == 1\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs[0], test_case.grads(), *fwd_inputs, *list(model.parameters())],\n iobytes=test_case.grad_iobytes(),\n )\n\n\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.generate_vocab_sizes())\ndef test_cross_entropy_mini_benchmark_fwd(benchmark, executor: str, vocab_size: int):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n # picking a value that doesn't OOM for large vocab sizes\n batch_size = 4096\n\n def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(int(batch_size), int(vocab_size))\n\n fwd_fn = with_executor(executor, fwd_call)\n run_benchmark(benchmark, fwd_fn, inputs)\n\n\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.generate_vocab_sizes())\ndef test_cross_entropy_mini_benchmark_bwd(benchmark, executor: str, vocab_size: int):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n # picking a value that doesn't OOM for large vocab sizes\n batch_size = 4096\n\n def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(batch_size, vocab_size)\n\n fwd_fn = with_executor(executor, fwd_call)\n outputs = fwd_fn(inputs)\n grads = SyntheticMiniModel.grads()\n run_benchmark(benchmark, unary_bwd_torch, [outputs, grads, *inputs])\n\n\n# Simple test of F.cross_entropy without final reduction\n# thunder won't use nvFuser for this fusion, here we manually define the fusion\ndef nvfuser_cross_entropy_fusion(\n fd: FusionDefinition, batch_size: int, vocab_size: int\n) -> None:\n \"\"\"\n NvFuser fusion definition for torch.nn.functional.cross_entropy(logits, labels, reduction='none')\n 1. Compute LSE (log-sum-exp) for each row\n 2. Access target logit directly: logits[i, labels[i]]\n 3. Compute loss: loss = lse - target_logit\n \"\"\"\n # Input tensors\n T0 = fd.define_tensor(\n shape=[batch_size, vocab_size],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[batch_size],\n contiguity=[True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.max(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.broadcast_in_dim(T3, shape=[batch_size, 1], broadcast_dims=[0])\n T11 = fd.ops.broadcast_in_dim(\n T4, shape=[batch_size, vocab_size], broadcast_dims=[0, 1]\n )\n T12 = fd.ops.sub(T2, T11)\n T13 = fd.ops.exp(T12)\n T14 = fd.ops.sum(T13, dims=[1], keepdim=False, dtype=DataType.Null)\n T15 = fd.ops.log(T14)\n T16 = fd.ops.add(T15, T3)\n T17 = fd.ops.broadcast_in_dim(T1, shape=[batch_size, 1], broadcast_dims=[0])\n T18 = fd.ops.gather(T0, T17, dim=1)\n T19 = fd.ops.squeeze(T18, dims=[1])\n T20 = fd.ops.cast(T19, dtype=DataType.Float)\n T21 = fd.ops.sub(T16, T20)\n T22 = fd.ops.cast(T21, dtype=DataType.BFloat16)\n fd.add_output(T22)\n\n\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.sizes_from_models)\ndef test_function_cross_entropy_fwd_nvf_benchmark(\n benchmark, vocab_size: int, disable_validation: bool, disable_benchmarking: bool\n):\n batch_size = 4096\n inputs = [\n 0.1\n * torch.randn(\n batch_size,\n vocab_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n ),\n torch.randint(\n 0,\n vocab_size,\n (batch_size,),\n device=\"cuda\",\n dtype=torch.int64,\n requires_grad=False,\n ),\n ]\n with FusionDefinition() as fd:\n nvfuser_cross_entropy_fusion(fd, batch_size, vocab_size)\n\n if not disable_validation:\n fd.validate(inputs, [torch_cross_entropy_fwd(inputs)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\ndef quack_cross_entropy_fwd_wrapper(inputs: list):\n return quack_cross_entropy_fwd(*inputs, return_dx=False)\n\n\n# cross entropy in thunder is split into log_softmax and nll_loss without\n# using nvFuser, the performance using nvFuser should be measured using\n# test_function_cross_entropy_fwd_nvf_benchmark\n@pytest.mark.parametrize(\n \"executor\",\n [\n \"eager\",\n \"torchcompile\",\n \"thunder-torchcompile\",\n pytest.param(\n \"quack\",\n marks=pytest.mark.skipif(\n not check_module_available(\"quack\"),\n reason=\"quack executor is not available on this device\",\n ),\n ),\n ],\n)\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.sizes_from_models)\ndef test_function_cross_entropy_fwd_benchmark(\n benchmark, executor: str, vocab_size: int\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n batch_size = 4096\n # vocab_size is large, scale by 0.1 to avoid overflow and represent realistic values, same used in quack test\n logits = 0.1 * torch.randn(\n batch_size, vocab_size, device=\"cuda\", dtype=torch.bfloat16, requires_grad=False\n )\n labels = torch.randint(\n 0,\n vocab_size,\n (batch_size,),\n device=\"cuda\",\n dtype=torch.int64,\n requires_grad=False,\n )\n\n if executor == \"quack\":\n fwd_fn = quack_cross_entropy_fwd_wrapper\n else:\n fwd_fn = with_executor(executor, torch_cross_entropy_fwd)\n\n run_benchmark(benchmark, fwd_fn, [logits, labels])","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss.test_cross_entropy_fwd_benchmark","uri":"program://Fuser/function/benchmarks.python.test_cross_entropy_loss.test_cross_entropy_fwd_benchmark#L37-L55","kind":"function","name":"test_cross_entropy_fwd_benchmark","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":37,"end_line":55,"context_start_line":17,"context_end_line":75,"code":" SyntheticMiniModel,\n)\nfrom .torch_ops import cross_entropy as torch_cross_entropy_fwd\n\n\nif check_module_available(\"quack\"):\n from quack.cross_entropy import cross_entropy_fwd as quack_cross_entropy_fwd\n\n\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\ndef test_cross_entropy_fwd_benchmark(\n benchmark,\n variation: str,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n test_case = cross_entropy_loss_setup[variation](dtype=torch.bfloat16)\n inputs = test_case.inputs()\n model = test_case.model()\n\n def fwd_call(inp):\n return model(**inp)\n\n # Compile the fwd fn for torchcompile\n benchmark_fn = with_executor(executor, fwd_call, **kwargs)\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\ndef test_cross_entropy_bwd_benchmark(\n benchmark,\n variation: str,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss.test_cross_entropy_bwd_benchmark","uri":"program://Fuser/function/benchmarks.python.test_cross_entropy_loss.test_cross_entropy_bwd_benchmark#L69-L96","kind":"function","name":"test_cross_entropy_bwd_benchmark","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":69,"end_line":96,"context_start_line":49,"context_end_line":116,"code":"\n def fwd_call(inp):\n return model(**inp)\n\n # Compile the fwd fn for torchcompile\n benchmark_fn = with_executor(executor, fwd_call, **kwargs)\n run_benchmark(benchmark, benchmark_fn, inputs)\n\n\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n ],\n)\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\ndef test_cross_entropy_bwd_benchmark(\n benchmark,\n variation: str,\n executor: str,\n):\n kwargs = {}\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n test_case = cross_entropy_loss_setup[variation](dtype=torch.bfloat16)\n fwd_inputs = test_case.inputs()\n model = test_case.model()\n\n def fwd_call(inp):\n return model(**inp)\n\n # execute the compiled fwd fn\n fwd_fn = with_executor(executor, fwd_call, **kwargs)\n outputs = fwd_fn(fwd_inputs)\n\n assert len(outputs) == 1\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs[0], test_case.grads(), *fwd_inputs, *list(model.parameters())],\n iobytes=test_case.grad_iobytes(),\n )\n\n\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.generate_vocab_sizes())\ndef test_cross_entropy_mini_benchmark_fwd(benchmark, executor: str, vocab_size: int):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n # picking a value that doesn't OOM for large vocab sizes\n batch_size = 4096\n\n def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(int(batch_size), int(vocab_size))\n\n fwd_fn = with_executor(executor, fwd_call)\n run_benchmark(benchmark, fwd_fn, inputs)","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss.test_cross_entropy_mini_benchmark_fwd","uri":"program://Fuser/function/benchmarks.python.test_cross_entropy_loss.test_cross_entropy_mini_benchmark_fwd#L103-L116","kind":"function","name":"test_cross_entropy_mini_benchmark_fwd","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":103,"end_line":116,"context_start_line":83,"context_end_line":136,"code":" return model(**inp)\n\n # execute the compiled fwd fn\n fwd_fn = with_executor(executor, fwd_call, **kwargs)\n outputs = fwd_fn(fwd_inputs)\n\n assert len(outputs) == 1\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs[0], test_case.grads(), *fwd_inputs, *list(model.parameters())],\n iobytes=test_case.grad_iobytes(),\n )\n\n\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.generate_vocab_sizes())\ndef test_cross_entropy_mini_benchmark_fwd(benchmark, executor: str, vocab_size: int):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n # picking a value that doesn't OOM for large vocab sizes\n batch_size = 4096\n\n def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(int(batch_size), int(vocab_size))\n\n fwd_fn = with_executor(executor, fwd_call)\n run_benchmark(benchmark, fwd_fn, inputs)\n\n\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.generate_vocab_sizes())\ndef test_cross_entropy_mini_benchmark_bwd(benchmark, executor: str, vocab_size: int):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n # picking a value that doesn't OOM for large vocab sizes\n batch_size = 4096\n\n def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(batch_size, vocab_size)\n\n fwd_fn = with_executor(executor, fwd_call)\n outputs = fwd_fn(inputs)","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss.test_cross_entropy_mini_benchmark_bwd","uri":"program://Fuser/function/benchmarks.python.test_cross_entropy_loss.test_cross_entropy_mini_benchmark_bwd#L123-L138","kind":"function","name":"test_cross_entropy_mini_benchmark_bwd","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":123,"end_line":138,"context_start_line":103,"context_end_line":158,"code":"def test_cross_entropy_mini_benchmark_fwd(benchmark, executor: str, vocab_size: int):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n # picking a value that doesn't OOM for large vocab sizes\n batch_size = 4096\n\n def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(int(batch_size), int(vocab_size))\n\n fwd_fn = with_executor(executor, fwd_call)\n run_benchmark(benchmark, fwd_fn, inputs)\n\n\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.generate_vocab_sizes())\ndef test_cross_entropy_mini_benchmark_bwd(benchmark, executor: str, vocab_size: int):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n # picking a value that doesn't OOM for large vocab sizes\n batch_size = 4096\n\n def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(batch_size, vocab_size)\n\n fwd_fn = with_executor(executor, fwd_call)\n outputs = fwd_fn(inputs)\n grads = SyntheticMiniModel.grads()\n run_benchmark(benchmark, unary_bwd_torch, [outputs, grads, *inputs])\n\n\n# Simple test of F.cross_entropy without final reduction\n# thunder won't use nvFuser for this fusion, here we manually define the fusion\ndef nvfuser_cross_entropy_fusion(\n fd: FusionDefinition, batch_size: int, vocab_size: int\n) -> None:\n \"\"\"\n NvFuser fusion definition for torch.nn.functional.cross_entropy(logits, labels, reduction='none')\n 1. Compute LSE (log-sum-exp) for each row\n 2. Access target logit directly: logits[i, labels[i]]\n 3. Compute loss: loss = lse - target_logit\n \"\"\"\n # Input tensors\n T0 = fd.define_tensor(\n shape=[batch_size, vocab_size],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss.nvfuser_cross_entropy_fusion","uri":"program://Fuser/function/benchmarks.python.test_cross_entropy_loss.nvfuser_cross_entropy_fusion#L143-L184","kind":"function","name":"nvfuser_cross_entropy_fusion","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":143,"end_line":184,"context_start_line":123,"context_end_line":204,"code":"def test_cross_entropy_mini_benchmark_bwd(benchmark, executor: str, vocab_size: int):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n # picking a value that doesn't OOM for large vocab sizes\n batch_size = 4096\n\n def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(batch_size, vocab_size)\n\n fwd_fn = with_executor(executor, fwd_call)\n outputs = fwd_fn(inputs)\n grads = SyntheticMiniModel.grads()\n run_benchmark(benchmark, unary_bwd_torch, [outputs, grads, *inputs])\n\n\n# Simple test of F.cross_entropy without final reduction\n# thunder won't use nvFuser for this fusion, here we manually define the fusion\ndef nvfuser_cross_entropy_fusion(\n fd: FusionDefinition, batch_size: int, vocab_size: int\n) -> None:\n \"\"\"\n NvFuser fusion definition for torch.nn.functional.cross_entropy(logits, labels, reduction='none')\n 1. Compute LSE (log-sum-exp) for each row\n 2. Access target logit directly: logits[i, labels[i]]\n 3. Compute loss: loss = lse - target_logit\n \"\"\"\n # Input tensors\n T0 = fd.define_tensor(\n shape=[batch_size, vocab_size],\n contiguity=[True, True],\n dtype=DataType.BFloat16,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T1 = fd.define_tensor(\n shape=[batch_size],\n contiguity=[True],\n dtype=DataType.Int,\n is_cpu=False,\n stride_order=[0],\n )\n T2 = fd.ops.cast(T0, dtype=DataType.Float)\n T3 = fd.ops.max(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.broadcast_in_dim(T3, shape=[batch_size, 1], broadcast_dims=[0])\n T11 = fd.ops.broadcast_in_dim(\n T4, shape=[batch_size, vocab_size], broadcast_dims=[0, 1]\n )\n T12 = fd.ops.sub(T2, T11)\n T13 = fd.ops.exp(T12)\n T14 = fd.ops.sum(T13, dims=[1], keepdim=False, dtype=DataType.Null)\n T15 = fd.ops.log(T14)\n T16 = fd.ops.add(T15, T3)\n T17 = fd.ops.broadcast_in_dim(T1, shape=[batch_size, 1], broadcast_dims=[0])\n T18 = fd.ops.gather(T0, T17, dim=1)\n T19 = fd.ops.squeeze(T18, dims=[1])\n T20 = fd.ops.cast(T19, dtype=DataType.Float)\n T21 = fd.ops.sub(T16, T20)\n T22 = fd.ops.cast(T21, dtype=DataType.BFloat16)\n fd.add_output(T22)\n\n\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.sizes_from_models)\ndef test_function_cross_entropy_fwd_nvf_benchmark(\n benchmark, vocab_size: int, disable_validation: bool, disable_benchmarking: bool\n):\n batch_size = 4096\n inputs = [\n 0.1\n * torch.randn(\n batch_size,\n vocab_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n ),\n torch.randint(\n 0,\n vocab_size,\n (batch_size,),","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss.test_function_cross_entropy_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_cross_entropy_loss.test_function_cross_entropy_fwd_nvf_benchmark#L188-L217","kind":"function","name":"test_function_cross_entropy_fwd_nvf_benchmark","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":188,"end_line":217,"context_start_line":168,"context_end_line":237,"code":" T3 = fd.ops.max(T2, dims=[1], keepdim=False, dtype=DataType.Null)\n T4 = fd.ops.broadcast_in_dim(T3, shape=[batch_size, 1], broadcast_dims=[0])\n T11 = fd.ops.broadcast_in_dim(\n T4, shape=[batch_size, vocab_size], broadcast_dims=[0, 1]\n )\n T12 = fd.ops.sub(T2, T11)\n T13 = fd.ops.exp(T12)\n T14 = fd.ops.sum(T13, dims=[1], keepdim=False, dtype=DataType.Null)\n T15 = fd.ops.log(T14)\n T16 = fd.ops.add(T15, T3)\n T17 = fd.ops.broadcast_in_dim(T1, shape=[batch_size, 1], broadcast_dims=[0])\n T18 = fd.ops.gather(T0, T17, dim=1)\n T19 = fd.ops.squeeze(T18, dims=[1])\n T20 = fd.ops.cast(T19, dtype=DataType.Float)\n T21 = fd.ops.sub(T16, T20)\n T22 = fd.ops.cast(T21, dtype=DataType.BFloat16)\n fd.add_output(T22)\n\n\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.sizes_from_models)\ndef test_function_cross_entropy_fwd_nvf_benchmark(\n benchmark, vocab_size: int, disable_validation: bool, disable_benchmarking: bool\n):\n batch_size = 4096\n inputs = [\n 0.1\n * torch.randn(\n batch_size,\n vocab_size,\n device=\"cuda\",\n dtype=torch.bfloat16,\n requires_grad=False,\n ),\n torch.randint(\n 0,\n vocab_size,\n (batch_size,),\n device=\"cuda\",\n dtype=torch.int64,\n requires_grad=False,\n ),\n ]\n with FusionDefinition() as fd:\n nvfuser_cross_entropy_fusion(fd, batch_size, vocab_size)\n\n if not disable_validation:\n fd.validate(inputs, [torch_cross_entropy_fwd(inputs)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\ndef quack_cross_entropy_fwd_wrapper(inputs: list):\n return quack_cross_entropy_fwd(*inputs, return_dx=False)\n\n\n# cross entropy in thunder is split into log_softmax and nll_loss without\n# using nvFuser, the performance using nvFuser should be measured using\n# test_function_cross_entropy_fwd_nvf_benchmark\n@pytest.mark.parametrize(\n \"executor\",\n [\n \"eager\",\n \"torchcompile\",\n \"thunder-torchcompile\",\n pytest.param(\n \"quack\",\n marks=pytest.mark.skipif(\n not check_module_available(\"quack\"),\n reason=\"quack executor is not available on this device\",","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss.quack_cross_entropy_fwd_wrapper","uri":"program://Fuser/function/benchmarks.python.test_cross_entropy_loss.quack_cross_entropy_fwd_wrapper#L220-L221","kind":"function","name":"quack_cross_entropy_fwd_wrapper","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":220,"end_line":221,"context_start_line":200,"context_end_line":241,"code":" ),\n torch.randint(\n 0,\n vocab_size,\n (batch_size,),\n device=\"cuda\",\n dtype=torch.int64,\n requires_grad=False,\n ),\n ]\n with FusionDefinition() as fd:\n nvfuser_cross_entropy_fusion(fd, batch_size, vocab_size)\n\n if not disable_validation:\n fd.validate(inputs, [torch_cross_entropy_fwd(inputs)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\ndef quack_cross_entropy_fwd_wrapper(inputs: list):\n return quack_cross_entropy_fwd(*inputs, return_dx=False)\n\n\n# cross entropy in thunder is split into log_softmax and nll_loss without\n# using nvFuser, the performance using nvFuser should be measured using\n# test_function_cross_entropy_fwd_nvf_benchmark\n@pytest.mark.parametrize(\n \"executor\",\n [\n \"eager\",\n \"torchcompile\",\n \"thunder-torchcompile\",\n pytest.param(\n \"quack\",\n marks=pytest.mark.skipif(\n not check_module_available(\"quack\"),\n reason=\"quack executor is not available on this device\",\n ),\n ),\n ],\n)","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss.test_function_cross_entropy_fwd_benchmark","uri":"program://Fuser/function/benchmarks.python.test_cross_entropy_loss.test_function_cross_entropy_fwd_benchmark#L243-L268","kind":"function","name":"test_function_cross_entropy_fwd_benchmark","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":243,"end_line":268,"context_start_line":223,"context_end_line":268,"code":"\n# cross entropy in thunder is split into log_softmax and nll_loss without\n# using nvFuser, the performance using nvFuser should be measured using\n# test_function_cross_entropy_fwd_nvf_benchmark\n@pytest.mark.parametrize(\n \"executor\",\n [\n \"eager\",\n \"torchcompile\",\n \"thunder-torchcompile\",\n pytest.param(\n \"quack\",\n marks=pytest.mark.skipif(\n not check_module_available(\"quack\"),\n reason=\"quack executor is not available on this device\",\n ),\n ),\n ],\n)\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.sizes_from_models)\ndef test_function_cross_entropy_fwd_benchmark(\n benchmark, executor: str, vocab_size: int\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n batch_size = 4096\n # vocab_size is large, scale by 0.1 to avoid overflow and represent realistic values, same used in quack test\n logits = 0.1 * torch.randn(\n batch_size, vocab_size, device=\"cuda\", dtype=torch.bfloat16, requires_grad=False\n )\n labels = torch.randint(\n 0,\n vocab_size,\n (batch_size,),\n device=\"cuda\",\n dtype=torch.int64,\n requires_grad=False,\n )\n\n if executor == \"quack\":\n fwd_fn = quack_cross_entropy_fwd_wrapper\n else:\n fwd_fn = with_executor(executor, torch_cross_entropy_fwd)\n\n run_benchmark(benchmark, fwd_fn, [logits, labels])","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_cross_entropy_loss.fwd_call","uri":"program://Fuser/function/benchmarks.python.test_cross_entropy_loss.fwd_call#L130-L131","kind":"function","name":"fwd_call","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":130,"end_line":131,"context_start_line":110,"context_end_line":151,"code":" def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(int(batch_size), int(vocab_size))\n\n fwd_fn = with_executor(executor, fwd_call)\n run_benchmark(benchmark, fwd_fn, inputs)\n\n\n@pytest.mark.parametrize(\n \"executor\", [\"eager\", \"torchcompile\", \"thunder\", \"thunder-torchcompile\"]\n)\n@pytest.mark.parametrize(\"vocab_size\", SyntheticMiniModel.generate_vocab_sizes())\ndef test_cross_entropy_mini_benchmark_bwd(benchmark, executor: str, vocab_size: int):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n # picking a value that doesn't OOM for large vocab sizes\n batch_size = 4096\n\n def fwd_call(inp):\n return SyntheticMiniModel.mini_model(*inp)\n\n inputs = SyntheticMiniModel.inputs(batch_size, vocab_size)\n\n fwd_fn = with_executor(executor, fwd_call)\n outputs = fwd_fn(inputs)\n grads = SyntheticMiniModel.grads()\n run_benchmark(benchmark, unary_bwd_torch, [outputs, grads, *inputs])\n\n\n# Simple test of F.cross_entropy without final reduction\n# thunder won't use nvFuser for this fusion, here we manually define the fusion\ndef nvfuser_cross_entropy_fusion(\n fd: FusionDefinition, batch_size: int, vocab_size: int\n) -> None:\n \"\"\"\n NvFuser fusion definition for torch.nn.functional.cross_entropy(logits, labels, reduction='none')\n 1. Compute LSE (log-sum-exp) for each row\n 2. Access target logit directly: logits[i, labels[i]]\n 3. Compute loss: loss = lse - target_logit\n \"\"\"","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization","uri":"program://Fuser/module/benchmarks.python.normalization#L1-L504","kind":"module","name":"benchmarks.python.normalization","path":"benchmarks/python/normalization.py","language":"python","start_line":1,"end_line":504,"context_start_line":1,"context_end_line":504,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom .global_params import PROMOTE_DTYPES\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nimport torch\nfrom .core import run_benchmark, unary_bwd_torch, clear_dynamo_cache, with_executor\nimport numpy as np\nfrom functools import reduce\n\n\ndef norm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n norm: str,\n num_dims: int,\n channels_last: bool,\n eps: float = 1e-5,\n momentum: float = 0.01,\n) -> None:\n \"\"\"\n Fusion definition for batch norm and instance norm forward in training mode.\n \"\"\"\n batch_dim = 0\n channel_dim = 1 if not channels_last else num_dims - 1\n bcast_mask = [True if i != channel_dim else False for i in range(num_dims)]\n channels_only_bcast_mask = [\n True if i != channel_dim else False for i in range(num_dims)\n ]\n\n reduction_axes = [i for i in range(num_dims) if i != channel_dim]\n if norm == \"instance_norm\":\n reduction_axes.remove(batch_dim)\n bcast_mask[batch_dim] = False\n\n input = fd.define_tensor(\n shape=[-1] * num_dims, contiguity=[True] * num_dims, dtype=dtype, is_cpu=False\n )\n weight = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n running_mean = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n running_var = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n weight = fd.ops.cast(weight, dtype=DataType.Float)\n bias = fd.ops.cast(bias, dtype=DataType.Float)\n\n var, mean = fd.ops.var_mean(input, dims=reduction_axes, correction=0, keepdim=False)\n\n eps = fd.define_scalar(eps, dtype=DataType.Double)\n var_eps = fd.ops.add(var, eps)\n invstd = fd.ops.rsqrt(var_eps)\n\n invstd_bcast = fd.ops.broadcast(invstd, bcast_mask)\n mean_bcast = fd.ops.broadcast(mean, bcast_mask)\n x_sub_mean = fd.ops.sub(input, mean_bcast)\n\n x_norm = fd.ops.mul(x_sub_mean, invstd_bcast)\n\n weight = fd.ops.broadcast(weight, channels_only_bcast_mask)\n x_scaled = fd.ops.mul(x_norm, weight)\n bias = fd.ops.broadcast(bias, channels_only_bcast_mask)\n output = fd.ops.add(x_scaled, bias)\n\n rev_momentum = fd.define_scalar(1 - momentum, dtype=DataType.Double)\n momentum = fd.define_scalar(momentum, dtype=DataType.Double)\n\n updated_mean = fd.ops.add(\n fd.ops.mul(momentum, mean), fd.ops.mul(rev_momentum, running_mean)\n )\n updated_var = fd.ops.add(\n fd.ops.mul(momentum, var), fd.ops.mul(rev_momentum, running_var)\n )\n\n if batch_dim not in reduction_axes:\n inverse_batch_size = fd.ops.reciprocal(input.size(0))\n updated_mean = fd.ops.mul(\n fd.ops.sum(updated_mean, batch_dim), inverse_batch_size\n )\n updated_var = fd.ops.mul(fd.ops.sum(updated_var, batch_dim), inverse_batch_size)\n\n if dtype in PROMOTE_DTYPES:\n output = fd.ops.cast(output, dtype=dtype)\n\n fd.add_output(output)\n fd.add_output(mean)\n fd.add_output(invstd)\n\n\ndef norm_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n norm: str,\n num_dims: int,\n channels_last: bool,\n eps: float = 1e-5,\n) -> None:\n \"\"\"\n Fusion definition for batch norm and instance norm backward in training mode.\n \"\"\"\n batch_dim = 0\n channel_dim = 1 if not channels_last else num_dims - 1\n bcast_mask = [True if i != channel_dim else False for i in range(num_dims)]\n channels_only_bcast_mask = [\n True if i != channel_dim else False for i in range(num_dims)\n ]\n\n reduction_axes = [i for i in range(num_dims) if i != channel_dim]\n if norm == \"instance_norm\":\n reduction_axes.remove(batch_dim)\n bcast_mask[batch_dim] = False\n\n num_spatial_dims = num_dims - len(reduction_axes)\n\n input = fd.define_tensor(\n shape=[-1] * num_dims, contiguity=[True] * num_dims, dtype=dtype, is_cpu=False\n )\n grad = fd.define_tensor(\n shape=[-1] * num_dims, contiguity=[True] * num_dims, dtype=dtype, is_cpu=False\n )\n weight = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n running_mean = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n running_var = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n\n mean = fd.define_tensor(\n shape=[-1] * num_spatial_dims,\n contiguity=[True] * num_spatial_dims,\n dtype=DataType.Float,\n is_cpu=False,\n )\n invstd = fd.define_tensor(\n shape=[-1] * num_spatial_dims,\n contiguity=[True] * num_spatial_dims,\n dtype=DataType.Float,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n grad = fd.ops.cast(grad, dtype=DataType.Float)\n weight = fd.ops.cast(weight, dtype=DataType.Float)\n\n num_features = reduce(fd.ops.mul, [input.size(ax) for ax in reduction_axes], 1)\n\n norm = fd.ops.reciprocal(num_features)\n\n mean = fd.ops.broadcast(mean, bcast_mask)\n\n grad_sum = fd.ops.sum(grad, dims=reduction_axes, keepdim=False)\n\n x_sub_mean = fd.ops.sub(input, mean)\n dot_p = fd.ops.sum(fd.ops.mul(grad, x_sub_mean), dims=reduction_axes, keepdim=False)\n\n grad_mean = fd.ops.broadcast(fd.ops.mul(grad_sum, norm), bcast_mask)\n proj_scale = fd.ops.mul(fd.ops.mul(dot_p, norm), fd.ops.mul(invstd, invstd))\n proj_scale = fd.ops.broadcast(proj_scale, bcast_mask)\n\n invstd_bcast = fd.ops.broadcast(invstd, bcast_mask)\n weight = fd.ops.broadcast(weight, channels_only_bcast_mask)\n grad_scale = fd.ops.mul(weight, invstd_bcast)\n proj = fd.ops.mul(proj_scale, x_sub_mean)\n\n grad_input = fd.ops.mul(fd.ops.sub(fd.ops.sub(grad, proj), grad_mean), grad_scale)\n grad_weight = fd.ops.mul(dot_p, invstd)\n grad_bias = grad_sum\n\n if batch_dim not in reduction_axes:\n # Weights and bias are channel-only\n grad_weight = fd.ops.sum(grad_weight, batch_dim, keepdim=False)\n grad_bias = fd.ops.sum(grad_bias, batch_dim, keepdim=False)\n\n if dtype in PROMOTE_DTYPES:\n grad_input = fd.ops.cast(grad_input, dtype=dtype)\n grad_weight = fd.ops.cast(grad_weight, dtype=dtype)\n grad_bias = fd.ops.cast(grad_bias, dtype=dtype)\n\n fd.add_output(grad_input)\n fd.add_output(grad_weight)\n fd.add_output(grad_bias)\n\n\ndef norm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n norm: str,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n \"\"\"\n Common benchmark setup for batchnorm/instance forward call in training mode.\n \"\"\"\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n num_dims = len(size)\n\n at_inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n\n # CPP benchmarks assume mean and variance to be of type Float\n running_mean = torch.zeros(size[1], device=\"cuda\", dtype=torch.float)\n running_var = torch.ones(size[1], device=\"cuda\", dtype=torch.float)\n\n if channels_last:\n at_inputs = at_inputs.to(memory_format=torch.channels_last)\n inputs = at_inputs.clone().detach().permute((0, *range(2, num_dims), 1))\n else:\n inputs = at_inputs\n\n with FusionDefinition() as fd:\n norm_fwd_fusion(\n fd=fd,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n norm=norm,\n num_dims=num_dims,\n channels_last=channels_last,\n )\n\n if not disable_validation:\n # PyTorch expects running mean and variance to be of same type as input.\n if norm == \"batch_norm\":\n eager_output = torch.nn.functional.batch_norm(\n at_inputs,\n running_mean.to(dtype),\n running_var.to(dtype),\n weight=weight,\n bias=bias,\n training=True,\n )\n elif norm == \"instance_norm\":\n eager_output = torch.nn.functional.instance_norm(\n at_inputs,\n running_mean.to(dtype),\n running_var.to(dtype),\n weight=weight,\n bias=bias,\n )\n if channels_last:\n eager_output = eager_output.permute((0, *range(2, num_dims), 1))\n\n batch_dim = 0\n channel_dim = 1 if not channels_last else num_dims - 1\n reduction_axes = [i for i in range(len(size)) if i != channel_dim]\n if norm == \"instance_norm\":\n reduction_axes.remove(batch_dim)\n\n mean = inputs.to(torch.float).mean(dim=reduction_axes)\n var = inputs.to(torch.float).var(dim=reduction_axes, unbiased=False)\n invstd = 1.0 / torch.sqrt(var + eps)\n\n fd.validate(\n [inputs, weight, bias, running_mean, running_var],\n [eager_output, mean, invstd],\n )\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark, fd.execute, [inputs, weight, bias, running_mean, running_var]\n )\n\n\ndef norm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n norm: str,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n \"\"\"\n Common benchmark setup for batchnorm/instance forward call in training mode.\n \"\"\"\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n\n num_dims = len(size)\n\n at_inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n at_grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n # CPP benchmarks assume mean and variance to be of type Float\n running_mean = torch.zeros(size[1], device=\"cuda\", dtype=torch.float)\n running_var = torch.ones(size[1], device=\"cuda\", dtype=torch.float)\n\n if channels_last:\n at_inputs = at_inputs.to(memory_format=torch.channels_last)\n at_inputs.retain_grad()\n at_grads = at_grads.to(memory_format=torch.channels_last)\n\n inputs = at_inputs.clone().detach().permute((0, *range(2, num_dims), 1))\n grads = at_grads.clone().detach().permute((0, *range(2, num_dims), 1))\n\n else:\n inputs = at_inputs\n grads = at_grads\n\n batch_dim = 0\n channel_dim = 1 if not channels_last else num_dims - 1\n reduction_axes = [i for i in range(len(size)) if i != channel_dim]\n if norm == \"instance_norm\":\n reduction_axes.remove(batch_dim)\n mean = inputs.to(torch.float).mean(dim=reduction_axes)\n var = inputs.to(torch.float).var(dim=reduction_axes, unbiased=False)\n invstd = 1.0 / torch.sqrt(var + eps)\n\n with FusionDefinition() as fd:\n norm_bwd_fusion(\n fd=fd,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n norm=norm,\n num_dims=num_dims,\n channels_last=channels_last,\n )\n\n if not disable_validation:\n # PyTorch expects running mean and variance to be of same type as input.\n if norm == \"batch_norm\":\n eager_output = torch.nn.functional.batch_norm(\n at_inputs.to(torch.double),\n running_mean.to(torch.double),\n running_var.to(torch.double),\n weight=weight.to(torch.double),\n bias=bias.to(torch.double),\n training=True,\n )\n elif norm == \"instance_norm\":\n eager_output = torch.nn.functional.instance_norm(\n at_inputs.to(torch.double),\n running_mean.to(torch.double),\n running_var.to(torch.double),\n weight=weight.to(torch.double),\n bias=bias.to(torch.double),\n )\n\n eager_output.backward(at_grads.to(torch.double))\n\n if channels_last:\n eager_grad = at_inputs.grad.permute((0, *range(2, num_dims), 1))\n else:\n eager_grad = at_inputs.grad\n\n fd.validate(\n [inputs, grads, weight, running_mean, running_var, mean, invstd],\n [eager_grad, weight.grad, bias.grad],\n )\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [inputs, grads, weight, running_mean, running_var, mean, invstd],\n )\n\n\ndef batchnorm_fwd_fn(inputs: list):\n input, weight, bias, running_mean, running_var = inputs\n return torch.nn.functional.batch_norm(\n input,\n running_mean,\n running_var,\n weight=weight,\n bias=bias,\n training=True,\n )\n\n\ndef instancenorm_fwd_fn(inputs: list):\n input, weight, bias, running_mean, running_var = inputs\n return torch.nn.functional.instance_norm(\n input,\n running_mean,\n running_var,\n weight=weight,\n bias=bias,\n )\n\n\ndef norm_fwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation required since nvFuser outputs (out, mean, invstd) differs from baselines (out)\n # size = [N, C, H, W]\n # Total IO bytes = in_tensor (size, dtype) + weight (size[1], dtype) + bias (size[1], dtype) +\n # running_mean (size[1], float) + running_var (size[1], float) + output (size, dtype) +\n # mean ([C]/[N, C] , float) + invstd ([C]/[N, C] , float)\n stat_size = (\n size[1] if norm == \"batch_norm\" else size[0] * size[1]\n ) # size of mean/invstd\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * (size[1] + stat_size)\n )\n\n\ndef norm_bwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, mean, invstd, weigts, grad_in, grad_weight, grad_bias) differ from baselines (out, grad_out)\n # size = [N, C, H, W]\n # Total IO bytes = in_tensor (size, dtype) + weight (size[1], dtype) +\n # running_mean (size[1], float) + running_var (size[1], float) +\n # mean ([C]/[N, C] , float) + invstd ([C]/[N, C] , float) + grad_out (size, dtype) +\n # grad_in (size, dtype) + grad_weight (size[1], dtype) + grad_bias (size[1], dtype)\n stat_size = size[1] if norm == \"batch_norm\" else size[0] * size[1]\n return int(\n dtype.itemsize * 3 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * (size[1] + stat_size)\n )\n\n\ndef norm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n executor: str,\n norm: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n running_mean = torch.zeros(size[1], device=\"cuda\", dtype=dtype)\n running_var = torch.ones(size[1], device=\"cuda\", dtype=dtype)\n if channels_last:\n inputs = inputs.to(memory_format=torch.channels_last)\n\n norm_fwd_fn = batchnorm_fwd_fn if norm == \"batch_norm\" else instancenorm_fwd_fn\n\n benchmark_fn = with_executor(executor, norm_fwd_fn)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, weight, bias, running_mean, running_var],\n iobytes=norm_fwd_iobytes(size, dtype, norm),\n )\n\n\ndef norm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n executor: str,\n norm: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n running_mean = torch.zeros(size[1], device=\"cuda\", dtype=dtype)\n running_var = torch.ones(size[1], device=\"cuda\", dtype=dtype)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n if channels_last:\n inputs = inputs.to(memory_format=torch.channels_last)\n grads = grads.to(memory_format=torch.channels_last)\n\n norm_fwd_fn = batchnorm_fwd_fn if norm == \"batch_norm\" else instancenorm_fwd_fn\n\n fwd_fn = with_executor(executor, norm_fwd_fn)\n fwd_inputs = [inputs, weight, bias, running_mean, running_var]\n outputs = fwd_fn(fwd_inputs)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=norm_bwd_iobytes(size, dtype, norm),\n )","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.norm_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.normalization.norm_fwd_fusion#L13-L94","kind":"function","name":"norm_fwd_fusion","path":"benchmarks/python/normalization.py","language":"python","start_line":13,"end_line":94,"context_start_line":1,"context_end_line":114,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom .global_params import PROMOTE_DTYPES\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nimport torch\nfrom .core import run_benchmark, unary_bwd_torch, clear_dynamo_cache, with_executor\nimport numpy as np\nfrom functools import reduce\n\n\ndef norm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n norm: str,\n num_dims: int,\n channels_last: bool,\n eps: float = 1e-5,\n momentum: float = 0.01,\n) -> None:\n \"\"\"\n Fusion definition for batch norm and instance norm forward in training mode.\n \"\"\"\n batch_dim = 0\n channel_dim = 1 if not channels_last else num_dims - 1\n bcast_mask = [True if i != channel_dim else False for i in range(num_dims)]\n channels_only_bcast_mask = [\n True if i != channel_dim else False for i in range(num_dims)\n ]\n\n reduction_axes = [i for i in range(num_dims) if i != channel_dim]\n if norm == \"instance_norm\":\n reduction_axes.remove(batch_dim)\n bcast_mask[batch_dim] = False\n\n input = fd.define_tensor(\n shape=[-1] * num_dims, contiguity=[True] * num_dims, dtype=dtype, is_cpu=False\n )\n weight = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n running_mean = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n running_var = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n weight = fd.ops.cast(weight, dtype=DataType.Float)\n bias = fd.ops.cast(bias, dtype=DataType.Float)\n\n var, mean = fd.ops.var_mean(input, dims=reduction_axes, correction=0, keepdim=False)\n\n eps = fd.define_scalar(eps, dtype=DataType.Double)\n var_eps = fd.ops.add(var, eps)\n invstd = fd.ops.rsqrt(var_eps)\n\n invstd_bcast = fd.ops.broadcast(invstd, bcast_mask)\n mean_bcast = fd.ops.broadcast(mean, bcast_mask)\n x_sub_mean = fd.ops.sub(input, mean_bcast)\n\n x_norm = fd.ops.mul(x_sub_mean, invstd_bcast)\n\n weight = fd.ops.broadcast(weight, channels_only_bcast_mask)\n x_scaled = fd.ops.mul(x_norm, weight)\n bias = fd.ops.broadcast(bias, channels_only_bcast_mask)\n output = fd.ops.add(x_scaled, bias)\n\n rev_momentum = fd.define_scalar(1 - momentum, dtype=DataType.Double)\n momentum = fd.define_scalar(momentum, dtype=DataType.Double)\n\n updated_mean = fd.ops.add(\n fd.ops.mul(momentum, mean), fd.ops.mul(rev_momentum, running_mean)\n )\n updated_var = fd.ops.add(\n fd.ops.mul(momentum, var), fd.ops.mul(rev_momentum, running_var)\n )\n\n if batch_dim not in reduction_axes:\n inverse_batch_size = fd.ops.reciprocal(input.size(0))\n updated_mean = fd.ops.mul(\n fd.ops.sum(updated_mean, batch_dim), inverse_batch_size\n )\n updated_var = fd.ops.mul(fd.ops.sum(updated_var, batch_dim), inverse_batch_size)\n\n if dtype in PROMOTE_DTYPES:\n output = fd.ops.cast(output, dtype=dtype)\n\n fd.add_output(output)\n fd.add_output(mean)\n fd.add_output(invstd)\n\n\ndef norm_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n norm: str,\n num_dims: int,\n channels_last: bool,\n eps: float = 1e-5,\n) -> None:\n \"\"\"\n Fusion definition for batch norm and instance norm backward in training mode.\n \"\"\"\n batch_dim = 0\n channel_dim = 1 if not channels_last else num_dims - 1\n bcast_mask = [True if i != channel_dim else False for i in range(num_dims)]\n channels_only_bcast_mask = [\n True if i != channel_dim else False for i in range(num_dims)\n ]\n","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.norm_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.normalization.norm_bwd_fusion#L97-L191","kind":"function","name":"norm_bwd_fusion","path":"benchmarks/python/normalization.py","language":"python","start_line":97,"end_line":191,"context_start_line":77,"context_end_line":211,"code":" )\n updated_var = fd.ops.add(\n fd.ops.mul(momentum, var), fd.ops.mul(rev_momentum, running_var)\n )\n\n if batch_dim not in reduction_axes:\n inverse_batch_size = fd.ops.reciprocal(input.size(0))\n updated_mean = fd.ops.mul(\n fd.ops.sum(updated_mean, batch_dim), inverse_batch_size\n )\n updated_var = fd.ops.mul(fd.ops.sum(updated_var, batch_dim), inverse_batch_size)\n\n if dtype in PROMOTE_DTYPES:\n output = fd.ops.cast(output, dtype=dtype)\n\n fd.add_output(output)\n fd.add_output(mean)\n fd.add_output(invstd)\n\n\ndef norm_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n norm: str,\n num_dims: int,\n channels_last: bool,\n eps: float = 1e-5,\n) -> None:\n \"\"\"\n Fusion definition for batch norm and instance norm backward in training mode.\n \"\"\"\n batch_dim = 0\n channel_dim = 1 if not channels_last else num_dims - 1\n bcast_mask = [True if i != channel_dim else False for i in range(num_dims)]\n channels_only_bcast_mask = [\n True if i != channel_dim else False for i in range(num_dims)\n ]\n\n reduction_axes = [i for i in range(num_dims) if i != channel_dim]\n if norm == \"instance_norm\":\n reduction_axes.remove(batch_dim)\n bcast_mask[batch_dim] = False\n\n num_spatial_dims = num_dims - len(reduction_axes)\n\n input = fd.define_tensor(\n shape=[-1] * num_dims, contiguity=[True] * num_dims, dtype=dtype, is_cpu=False\n )\n grad = fd.define_tensor(\n shape=[-1] * num_dims, contiguity=[True] * num_dims, dtype=dtype, is_cpu=False\n )\n weight = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n running_mean = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n running_var = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n\n mean = fd.define_tensor(\n shape=[-1] * num_spatial_dims,\n contiguity=[True] * num_spatial_dims,\n dtype=DataType.Float,\n is_cpu=False,\n )\n invstd = fd.define_tensor(\n shape=[-1] * num_spatial_dims,\n contiguity=[True] * num_spatial_dims,\n dtype=DataType.Float,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n grad = fd.ops.cast(grad, dtype=DataType.Float)\n weight = fd.ops.cast(weight, dtype=DataType.Float)\n\n num_features = reduce(fd.ops.mul, [input.size(ax) for ax in reduction_axes], 1)\n\n norm = fd.ops.reciprocal(num_features)\n\n mean = fd.ops.broadcast(mean, bcast_mask)\n\n grad_sum = fd.ops.sum(grad, dims=reduction_axes, keepdim=False)\n\n x_sub_mean = fd.ops.sub(input, mean)\n dot_p = fd.ops.sum(fd.ops.mul(grad, x_sub_mean), dims=reduction_axes, keepdim=False)\n\n grad_mean = fd.ops.broadcast(fd.ops.mul(grad_sum, norm), bcast_mask)\n proj_scale = fd.ops.mul(fd.ops.mul(dot_p, norm), fd.ops.mul(invstd, invstd))\n proj_scale = fd.ops.broadcast(proj_scale, bcast_mask)\n\n invstd_bcast = fd.ops.broadcast(invstd, bcast_mask)\n weight = fd.ops.broadcast(weight, channels_only_bcast_mask)\n grad_scale = fd.ops.mul(weight, invstd_bcast)\n proj = fd.ops.mul(proj_scale, x_sub_mean)\n\n grad_input = fd.ops.mul(fd.ops.sub(fd.ops.sub(grad, proj), grad_mean), grad_scale)\n grad_weight = fd.ops.mul(dot_p, invstd)\n grad_bias = grad_sum\n\n if batch_dim not in reduction_axes:\n # Weights and bias are channel-only\n grad_weight = fd.ops.sum(grad_weight, batch_dim, keepdim=False)\n grad_bias = fd.ops.sum(grad_bias, batch_dim, keepdim=False)\n\n if dtype in PROMOTE_DTYPES:\n grad_input = fd.ops.cast(grad_input, dtype=dtype)\n grad_weight = fd.ops.cast(grad_weight, dtype=dtype)\n grad_bias = fd.ops.cast(grad_bias, dtype=dtype)\n\n fd.add_output(grad_input)\n fd.add_output(grad_weight)\n fd.add_output(grad_bias)\n\n\ndef norm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n norm: str,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n \"\"\"\n Common benchmark setup for batchnorm/instance forward call in training mode.\n \"\"\"\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n num_dims = len(size)","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.norm_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.normalization.norm_fwd_nvf_benchmark#L194-L276","kind":"function","name":"norm_fwd_nvf_benchmark","path":"benchmarks/python/normalization.py","language":"python","start_line":194,"end_line":276,"context_start_line":174,"context_end_line":296,"code":"\n grad_input = fd.ops.mul(fd.ops.sub(fd.ops.sub(grad, proj), grad_mean), grad_scale)\n grad_weight = fd.ops.mul(dot_p, invstd)\n grad_bias = grad_sum\n\n if batch_dim not in reduction_axes:\n # Weights and bias are channel-only\n grad_weight = fd.ops.sum(grad_weight, batch_dim, keepdim=False)\n grad_bias = fd.ops.sum(grad_bias, batch_dim, keepdim=False)\n\n if dtype in PROMOTE_DTYPES:\n grad_input = fd.ops.cast(grad_input, dtype=dtype)\n grad_weight = fd.ops.cast(grad_weight, dtype=dtype)\n grad_bias = fd.ops.cast(grad_bias, dtype=dtype)\n\n fd.add_output(grad_input)\n fd.add_output(grad_weight)\n fd.add_output(grad_bias)\n\n\ndef norm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n norm: str,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n \"\"\"\n Common benchmark setup for batchnorm/instance forward call in training mode.\n \"\"\"\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n num_dims = len(size)\n\n at_inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n\n # CPP benchmarks assume mean and variance to be of type Float\n running_mean = torch.zeros(size[1], device=\"cuda\", dtype=torch.float)\n running_var = torch.ones(size[1], device=\"cuda\", dtype=torch.float)\n\n if channels_last:\n at_inputs = at_inputs.to(memory_format=torch.channels_last)\n inputs = at_inputs.clone().detach().permute((0, *range(2, num_dims), 1))\n else:\n inputs = at_inputs\n\n with FusionDefinition() as fd:\n norm_fwd_fusion(\n fd=fd,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n norm=norm,\n num_dims=num_dims,\n channels_last=channels_last,\n )\n\n if not disable_validation:\n # PyTorch expects running mean and variance to be of same type as input.\n if norm == \"batch_norm\":\n eager_output = torch.nn.functional.batch_norm(\n at_inputs,\n running_mean.to(dtype),\n running_var.to(dtype),\n weight=weight,\n bias=bias,\n training=True,\n )\n elif norm == \"instance_norm\":\n eager_output = torch.nn.functional.instance_norm(\n at_inputs,\n running_mean.to(dtype),\n running_var.to(dtype),\n weight=weight,\n bias=bias,\n )\n if channels_last:\n eager_output = eager_output.permute((0, *range(2, num_dims), 1))\n\n batch_dim = 0\n channel_dim = 1 if not channels_last else num_dims - 1\n reduction_axes = [i for i in range(len(size)) if i != channel_dim]\n if norm == \"instance_norm\":\n reduction_axes.remove(batch_dim)\n\n mean = inputs.to(torch.float).mean(dim=reduction_axes)\n var = inputs.to(torch.float).var(dim=reduction_axes, unbiased=False)\n invstd = 1.0 / torch.sqrt(var + eps)\n\n fd.validate(\n [inputs, weight, bias, running_mean, running_var],\n [eager_output, mean, invstd],\n )\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark, fd.execute, [inputs, weight, bias, running_mean, running_var]\n )\n\n\ndef norm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n norm: str,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n \"\"\"\n Common benchmark setup for batchnorm/instance forward call in training mode.\n \"\"\"\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.norm_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.normalization.norm_bwd_nvf_benchmark#L279-L375","kind":"function","name":"norm_bwd_nvf_benchmark","path":"benchmarks/python/normalization.py","language":"python","start_line":279,"end_line":375,"context_start_line":259,"context_end_line":395,"code":" channel_dim = 1 if not channels_last else num_dims - 1\n reduction_axes = [i for i in range(len(size)) if i != channel_dim]\n if norm == \"instance_norm\":\n reduction_axes.remove(batch_dim)\n\n mean = inputs.to(torch.float).mean(dim=reduction_axes)\n var = inputs.to(torch.float).var(dim=reduction_axes, unbiased=False)\n invstd = 1.0 / torch.sqrt(var + eps)\n\n fd.validate(\n [inputs, weight, bias, running_mean, running_var],\n [eager_output, mean, invstd],\n )\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark, fd.execute, [inputs, weight, bias, running_mean, running_var]\n )\n\n\ndef norm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n norm: str,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n \"\"\"\n Common benchmark setup for batchnorm/instance forward call in training mode.\n \"\"\"\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n\n num_dims = len(size)\n\n at_inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n at_grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n # CPP benchmarks assume mean and variance to be of type Float\n running_mean = torch.zeros(size[1], device=\"cuda\", dtype=torch.float)\n running_var = torch.ones(size[1], device=\"cuda\", dtype=torch.float)\n\n if channels_last:\n at_inputs = at_inputs.to(memory_format=torch.channels_last)\n at_inputs.retain_grad()\n at_grads = at_grads.to(memory_format=torch.channels_last)\n\n inputs = at_inputs.clone().detach().permute((0, *range(2, num_dims), 1))\n grads = at_grads.clone().detach().permute((0, *range(2, num_dims), 1))\n\n else:\n inputs = at_inputs\n grads = at_grads\n\n batch_dim = 0\n channel_dim = 1 if not channels_last else num_dims - 1\n reduction_axes = [i for i in range(len(size)) if i != channel_dim]\n if norm == \"instance_norm\":\n reduction_axes.remove(batch_dim)\n mean = inputs.to(torch.float).mean(dim=reduction_axes)\n var = inputs.to(torch.float).var(dim=reduction_axes, unbiased=False)\n invstd = 1.0 / torch.sqrt(var + eps)\n\n with FusionDefinition() as fd:\n norm_bwd_fusion(\n fd=fd,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n norm=norm,\n num_dims=num_dims,\n channels_last=channels_last,\n )\n\n if not disable_validation:\n # PyTorch expects running mean and variance to be of same type as input.\n if norm == \"batch_norm\":\n eager_output = torch.nn.functional.batch_norm(\n at_inputs.to(torch.double),\n running_mean.to(torch.double),\n running_var.to(torch.double),\n weight=weight.to(torch.double),\n bias=bias.to(torch.double),\n training=True,\n )\n elif norm == \"instance_norm\":\n eager_output = torch.nn.functional.instance_norm(\n at_inputs.to(torch.double),\n running_mean.to(torch.double),\n running_var.to(torch.double),\n weight=weight.to(torch.double),\n bias=bias.to(torch.double),\n )\n\n eager_output.backward(at_grads.to(torch.double))\n\n if channels_last:\n eager_grad = at_inputs.grad.permute((0, *range(2, num_dims), 1))\n else:\n eager_grad = at_inputs.grad\n\n fd.validate(\n [inputs, grads, weight, running_mean, running_var, mean, invstd],\n [eager_grad, weight.grad, bias.grad],\n )\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [inputs, grads, weight, running_mean, running_var, mean, invstd],\n )\n\n\ndef batchnorm_fwd_fn(inputs: list):\n input, weight, bias, running_mean, running_var = inputs\n return torch.nn.functional.batch_norm(\n input,\n running_mean,\n running_var,\n weight=weight,\n bias=bias,\n training=True,\n )\n\n\ndef instancenorm_fwd_fn(inputs: list):\n input, weight, bias, running_mean, running_var = inputs\n return torch.nn.functional.instance_norm(\n input,\n running_mean,\n running_var,","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.batchnorm_fwd_fn","uri":"program://Fuser/function/benchmarks.python.normalization.batchnorm_fwd_fn#L378-L387","kind":"function","name":"batchnorm_fwd_fn","path":"benchmarks/python/normalization.py","language":"python","start_line":378,"end_line":387,"context_start_line":358,"context_end_line":407,"code":" eager_output.backward(at_grads.to(torch.double))\n\n if channels_last:\n eager_grad = at_inputs.grad.permute((0, *range(2, num_dims), 1))\n else:\n eager_grad = at_inputs.grad\n\n fd.validate(\n [inputs, grads, weight, running_mean, running_var, mean, invstd],\n [eager_grad, weight.grad, bias.grad],\n )\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [inputs, grads, weight, running_mean, running_var, mean, invstd],\n )\n\n\ndef batchnorm_fwd_fn(inputs: list):\n input, weight, bias, running_mean, running_var = inputs\n return torch.nn.functional.batch_norm(\n input,\n running_mean,\n running_var,\n weight=weight,\n bias=bias,\n training=True,\n )\n\n\ndef instancenorm_fwd_fn(inputs: list):\n input, weight, bias, running_mean, running_var = inputs\n return torch.nn.functional.instance_norm(\n input,\n running_mean,\n running_var,\n weight=weight,\n bias=bias,\n )\n\n\ndef norm_fwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation required since nvFuser outputs (out, mean, invstd) differs from baselines (out)\n # size = [N, C, H, W]\n # Total IO bytes = in_tensor (size, dtype) + weight (size[1], dtype) + bias (size[1], dtype) +\n # running_mean (size[1], float) + running_var (size[1], float) + output (size, dtype) +\n # mean ([C]/[N, C] , float) + invstd ([C]/[N, C] , float)\n stat_size = (","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.instancenorm_fwd_fn","uri":"program://Fuser/function/benchmarks.python.normalization.instancenorm_fwd_fn#L390-L398","kind":"function","name":"instancenorm_fwd_fn","path":"benchmarks/python/normalization.py","language":"python","start_line":390,"end_line":398,"context_start_line":370,"context_end_line":418,"code":" if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [inputs, grads, weight, running_mean, running_var, mean, invstd],\n )\n\n\ndef batchnorm_fwd_fn(inputs: list):\n input, weight, bias, running_mean, running_var = inputs\n return torch.nn.functional.batch_norm(\n input,\n running_mean,\n running_var,\n weight=weight,\n bias=bias,\n training=True,\n )\n\n\ndef instancenorm_fwd_fn(inputs: list):\n input, weight, bias, running_mean, running_var = inputs\n return torch.nn.functional.instance_norm(\n input,\n running_mean,\n running_var,\n weight=weight,\n bias=bias,\n )\n\n\ndef norm_fwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation required since nvFuser outputs (out, mean, invstd) differs from baselines (out)\n # size = [N, C, H, W]\n # Total IO bytes = in_tensor (size, dtype) + weight (size[1], dtype) + bias (size[1], dtype) +\n # running_mean (size[1], float) + running_var (size[1], float) + output (size, dtype) +\n # mean ([C]/[N, C] , float) + invstd ([C]/[N, C] , float)\n stat_size = (\n size[1] if norm == \"batch_norm\" else size[0] * size[1]\n ) # size of mean/invstd\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * (size[1] + stat_size)\n )\n\n\ndef norm_bwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, mean, invstd, weigts, grad_in, grad_weight, grad_bias) differ from baselines (out, grad_out)\n # size = [N, C, H, W]","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.norm_fwd_iobytes","uri":"program://Fuser/function/benchmarks.python.normalization.norm_fwd_iobytes#L401-L413","kind":"function","name":"norm_fwd_iobytes","path":"benchmarks/python/normalization.py","language":"python","start_line":401,"end_line":413,"context_start_line":381,"context_end_line":433,"code":" input,\n running_mean,\n running_var,\n weight=weight,\n bias=bias,\n training=True,\n )\n\n\ndef instancenorm_fwd_fn(inputs: list):\n input, weight, bias, running_mean, running_var = inputs\n return torch.nn.functional.instance_norm(\n input,\n running_mean,\n running_var,\n weight=weight,\n bias=bias,\n )\n\n\ndef norm_fwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation required since nvFuser outputs (out, mean, invstd) differs from baselines (out)\n # size = [N, C, H, W]\n # Total IO bytes = in_tensor (size, dtype) + weight (size[1], dtype) + bias (size[1], dtype) +\n # running_mean (size[1], float) + running_var (size[1], float) + output (size, dtype) +\n # mean ([C]/[N, C] , float) + invstd ([C]/[N, C] , float)\n stat_size = (\n size[1] if norm == \"batch_norm\" else size[0] * size[1]\n ) # size of mean/invstd\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * (size[1] + stat_size)\n )\n\n\ndef norm_bwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, mean, invstd, weigts, grad_in, grad_weight, grad_bias) differ from baselines (out, grad_out)\n # size = [N, C, H, W]\n # Total IO bytes = in_tensor (size, dtype) + weight (size[1], dtype) +\n # running_mean (size[1], float) + running_var (size[1], float) +\n # mean ([C]/[N, C] , float) + invstd ([C]/[N, C] , float) + grad_out (size, dtype) +\n # grad_in (size, dtype) + grad_weight (size[1], dtype) + grad_bias (size[1], dtype)\n stat_size = size[1] if norm == \"batch_norm\" else size[0] * size[1]\n return int(\n dtype.itemsize * 3 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * (size[1] + stat_size)\n )\n\n\ndef norm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.norm_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.normalization.norm_bwd_iobytes#L416-L427","kind":"function","name":"norm_bwd_iobytes","path":"benchmarks/python/normalization.py","language":"python","start_line":416,"end_line":427,"context_start_line":396,"context_end_line":447,"code":" weight=weight,\n bias=bias,\n )\n\n\ndef norm_fwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation required since nvFuser outputs (out, mean, invstd) differs from baselines (out)\n # size = [N, C, H, W]\n # Total IO bytes = in_tensor (size, dtype) + weight (size[1], dtype) + bias (size[1], dtype) +\n # running_mean (size[1], float) + running_var (size[1], float) + output (size, dtype) +\n # mean ([C]/[N, C] , float) + invstd ([C]/[N, C] , float)\n stat_size = (\n size[1] if norm == \"batch_norm\" else size[0] * size[1]\n ) # size of mean/invstd\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * (size[1] + stat_size)\n )\n\n\ndef norm_bwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, mean, invstd, weigts, grad_in, grad_weight, grad_bias) differ from baselines (out, grad_out)\n # size = [N, C, H, W]\n # Total IO bytes = in_tensor (size, dtype) + weight (size[1], dtype) +\n # running_mean (size[1], float) + running_var (size[1], float) +\n # mean ([C]/[N, C] , float) + invstd ([C]/[N, C] , float) + grad_out (size, dtype) +\n # grad_in (size, dtype) + grad_weight (size[1], dtype) + grad_bias (size[1], dtype)\n stat_size = size[1] if norm == \"batch_norm\" else size[0] * size[1]\n return int(\n dtype.itemsize * 3 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * (size[1] + stat_size)\n )\n\n\ndef norm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n executor: str,\n norm: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.norm_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.normalization.norm_fwd_baseline_benchmark#L430-L463","kind":"function","name":"norm_fwd_baseline_benchmark","path":"benchmarks/python/normalization.py","language":"python","start_line":430,"end_line":463,"context_start_line":410,"context_end_line":483,"code":" return int(\n dtype.itemsize * 2 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * (size[1] + stat_size)\n )\n\n\ndef norm_bwd_iobytes(size: tuple, dtype: torch.dtype, norm: str):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, mean, invstd, weigts, grad_in, grad_weight, grad_bias) differ from baselines (out, grad_out)\n # size = [N, C, H, W]\n # Total IO bytes = in_tensor (size, dtype) + weight (size[1], dtype) +\n # running_mean (size[1], float) + running_var (size[1], float) +\n # mean ([C]/[N, C] , float) + invstd ([C]/[N, C] , float) + grad_out (size, dtype) +\n # grad_in (size, dtype) + grad_weight (size[1], dtype) + grad_bias (size[1], dtype)\n stat_size = size[1] if norm == \"batch_norm\" else size[0] * size[1]\n return int(\n dtype.itemsize * 3 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * (size[1] + stat_size)\n )\n\n\ndef norm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n executor: str,\n norm: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n running_mean = torch.zeros(size[1], device=\"cuda\", dtype=dtype)\n running_var = torch.ones(size[1], device=\"cuda\", dtype=dtype)\n if channels_last:\n inputs = inputs.to(memory_format=torch.channels_last)\n\n norm_fwd_fn = batchnorm_fwd_fn if norm == \"batch_norm\" else instancenorm_fwd_fn\n\n benchmark_fn = with_executor(executor, norm_fwd_fn)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, weight, bias, running_mean, running_var],\n iobytes=norm_fwd_iobytes(size, dtype, norm),\n )\n\n\ndef norm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n executor: str,\n norm: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.normalization.norm_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.normalization.norm_bwd_baseline_benchmark#L466-L504","kind":"function","name":"norm_bwd_baseline_benchmark","path":"benchmarks/python/normalization.py","language":"python","start_line":466,"end_line":504,"context_start_line":446,"context_end_line":504,"code":" bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n running_mean = torch.zeros(size[1], device=\"cuda\", dtype=dtype)\n running_var = torch.ones(size[1], device=\"cuda\", dtype=dtype)\n if channels_last:\n inputs = inputs.to(memory_format=torch.channels_last)\n\n norm_fwd_fn = batchnorm_fwd_fn if norm == \"batch_norm\" else instancenorm_fwd_fn\n\n benchmark_fn = with_executor(executor, norm_fwd_fn)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, weight, bias, running_mean, running_var],\n iobytes=norm_fwd_iobytes(size, dtype, norm),\n )\n\n\ndef norm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n executor: str,\n norm: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n assert norm in [\"batch_norm\", \"instance_norm\"], NotImplementedError\n\n # Size is assumed to be in the order N, C, ...\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n weight = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n running_mean = torch.zeros(size[1], device=\"cuda\", dtype=dtype)\n running_var = torch.ones(size[1], device=\"cuda\", dtype=dtype)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n if channels_last:\n inputs = inputs.to(memory_format=torch.channels_last)\n grads = grads.to(memory_format=torch.channels_last)\n\n norm_fwd_fn = batchnorm_fwd_fn if norm == \"batch_norm\" else instancenorm_fwd_fn\n\n fwd_fn = with_executor(executor, norm_fwd_fn)\n fwd_inputs = [inputs, weight, bias, running_mean, running_var]\n outputs = fwd_fn(fwd_inputs)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=norm_bwd_iobytes(size, dtype, norm),\n )","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_pointwise_mul","uri":"program://Fuser/module/benchmarks.python.test_pointwise_mul#L1-L75","kind":"module","name":"benchmarks.python.test_pointwise_mul","path":"benchmarks/python/test_pointwise_mul.py","language":"python","start_line":1,"end_line":75,"context_start_line":1,"context_end_line":75,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef pointwise_mul_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.mul(T0, T0)\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=dtype)\n fd.add_output(T2)\n\n\ndef pointwise_mul_fwd_fn(inputs: list): # in_tensor\n return torch.mul(inputs[0], inputs[0])\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_pointwise_mul_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n pointwise_mul_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.mul(inputs[0].to(torch.double), inputs[0].to(torch.double))\n fd.validate(inputs, [eager_output.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_pointwise_mul_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n input = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n benchmark_fn = with_executor(executor, pointwise_mul_fwd_fn)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(\n benchmark,\n benchmark_fn,\n [input],\n )","source_hash":"9ec21ff076e00259c54ca25e589cfe059cd0014e8a9039244ef6cdcdce74df0f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_pointwise_mul.pointwise_mul_fusion","uri":"program://Fuser/function/benchmarks.python.test_pointwise_mul.pointwise_mul_fusion#L12-L24","kind":"function","name":"pointwise_mul_fusion","path":"benchmarks/python/test_pointwise_mul.py","language":"python","start_line":12,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef pointwise_mul_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.mul(T0, T0)\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=dtype)\n fd.add_output(T2)\n\n\ndef pointwise_mul_fwd_fn(inputs: list): # in_tensor\n return torch.mul(inputs[0], inputs[0])\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_pointwise_mul_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n pointwise_mul_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))","source_hash":"9ec21ff076e00259c54ca25e589cfe059cd0014e8a9039244ef6cdcdce74df0f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_pointwise_mul.pointwise_mul_fwd_fn","uri":"program://Fuser/function/benchmarks.python.test_pointwise_mul.pointwise_mul_fwd_fn#L27-L28","kind":"function","name":"pointwise_mul_fwd_fn","path":"benchmarks/python/test_pointwise_mul.py","language":"python","start_line":27,"end_line":28,"context_start_line":7,"context_end_line":48,"code":"from .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef pointwise_mul_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.mul(T0, T0)\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=dtype)\n fd.add_output(T2)\n\n\ndef pointwise_mul_fwd_fn(inputs: list): # in_tensor\n return torch.mul(inputs[0], inputs[0])\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_pointwise_mul_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n pointwise_mul_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.mul(inputs[0].to(torch.double), inputs[0].to(torch.double))\n fd.validate(inputs, [eager_output.to(dtype)])","source_hash":"9ec21ff076e00259c54ca25e589cfe059cd0014e8a9039244ef6cdcdce74df0f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_pointwise_mul.test_pointwise_mul_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_pointwise_mul.test_pointwise_mul_nvf_benchmark#L34-L51","kind":"function","name":"test_pointwise_mul_nvf_benchmark","path":"benchmarks/python/test_pointwise_mul.py","language":"python","start_line":34,"end_line":51,"context_start_line":14,"context_end_line":71,"code":" dtype: DataType,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.mul(T0, T0)\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=dtype)\n fd.add_output(T2)\n\n\ndef pointwise_mul_fwd_fn(inputs: list): # in_tensor\n return torch.mul(inputs[0], inputs[0])\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_pointwise_mul_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n pointwise_mul_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.mul(inputs[0].to(torch.double), inputs[0].to(torch.double))\n fd.validate(inputs, [eager_output.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_pointwise_mul_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n input = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n benchmark_fn = with_executor(executor, pointwise_mul_fwd_fn)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(","source_hash":"9ec21ff076e00259c54ca25e589cfe059cd0014e8a9039244ef6cdcdce74df0f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_pointwise_mul.test_pointwise_mul_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_pointwise_mul.test_pointwise_mul_baseline_benchmark#L58-L75","kind":"function","name":"test_pointwise_mul_baseline_benchmark","path":"benchmarks/python/test_pointwise_mul.py","language":"python","start_line":58,"end_line":75,"context_start_line":38,"context_end_line":75,"code":" disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n pointwise_mul_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.mul(inputs[0].to(torch.double), inputs[0].to(torch.double))\n fd.validate(inputs, [eager_output.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_pointwise_mul_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n input = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n benchmark_fn = with_executor(executor, pointwise_mul_fwd_fn)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(\n benchmark,\n benchmark_fn,\n [input],\n )","source_hash":"9ec21ff076e00259c54ca25e589cfe059cd0014e8a9039244ef6cdcdce74df0f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_batchnorm_fwd","uri":"program://Fuser/module/benchmarks.python.test_batchnorm_fwd#L1-L56","kind":"module","name":"benchmarks.python.test_batchnorm_fwd","path":"benchmarks/python/test_batchnorm_fwd.py","language":"python","start_line":1,"end_line":56,"context_start_line":1,"context_end_line":56,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_fwd_nvf_benchmark, norm_fwd_baseline_benchmark\nfrom .core import DEFAULT_EXECUTORS\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n norm_fwd_nvf_benchmark(\n benchmark,\n size,\n dtype,\n \"batch_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n eps,\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_fwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_fwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"batch_norm\"\n )","source_hash":"302421ae331c310ceac218ecf265478a7ee883d909def27d7bfd8225a65a60ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_batchnorm_fwd.test_batchnorm_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_batchnorm_fwd.test_batchnorm_fwd_nvf_benchmark#L20-L38","kind":"function","name":"test_batchnorm_fwd_nvf_benchmark","path":"benchmarks/python/test_batchnorm_fwd.py","language":"python","start_line":20,"end_line":38,"context_start_line":1,"context_end_line":56,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_fwd_nvf_benchmark, norm_fwd_baseline_benchmark\nfrom .core import DEFAULT_EXECUTORS\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n norm_fwd_nvf_benchmark(\n benchmark,\n size,\n dtype,\n \"batch_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n eps,\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_fwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_fwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"batch_norm\"\n )","source_hash":"302421ae331c310ceac218ecf265478a7ee883d909def27d7bfd8225a65a60ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_batchnorm_fwd.test_batchnorm_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_batchnorm_fwd.test_batchnorm_fwd_baseline_benchmark#L51-L56","kind":"function","name":"test_batchnorm_fwd_baseline_benchmark","path":"benchmarks/python/test_batchnorm_fwd.py","language":"python","start_line":51,"end_line":56,"context_start_line":31,"context_end_line":56,"code":" size,\n dtype,\n \"batch_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n eps,\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_fwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_fwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"batch_norm\"\n )","source_hash":"302421ae331c310ceac218ecf265478a7ee883d909def27d7bfd8225a65a60ce","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction","uri":"program://Fuser/module/benchmarks.python.test_reduction#L1-L80","kind":"module","name":"benchmarks.python.test_reduction","path":"benchmarks/python/test_reduction.py","language":"python","start_line":1,"end_line":80,"context_start_line":1,"context_end_line":80,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef reduction_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n reduction_axis: int,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.sum(T0, dims=[reduction_axis], keepdim=False)\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=dtype)\n fd.add_output(T2)\n\n\ndef reduction_fwd_fn(inputs: list): # in_tensor, reduction_axis\n return torch.sum(inputs[0], dim=inputs[1])\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_reduction_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(*size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n reduction_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis)\n\n if not disable_validation:\n eager_output = torch.sum(inputs[0].to(torch.double), dim=reduction_axis)\n fd.validate(inputs, [eager_output.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_reduction_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n input = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n benchmark_fn = with_executor(executor, reduction_fwd_fn)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(\n benchmark,\n benchmark_fn,\n [input, reduction_axis],\n )","source_hash":"eeb2a64c3468f47f8c4e79a991ac442cbc4ffbb2679101386f2e26ac26e22d35","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction.reduction_fusion","uri":"program://Fuser/function/benchmarks.python.test_reduction.reduction_fusion#L12-L25","kind":"function","name":"reduction_fusion","path":"benchmarks/python/test_reduction.py","language":"python","start_line":12,"end_line":25,"context_start_line":1,"context_end_line":45,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef reduction_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n reduction_axis: int,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.sum(T0, dims=[reduction_axis], keepdim=False)\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=dtype)\n fd.add_output(T2)\n\n\ndef reduction_fwd_fn(inputs: list): # in_tensor, reduction_axis\n return torch.sum(inputs[0], dim=inputs[1])\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_reduction_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(*size, device=\"cuda\", dtype=dtype)]\n","source_hash":"eeb2a64c3468f47f8c4e79a991ac442cbc4ffbb2679101386f2e26ac26e22d35","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction.reduction_fwd_fn","uri":"program://Fuser/function/benchmarks.python.test_reduction.reduction_fwd_fn#L28-L29","kind":"function","name":"reduction_fwd_fn","path":"benchmarks/python/test_reduction.py","language":"python","start_line":28,"end_line":29,"context_start_line":8,"context_end_line":49,"code":"import torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef reduction_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n reduction_axis: int,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.sum(T0, dims=[reduction_axis], keepdim=False)\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=dtype)\n fd.add_output(T2)\n\n\ndef reduction_fwd_fn(inputs: list): # in_tensor, reduction_axis\n return torch.sum(inputs[0], dim=inputs[1])\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_reduction_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(*size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n reduction_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis)\n\n if not disable_validation:","source_hash":"eeb2a64c3468f47f8c4e79a991ac442cbc4ffbb2679101386f2e26ac26e22d35","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction.test_reduction_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_reduction.test_reduction_nvf_benchmark#L36-L54","kind":"function","name":"test_reduction_nvf_benchmark","path":"benchmarks/python/test_reduction.py","language":"python","start_line":36,"end_line":54,"context_start_line":16,"context_end_line":74,"code":") -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.sum(T0, dims=[reduction_axis], keepdim=False)\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=dtype)\n fd.add_output(T2)\n\n\ndef reduction_fwd_fn(inputs: list): # in_tensor, reduction_axis\n return torch.sum(inputs[0], dim=inputs[1])\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_reduction_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(*size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n reduction_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis)\n\n if not disable_validation:\n eager_output = torch.sum(inputs[0].to(torch.double), dim=reduction_axis)\n fd.validate(inputs, [eager_output.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_reduction_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n input = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n benchmark_fn = with_executor(executor, reduction_fwd_fn)\n","source_hash":"eeb2a64c3468f47f8c4e79a991ac442cbc4ffbb2679101386f2e26ac26e22d35","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_reduction.test_reduction_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_reduction.test_reduction_baseline_benchmark#L62-L80","kind":"function","name":"test_reduction_baseline_benchmark","path":"benchmarks/python/test_reduction.py","language":"python","start_line":62,"end_line":80,"context_start_line":42,"context_end_line":80,"code":" disable_benchmarking: bool,\n):\n inputs = [torch.randn(*size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n reduction_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis)\n\n if not disable_validation:\n eager_output = torch.sum(inputs[0].to(torch.double), dim=reduction_axis)\n fd.validate(inputs, [eager_output.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_reduction_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n input = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n benchmark_fn = with_executor(executor, reduction_fwd_fn)\n\n # Inputs and outputs are same as nvFuser, no need for manual IOByte computation\n run_benchmark(\n benchmark,\n benchmark_fn,\n [input, reduction_axis],\n )","source_hash":"eeb2a64c3468f47f8c4e79a991ac442cbc4ffbb2679101386f2e26ac26e22d35","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_groupnorm_fwd","uri":"program://Fuser/module/benchmarks.python.test_groupnorm_fwd#L1-L153","kind":"module","name":"benchmarks.python.test_groupnorm_fwd","path":"benchmarks/python/test_groupnorm_fwd.py","language":"python","start_line":1,"end_line":153,"context_start_line":1,"context_end_line":153,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef get_n_groups(C):\n # start num_groups from 1 and increase to 32 at max\n # 32 is a widely used value for num_groups\n # it doesn't make sense to use num_groups > C\n num_groups = 1\n while num_groups * 2 <= 32 and C % (num_groups * 2) == 0:\n num_groups *= 2\n return num_groups\n\n\n# This version is based on requires_grad = False.\n# When requires_grad = True, two additional tensors (T4, T14) are added to outputs.\ndef groupnorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n n_groups: int = 32,\n eps: float = 1e-5,\n) -> None:\n # inputs, T0-x, T1-weight, T2-bias\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T2 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n # initial input shape: [N, C, H, W]\n # reshape input to [N, n_groups, C//n_groups, H, W] and do normalization with scale and bias\n # reshape back to [N, C, H, W]\n V0 = T0.shape()\n G0 = fd.define_scalar(n_groups, dtype=DataType.Int)\n C0 = fd.ops.div(T0.size(1), G0)\n T0 = fd.ops.reshape(\n T0, new_shape=[T0.size(0), n_groups, C0, T0.size(2), T0.size(3)]\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n T3, T4 = fd.ops.var_mean(T0, dims=[2, 3, 4], correction=0, keepdim=False)\n\n T7 = fd.ops.broadcast_in_dim(\n T3, shape=[T0.size(0), n_groups, 1, 1, 1], broadcast_dims=[0, 1]\n )\n T11 = fd.ops.broadcast_in_dim(\n T4, shape=[T0.size(0), n_groups, 1, 1, 1], broadcast_dims=[0, 1]\n )\n\n S12 = fd.define_scalar(eps, dtype=DataType.Double)\n T13 = fd.ops.add(T7, S12)\n T14 = fd.ops.rsqrt(T13)\n # N, G, C//G, H, W\n V3 = T0.shape()\n T18 = fd.ops.broadcast_in_dim(T11, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T19 = fd.ops.sub(T0, T18)\n T23 = fd.ops.broadcast_in_dim(T14, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T24 = fd.ops.mul(T19, T23)\n\n # reshape weights and bias to [1, n_groups, C//n_groups, 1, 1]\n # due to https://github.com/NVIDIA/Fuser/issues/2671 must define C1 and C2\n # using T1.size(0) and T2.size(0), can't directly reuse C0 which is based on T0.size(1)\n C1 = fd.ops.div(T1.size(0), G0)\n T1 = fd.ops.reshape(T1, new_shape=[1, n_groups, C1, 1, 1])\n\n C2 = fd.ops.div(T2.size(0), G0)\n T2 = fd.ops.reshape(T2, new_shape=[1, n_groups, C2, 1, 1])\n\n # broadcast weights and bias to [N, n_groups, C//n_groups, H, W]\n T25 = fd.ops.broadcast_in_dim(T1, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T26 = fd.ops.mul(T24, T25)\n T27 = fd.ops.broadcast_in_dim(T2, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T28 = fd.ops.add(T26, T27)\n\n # convert back to original dtype and shape\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T28 = fd.ops.reshape(T28, new_shape=V0)\n fd.add_output(T28)\n\n\ndef groupnorm_fwd(inputs: list): # [in_tensor, weights, bias, n_groups]\n return torch.nn.functional.group_norm(\n inputs[0], num_groups=inputs[3], weight=inputs[1], bias=inputs[2], eps=1e-05\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_groupnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n N, C, H, W = size\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n weight = torch.randn(C, device=\"cuda\", dtype=dtype)\n bias = torch.randn(C, device=\"cuda\", dtype=dtype)\n num_groups = get_n_groups(C)\n\n with FusionDefinition() as fd:\n groupnorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), num_groups)\n\n if not disable_validation:\n eager_output = groupnorm_fwd([x, weight, bias, num_groups])\n fd.validate([x, weight, bias], [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [x, weight, bias])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_groupnorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n N, C, H, W = size\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n weight = torch.randn(C, device=\"cuda\", dtype=dtype)\n bias = torch.randn(C, device=\"cuda\", dtype=dtype)\n num_groups = get_n_groups(C)\n\n benchmark_fn = with_executor(executor, groupnorm_fwd)\n\n run_benchmark(\n benchmark,\n benchmark_fn,\n [x, weight, bias, num_groups],\n )","source_hash":"3cfdff05b8f25e6094b238a67f13967849f0de39cfdabd2973aedbeddc55c54e","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_groupnorm_fwd.get_n_groups","uri":"program://Fuser/function/benchmarks.python.test_groupnorm_fwd.get_n_groups#L12-L19","kind":"function","name":"get_n_groups","path":"benchmarks/python/test_groupnorm_fwd.py","language":"python","start_line":12,"end_line":19,"context_start_line":1,"context_end_line":39,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef get_n_groups(C):\n # start num_groups from 1 and increase to 32 at max\n # 32 is a widely used value for num_groups\n # it doesn't make sense to use num_groups > C\n num_groups = 1\n while num_groups * 2 <= 32 and C % (num_groups * 2) == 0:\n num_groups *= 2\n return num_groups\n\n\n# This version is based on requires_grad = False.\n# When requires_grad = True, two additional tensors (T4, T14) are added to outputs.\ndef groupnorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n n_groups: int = 32,\n eps: float = 1e-5,\n) -> None:\n # inputs, T0-x, T1-weight, T2-bias\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T2 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n","source_hash":"3cfdff05b8f25e6094b238a67f13967849f0de39cfdabd2973aedbeddc55c54e","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_groupnorm_fwd.groupnorm_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_groupnorm_fwd.groupnorm_fwd_fusion#L24-L92","kind":"function","name":"groupnorm_fwd_fusion","path":"benchmarks/python/test_groupnorm_fwd.py","language":"python","start_line":24,"end_line":92,"context_start_line":4,"context_end_line":112,"code":"import pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef get_n_groups(C):\n # start num_groups from 1 and increase to 32 at max\n # 32 is a widely used value for num_groups\n # it doesn't make sense to use num_groups > C\n num_groups = 1\n while num_groups * 2 <= 32 and C % (num_groups * 2) == 0:\n num_groups *= 2\n return num_groups\n\n\n# This version is based on requires_grad = False.\n# When requires_grad = True, two additional tensors (T4, T14) are added to outputs.\ndef groupnorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n n_groups: int = 32,\n eps: float = 1e-5,\n) -> None:\n # inputs, T0-x, T1-weight, T2-bias\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T2 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n # initial input shape: [N, C, H, W]\n # reshape input to [N, n_groups, C//n_groups, H, W] and do normalization with scale and bias\n # reshape back to [N, C, H, W]\n V0 = T0.shape()\n G0 = fd.define_scalar(n_groups, dtype=DataType.Int)\n C0 = fd.ops.div(T0.size(1), G0)\n T0 = fd.ops.reshape(\n T0, new_shape=[T0.size(0), n_groups, C0, T0.size(2), T0.size(3)]\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n T3, T4 = fd.ops.var_mean(T0, dims=[2, 3, 4], correction=0, keepdim=False)\n\n T7 = fd.ops.broadcast_in_dim(\n T3, shape=[T0.size(0), n_groups, 1, 1, 1], broadcast_dims=[0, 1]\n )\n T11 = fd.ops.broadcast_in_dim(\n T4, shape=[T0.size(0), n_groups, 1, 1, 1], broadcast_dims=[0, 1]\n )\n\n S12 = fd.define_scalar(eps, dtype=DataType.Double)\n T13 = fd.ops.add(T7, S12)\n T14 = fd.ops.rsqrt(T13)\n # N, G, C//G, H, W\n V3 = T0.shape()\n T18 = fd.ops.broadcast_in_dim(T11, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T19 = fd.ops.sub(T0, T18)\n T23 = fd.ops.broadcast_in_dim(T14, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T24 = fd.ops.mul(T19, T23)\n\n # reshape weights and bias to [1, n_groups, C//n_groups, 1, 1]\n # due to https://github.com/NVIDIA/Fuser/issues/2671 must define C1 and C2\n # using T1.size(0) and T2.size(0), can't directly reuse C0 which is based on T0.size(1)\n C1 = fd.ops.div(T1.size(0), G0)\n T1 = fd.ops.reshape(T1, new_shape=[1, n_groups, C1, 1, 1])\n\n C2 = fd.ops.div(T2.size(0), G0)\n T2 = fd.ops.reshape(T2, new_shape=[1, n_groups, C2, 1, 1])\n\n # broadcast weights and bias to [N, n_groups, C//n_groups, H, W]\n T25 = fd.ops.broadcast_in_dim(T1, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T26 = fd.ops.mul(T24, T25)\n T27 = fd.ops.broadcast_in_dim(T2, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T28 = fd.ops.add(T26, T27)\n\n # convert back to original dtype and shape\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T28 = fd.ops.reshape(T28, new_shape=V0)\n fd.add_output(T28)\n\n\ndef groupnorm_fwd(inputs: list): # [in_tensor, weights, bias, n_groups]\n return torch.nn.functional.group_norm(\n inputs[0], num_groups=inputs[3], weight=inputs[1], bias=inputs[2], eps=1e-05\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_groupnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n N, C, H, W = size","source_hash":"3cfdff05b8f25e6094b238a67f13967849f0de39cfdabd2973aedbeddc55c54e","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_groupnorm_fwd.groupnorm_fwd","uri":"program://Fuser/function/benchmarks.python.test_groupnorm_fwd.groupnorm_fwd#L95-L98","kind":"function","name":"groupnorm_fwd","path":"benchmarks/python/test_groupnorm_fwd.py","language":"python","start_line":95,"end_line":98,"context_start_line":75,"context_end_line":118,"code":" # using T1.size(0) and T2.size(0), can't directly reuse C0 which is based on T0.size(1)\n C1 = fd.ops.div(T1.size(0), G0)\n T1 = fd.ops.reshape(T1, new_shape=[1, n_groups, C1, 1, 1])\n\n C2 = fd.ops.div(T2.size(0), G0)\n T2 = fd.ops.reshape(T2, new_shape=[1, n_groups, C2, 1, 1])\n\n # broadcast weights and bias to [N, n_groups, C//n_groups, H, W]\n T25 = fd.ops.broadcast_in_dim(T1, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T26 = fd.ops.mul(T24, T25)\n T27 = fd.ops.broadcast_in_dim(T2, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T28 = fd.ops.add(T26, T27)\n\n # convert back to original dtype and shape\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T28 = fd.ops.reshape(T28, new_shape=V0)\n fd.add_output(T28)\n\n\ndef groupnorm_fwd(inputs: list): # [in_tensor, weights, bias, n_groups]\n return torch.nn.functional.group_norm(\n inputs[0], num_groups=inputs[3], weight=inputs[1], bias=inputs[2], eps=1e-05\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_groupnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n N, C, H, W = size\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n weight = torch.randn(C, device=\"cuda\", dtype=dtype)\n bias = torch.randn(C, device=\"cuda\", dtype=dtype)\n num_groups = get_n_groups(C)\n\n with FusionDefinition() as fd:","source_hash":"3cfdff05b8f25e6094b238a67f13967849f0de39cfdabd2973aedbeddc55c54e","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_groupnorm_fwd.test_groupnorm_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_groupnorm_fwd.test_groupnorm_fwd_nvf_benchmark#L104-L126","kind":"function","name":"test_groupnorm_fwd_nvf_benchmark","path":"benchmarks/python/test_groupnorm_fwd.py","language":"python","start_line":104,"end_line":126,"context_start_line":84,"context_end_line":146,"code":" T26 = fd.ops.mul(T24, T25)\n T27 = fd.ops.broadcast_in_dim(T2, shape=V3, broadcast_dims=[0, 1, 2, 3, 4])\n T28 = fd.ops.add(T26, T27)\n\n # convert back to original dtype and shape\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T28 = fd.ops.reshape(T28, new_shape=V0)\n fd.add_output(T28)\n\n\ndef groupnorm_fwd(inputs: list): # [in_tensor, weights, bias, n_groups]\n return torch.nn.functional.group_norm(\n inputs[0], num_groups=inputs[3], weight=inputs[1], bias=inputs[2], eps=1e-05\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_groupnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n N, C, H, W = size\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n weight = torch.randn(C, device=\"cuda\", dtype=dtype)\n bias = torch.randn(C, device=\"cuda\", dtype=dtype)\n num_groups = get_n_groups(C)\n\n with FusionDefinition() as fd:\n groupnorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), num_groups)\n\n if not disable_validation:\n eager_output = groupnorm_fwd([x, weight, bias, num_groups])\n fd.validate([x, weight, bias], [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [x, weight, bias])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_groupnorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n N, C, H, W = size\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n weight = torch.randn(C, device=\"cuda\", dtype=dtype)\n bias = torch.randn(C, device=\"cuda\", dtype=dtype)\n num_groups = get_n_groups(C)\n","source_hash":"3cfdff05b8f25e6094b238a67f13967849f0de39cfdabd2973aedbeddc55c54e","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_groupnorm_fwd.test_groupnorm_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_groupnorm_fwd.test_groupnorm_fwd_baseline_benchmark#L133-L153","kind":"function","name":"test_groupnorm_fwd_baseline_benchmark","path":"benchmarks/python/test_groupnorm_fwd.py","language":"python","start_line":133,"end_line":153,"context_start_line":113,"context_end_line":153,"code":" x = torch.randn(size, device=\"cuda\", dtype=dtype)\n weight = torch.randn(C, device=\"cuda\", dtype=dtype)\n bias = torch.randn(C, device=\"cuda\", dtype=dtype)\n num_groups = get_n_groups(C)\n\n with FusionDefinition() as fd:\n groupnorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), num_groups)\n\n if not disable_validation:\n eager_output = groupnorm_fwd([x, weight, bias, num_groups])\n fd.validate([x, weight, bias], [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [x, weight, bias])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_groupnorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n N, C, H, W = size\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n weight = torch.randn(C, device=\"cuda\", dtype=dtype)\n bias = torch.randn(C, device=\"cuda\", dtype=dtype)\n num_groups = get_n_groups(C)\n\n benchmark_fn = with_executor(executor, groupnorm_fwd)\n\n run_benchmark(\n benchmark,\n benchmark_fn,\n [x, weight, bias, num_groups],\n )","source_hash":"3cfdff05b8f25e6094b238a67f13967849f0de39cfdabd2973aedbeddc55c54e","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_bwd","uri":"program://Fuser/module/benchmarks.python.test_dropout_rmsnorm_bwd#L1-L203","kind":"module","name":"benchmarks.python.test_dropout_rmsnorm_bwd","path":"benchmarks/python/test_dropout_rmsnorm_bwd.py","language":"python","start_line":1,"end_line":203,"context_start_line":1,"context_end_line":203,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_rmsnorm\n\n\ndef dropout_rmsnorm_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n dropout_p: float,\n) -> None:\n \"\"\"\n Backward pass fusion definition for computing:\n output = rmsnorm (input2 + dropout (input1, p=dropout_p))\n\n Fusion inputs: input, dropout_mask, rms, grad_output, weights\n Fusion outputs: grad_input, grad_weights\n \"\"\"\n T5 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # input1\n T4 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # input2\n T6 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Bool, is_cpu=False\n ) # dropout_mask\n T7 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n ) # rms_eps\n T8 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # grads\n T9 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False\n ) # weights\n\n if dtype in PROMOTE_DTYPES:\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n T5 = fd.ops.cast(T5, dtype=DataType.Float)\n T6 = fd.ops.cast(T6, dtype=DataType.Float)\n T8 = fd.ops.cast(T8, dtype=DataType.Float)\n T9 = fd.ops.cast(T9, dtype=DataType.Float)\n\n T12 = fd.ops.mul(T5, T6)\n S13 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T14 = fd.ops.mul(T12, S13)\n T15 = fd.ops.add(T4, T14)\n\n V19 = T5.shape()\n T20 = fd.ops.broadcast_in_dim(T7, shape=V19, broadcast_dims=[0, 1])\n T22 = fd.ops.reciprocal(T20)\n T23 = fd.ops.mul(T15, T22)\n\n T27 = fd.ops.broadcast_in_dim(T9, shape=V19, broadcast_dims=[1])\n\n T30 = fd.ops.mul(T8, T23)\n T31 = fd.ops.mul(T8, T27)\n T32 = fd.ops.sum(T30, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T35 = fd.ops.mul(T31, T22)\n T36 = fd.ops.neg(T31)\n T37 = fd.ops.mul(T36, T15)\n S38 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T39 = fd.ops.pow(T20, S38)\n T40 = fd.ops.reciprocal(T39)\n T41 = fd.ops.mul(T37, T40)\n T42 = fd.ops.sum(T41, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T47 = fd.ops.broadcast_in_dim(T42, shape=[T5.size(0), 1], broadcast_dims=[0])\n\n T50 = fd.ops.mul(S38, T7)\n T51 = fd.ops.reciprocal(T50)\n T52 = fd.ops.mul(T47, T51)\n S55 = fd.ops.reciprocal(T5.size(1))\n T56 = fd.ops.mul(T52, S55)\n T57 = fd.ops.sum(T56, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T61 = fd.ops.broadcast_in_dim(T57, shape=[T5.size(0), 1], broadcast_dims=[0])\n T65 = fd.ops.broadcast_in_dim(T61, shape=V19, broadcast_dims=[0, 1])\n T66 = fd.ops.mul(T65, S38)\n T69 = fd.ops.mul(T66, T15)\n T70 = fd.ops.add(T35, T69)\n\n T73 = fd.ops.mul(T70, S13)\n T74 = fd.ops.mul(T73, T6)\n\n if dtype in PROMOTE_DTYPES:\n T70 = fd.ops.cast(T70, dtype=dtype)\n T74 = fd.ops.cast(T74, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T74)\n fd.add_output(T70)\n fd.add_output(T32)\n\n\ndef dropout_rmsnorm_bwd_iobytes(size, dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output, grad_out).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"rms\": (size[0], torch.float),\n \"grad_out\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n # Outputs\n \"grad_in1\": (size, dtype),\n \"grad_in2\": (size, dtype),\n \"grad_weights\": (size[1], dtype),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n dropout_p = 0.2\n dropout_mask = torch.lt(torch.rand(*size, device=\"cuda\"), 1 - dropout_p)\n\n # Manually compute dropout for validation\n x = input2 + 1 / (1 - dropout_p) * dropout_mask * input1\n squared_mean = (x.to(torch.float) ** 2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + eps)\n\n with FusionDefinition() as fd:\n dropout_rmsnorm_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p)\n\n if not disable_validation:\n eager_output = weights.to(torch.double) * (\n x.to(torch.double) / rms_eps.to(torch.double)\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate(\n [input1, input2, dropout_mask, rms_eps, grads, weights],\n [input1.grad, input2.grad, weights.grad],\n )\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [input1, input2, dropout_mask, rms_eps, grads, weights],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n dropout_p = 0.2\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n fwd_fn = with_executor(executor, dropout_rmsnorm)\n fwd_inputs = [input1, input2, weights, dropout_p]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=dropout_rmsnorm_bwd_iobytes(size, dtype),\n )","source_hash":"0501d66d223eaf8dfc5914be20df775bab9a4c191a3d1ebc2494dd38df7b3877","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_bwd.dropout_rmsnorm_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_dropout_rmsnorm_bwd.dropout_rmsnorm_bwd_fusion#L20-L108","kind":"function","name":"dropout_rmsnorm_bwd_fusion","path":"benchmarks/python/test_dropout_rmsnorm_bwd.py","language":"python","start_line":20,"end_line":108,"context_start_line":1,"context_end_line":128,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_rmsnorm\n\n\ndef dropout_rmsnorm_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n dropout_p: float,\n) -> None:\n \"\"\"\n Backward pass fusion definition for computing:\n output = rmsnorm (input2 + dropout (input1, p=dropout_p))\n\n Fusion inputs: input, dropout_mask, rms, grad_output, weights\n Fusion outputs: grad_input, grad_weights\n \"\"\"\n T5 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # input1\n T4 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # input2\n T6 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Bool, is_cpu=False\n ) # dropout_mask\n T7 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n ) # rms_eps\n T8 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n ) # grads\n T9 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False\n ) # weights\n\n if dtype in PROMOTE_DTYPES:\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n T5 = fd.ops.cast(T5, dtype=DataType.Float)\n T6 = fd.ops.cast(T6, dtype=DataType.Float)\n T8 = fd.ops.cast(T8, dtype=DataType.Float)\n T9 = fd.ops.cast(T9, dtype=DataType.Float)\n\n T12 = fd.ops.mul(T5, T6)\n S13 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T14 = fd.ops.mul(T12, S13)\n T15 = fd.ops.add(T4, T14)\n\n V19 = T5.shape()\n T20 = fd.ops.broadcast_in_dim(T7, shape=V19, broadcast_dims=[0, 1])\n T22 = fd.ops.reciprocal(T20)\n T23 = fd.ops.mul(T15, T22)\n\n T27 = fd.ops.broadcast_in_dim(T9, shape=V19, broadcast_dims=[1])\n\n T30 = fd.ops.mul(T8, T23)\n T31 = fd.ops.mul(T8, T27)\n T32 = fd.ops.sum(T30, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T35 = fd.ops.mul(T31, T22)\n T36 = fd.ops.neg(T31)\n T37 = fd.ops.mul(T36, T15)\n S38 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T39 = fd.ops.pow(T20, S38)\n T40 = fd.ops.reciprocal(T39)\n T41 = fd.ops.mul(T37, T40)\n T42 = fd.ops.sum(T41, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T47 = fd.ops.broadcast_in_dim(T42, shape=[T5.size(0), 1], broadcast_dims=[0])\n\n T50 = fd.ops.mul(S38, T7)\n T51 = fd.ops.reciprocal(T50)\n T52 = fd.ops.mul(T47, T51)\n S55 = fd.ops.reciprocal(T5.size(1))\n T56 = fd.ops.mul(T52, S55)\n T57 = fd.ops.sum(T56, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T61 = fd.ops.broadcast_in_dim(T57, shape=[T5.size(0), 1], broadcast_dims=[0])\n T65 = fd.ops.broadcast_in_dim(T61, shape=V19, broadcast_dims=[0, 1])\n T66 = fd.ops.mul(T65, S38)\n T69 = fd.ops.mul(T66, T15)\n T70 = fd.ops.add(T35, T69)\n\n T73 = fd.ops.mul(T70, S13)\n T74 = fd.ops.mul(T73, T6)\n\n if dtype in PROMOTE_DTYPES:\n T70 = fd.ops.cast(T70, dtype=dtype)\n T74 = fd.ops.cast(T74, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T74)\n fd.add_output(T70)\n fd.add_output(T32)\n\n\ndef dropout_rmsnorm_bwd_iobytes(size, dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output, grad_out).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"rms\": (size[0], torch.float),\n \"grad_out\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n # Outputs\n \"grad_in1\": (size, dtype),\n \"grad_in2\": (size, dtype),\n \"grad_weights\": (size[1], dtype),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n","source_hash":"0501d66d223eaf8dfc5914be20df775bab9a4c191a3d1ebc2494dd38df7b3877","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_bwd.dropout_rmsnorm_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_dropout_rmsnorm_bwd.dropout_rmsnorm_bwd_iobytes#L111-L126","kind":"function","name":"dropout_rmsnorm_bwd_iobytes","path":"benchmarks/python/test_dropout_rmsnorm_bwd.py","language":"python","start_line":111,"end_line":126,"context_start_line":91,"context_end_line":146,"code":"\n T61 = fd.ops.broadcast_in_dim(T57, shape=[T5.size(0), 1], broadcast_dims=[0])\n T65 = fd.ops.broadcast_in_dim(T61, shape=V19, broadcast_dims=[0, 1])\n T66 = fd.ops.mul(T65, S38)\n T69 = fd.ops.mul(T66, T15)\n T70 = fd.ops.add(T35, T69)\n\n T73 = fd.ops.mul(T70, S13)\n T74 = fd.ops.mul(T73, T6)\n\n if dtype in PROMOTE_DTYPES:\n T70 = fd.ops.cast(T70, dtype=dtype)\n T74 = fd.ops.cast(T74, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T74)\n fd.add_output(T70)\n fd.add_output(T32)\n\n\ndef dropout_rmsnorm_bwd_iobytes(size, dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output, grad_out).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"rms\": (size[0], torch.float),\n \"grad_out\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n # Outputs\n \"grad_in1\": (size, dtype),\n \"grad_in2\": (size, dtype),\n \"grad_weights\": (size[1], dtype),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n dropout_p = 0.2","source_hash":"0501d66d223eaf8dfc5914be20df775bab9a4c191a3d1ebc2494dd38df7b3877","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_bwd.test_dropout_rmsnorm_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_dropout_rmsnorm_bwd.test_dropout_rmsnorm_bwd_nvf_benchmark#L133-L172","kind":"function","name":"test_dropout_rmsnorm_bwd_nvf_benchmark","path":"benchmarks/python/test_dropout_rmsnorm_bwd.py","language":"python","start_line":133,"end_line":172,"context_start_line":113,"context_end_line":192,"code":" nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"rms\": (size[0], torch.float),\n \"grad_out\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n # Outputs\n \"grad_in1\": (size, dtype),\n \"grad_in2\": (size, dtype),\n \"grad_weights\": (size[1], dtype),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n dropout_p = 0.2\n dropout_mask = torch.lt(torch.rand(*size, device=\"cuda\"), 1 - dropout_p)\n\n # Manually compute dropout for validation\n x = input2 + 1 / (1 - dropout_p) * dropout_mask * input1\n squared_mean = (x.to(torch.float) ** 2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + eps)\n\n with FusionDefinition() as fd:\n dropout_rmsnorm_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p)\n\n if not disable_validation:\n eager_output = weights.to(torch.double) * (\n x.to(torch.double) / rms_eps.to(torch.double)\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate(\n [input1, input2, dropout_mask, rms_eps, grads, weights],\n [input1.grad, input2.grad, weights.grad],\n )\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [input1, input2, dropout_mask, rms_eps, grads, weights],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n dropout_p = 0.2\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)","source_hash":"0501d66d223eaf8dfc5914be20df775bab9a4c191a3d1ebc2494dd38df7b3877","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_bwd.test_dropout_rmsnorm_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_dropout_rmsnorm_bwd.test_dropout_rmsnorm_bwd_baseline_benchmark#L180-L203","kind":"function","name":"test_dropout_rmsnorm_bwd_baseline_benchmark","path":"benchmarks/python/test_dropout_rmsnorm_bwd.py","language":"python","start_line":180,"end_line":203,"context_start_line":160,"context_end_line":203,"code":" )\n eager_output.backward(grads.to(torch.double))\n fd.validate(\n [input1, input2, dropout_mask, rms_eps, grads, weights],\n [input1.grad, input2.grad, weights.grad],\n )\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n fd.execute,\n [input1, input2, dropout_mask, rms_eps, grads, weights],\n )\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n dropout_p = 0.2\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n fwd_fn = with_executor(executor, dropout_rmsnorm)\n fwd_inputs = [input1, input2, weights, dropout_p]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=dropout_rmsnorm_bwd_iobytes(size, dtype),\n )","source_hash":"0501d66d223eaf8dfc5914be20df775bab9a4c191a3d1ebc2494dd38df7b3877","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap","uri":"program://Fuser/module/benchmarks.python.benchmark_overlap#L1-L242","kind":"module","name":"benchmarks.python.benchmark_overlap","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":1,"end_line":242,"context_start_line":1,"context_end_line":242,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\nimport pytest\nimport torch\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition, CommunicatorBackend\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import BENCHMARK_CONFIG, clear_l2_cache\n\n# Run command:\n# export NVFUSER_BUILD_WITH_UCC=1\n# pip install --no-build-isolation -e python -v\n# mpirun -np 1 pytest benchmarks/python/benchmark_overlap.py --with-mpi\n\n\nclass CUDAEventTimer:\n \"\"\"Custom CUDA event-based timer for accurate GPU timing.\n\n This timer uses CUDA events to measure elapsed time between operations,\n providing more accurate GPU timing than CPU-based timing methods.\n \"\"\"\n\n def __init__(self):\n self.start_event = torch.cuda.Event(enable_timing=True)\n self.end_event = torch.cuda.Event(enable_timing=True)\n self.is_running = False\n\n def __call__(self):\n \"\"\"Record timing events and compute elapsed time.\n\n Returns:\n float: Elapsed time in seconds\n \"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n elapsed_ms = self.start_event.elapsed_time(self.end_event)\n self.is_running = False\n return elapsed_ms / 1000.0 # Convert ms to seconds\n else:\n self.start_event.record()\n self.is_running = True\n return 0.0\n\n def cleanup(self):\n \"\"\"Ensure timer is not running and synchronize CUDA.\"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n self.is_running = False\n\n\ndef benchmark_cuda_events_pedantic(\n benchmark, benchmark_fn, inputs, rounds, warmup_rounds\n):\n \"\"\"Wrapper for benchmark_cuda_events that uses pytest's pedantic method with CUDA events.\n\n Args:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Function to benchmark\n inputs: List of inputs to pass to benchmark_fn\n rounds: Number of rounds to run\n warmup_rounds: Number of warmup rounds\n \"\"\"\n\n def setup():\n clear_l2_cache()\n return inputs, {}\n\n def wrapped_fn(*args):\n benchmark_fn(*args[0])\n return None\n\n # Set our custom CUDA event timer\n benchmark._timer = CUDAEventTimer()\n\n benchmark.pedantic(\n wrapped_fn,\n setup=setup,\n rounds=rounds,\n warmup_rounds=warmup_rounds,\n iterations=1,\n )\n\n\nclass MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n\n def __init__(self):\n self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor(\n self, t: torch.Tensor, dim: int, mesh: nvfuser.multidevice.DeviceMesh\n ) -> torch.Tensor:\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim, self.rank).cuda(self.rank)\n\n\n@pytest.fixture\ndef multidevice_settings():\n return MultideviceSettings()\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.ucc, CommunicatorBackend.nccl]\n)\n@pytest.mark.parametrize(\"s\", [1, 8])\n@pytest.mark.parametrize(\"m\", [2**16])\n@pytest.mark.parametrize(\"k\", [2**12, 2**16])\n@pytest.mark.parametrize(\"n\", [2**10])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.float32])\ndef test_overlap_allgather_matmul_stream_outermost(\n benchmark,\n multidevice_settings,\n backend_type,\n s,\n m,\n k,\n n,\n dtype,\n validate_output=False,\n):\n \"\"\"Test overlapping all-gather with matrix multiplication using stream parallelism.\n\n Args:\n benchmark: pytest-benchmark fixture\n multidevice_settings: Settings for multi-device execution\n backend_type: Communication backend to use\n s: Number of streams\n m: Matrix dimension m\n k: Matrix dimension k\n n: Matrix dimension n\n dtype: Data type for computation\n validate_output: Whether to validate output against reference\n \"\"\"\n\n def fusion_definition(fd, m, k, n, s, d) -> None:\n \"\"\"Fusion definition for overlapping all-gather with matrix multiplication.\n\n This fusion implements a matrix multiplication operation with overlapping\n all-gather communication, using stream parallelism for the outermost dimension.\n \"\"\"\n x = fd.define_tensor(\n shape=[s, d, m // (s * d), k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n weight = fd.define_tensor(\n shape=[n, k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n bias = fd.define_tensor(\n shape=[n], contiguity=True, dtype=torch_dtype_to_nvfuser_dtype(dtype)\n )\n out = fd.ops.linear(x, weight, bias)\n fd.add_output(out)\n return x, weight, bias, out\n\n def multidevice_schedule(fd, tensors, num_devices):\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n for tv in tensors:\n tv.set_device_mesh(mesh)\n\n x, weight, bias, out = tensors\n x.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n out.axis(0).parallelize(nvfuser.ParallelType.stream)\n\n d = multidevice_settings.size\n assert m % (s * d) == 0\n os.environ[\"UCC_CL_BASIC_TLS\"] = \"nccl\"\n torch.cuda.set_device(multidevice_settings.local_rank)\n\n # Create input tensors\n x_unsharded = torch.testing.make_tensor(\n s, d, m // (s * d), k, dtype=dtype, device=\"cpu\"\n )\n x = multidevice_settings.shard_tensor(\n x_unsharded, 1, nvfuser.multidevice.DeviceMesh(range(multidevice_settings.size))\n )\n weight = torch.testing.make_tensor(n, k, dtype=dtype, device=\"cuda\")\n bias = torch.testing.make_tensor(n, dtype=dtype, device=\"cuda\")\n inputs = [x, weight, bias]\n\n # Create fusion definition\n with FusionDefinition() as fd:\n tensors = fusion_definition(fd, m, k, n, s, d)\n multidevice_schedule(fd, tensors, d)\n\n params = nvfuser.multidevice.MultiDeviceExecutorParams()\n params.backend_type = backend_type\n params.use_allocation_cache = True\n multidevice_executor = nvfuser.multidevice.MultiDeviceExecutor(fd.fusion, params)\n\n if validate_output:\n outputs = multidevice_executor.run(inputs)\n out = outputs[0].cpu()\n assert out.dtype == dtype\n assert out.shape == torch.Size([s, d, m // (s * d), n])\n out_ref = torch.nn.functional.linear(x_unsharded, weight.cpu(), bias.cpu())\n torch.testing.assert_close(out, out_ref, rtol=float(\"inf\"), atol=1e-1)\n\n def benchmark_fn(*args):\n outputs = multidevice_executor.run(inputs)\n return outputs[0]\n\n benchmark_cuda_events_pedantic(\n benchmark,\n benchmark_fn,\n [inputs],\n warmup_rounds=BENCHMARK_CONFIG[\"warmup_rounds\"],\n rounds=BENCHMARK_CONFIG[\"rounds\"],\n )","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.CUDAEventTimer","uri":"program://Fuser/class/benchmarks.python.benchmark_overlap.CUDAEventTimer#L19-L53","kind":"class","name":"CUDAEventTimer","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":19,"end_line":53,"context_start_line":1,"context_end_line":73,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\nimport pytest\nimport torch\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition, CommunicatorBackend\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import BENCHMARK_CONFIG, clear_l2_cache\n\n# Run command:\n# export NVFUSER_BUILD_WITH_UCC=1\n# pip install --no-build-isolation -e python -v\n# mpirun -np 1 pytest benchmarks/python/benchmark_overlap.py --with-mpi\n\n\nclass CUDAEventTimer:\n \"\"\"Custom CUDA event-based timer for accurate GPU timing.\n\n This timer uses CUDA events to measure elapsed time between operations,\n providing more accurate GPU timing than CPU-based timing methods.\n \"\"\"\n\n def __init__(self):\n self.start_event = torch.cuda.Event(enable_timing=True)\n self.end_event = torch.cuda.Event(enable_timing=True)\n self.is_running = False\n\n def __call__(self):\n \"\"\"Record timing events and compute elapsed time.\n\n Returns:\n float: Elapsed time in seconds\n \"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n elapsed_ms = self.start_event.elapsed_time(self.end_event)\n self.is_running = False\n return elapsed_ms / 1000.0 # Convert ms to seconds\n else:\n self.start_event.record()\n self.is_running = True\n return 0.0\n\n def cleanup(self):\n \"\"\"Ensure timer is not running and synchronize CUDA.\"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n self.is_running = False\n\n\ndef benchmark_cuda_events_pedantic(\n benchmark, benchmark_fn, inputs, rounds, warmup_rounds\n):\n \"\"\"Wrapper for benchmark_cuda_events that uses pytest's pedantic method with CUDA events.\n\n Args:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Function to benchmark\n inputs: List of inputs to pass to benchmark_fn\n rounds: Number of rounds to run\n warmup_rounds: Number of warmup rounds\n \"\"\"\n\n def setup():\n clear_l2_cache()\n return inputs, {}\n\n def wrapped_fn(*args):","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.benchmark_cuda_events_pedantic","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.benchmark_cuda_events_pedantic#L56-L86","kind":"function","name":"benchmark_cuda_events_pedantic","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":56,"end_line":86,"context_start_line":36,"context_end_line":106,"code":" \"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n elapsed_ms = self.start_event.elapsed_time(self.end_event)\n self.is_running = False\n return elapsed_ms / 1000.0 # Convert ms to seconds\n else:\n self.start_event.record()\n self.is_running = True\n return 0.0\n\n def cleanup(self):\n \"\"\"Ensure timer is not running and synchronize CUDA.\"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n self.is_running = False\n\n\ndef benchmark_cuda_events_pedantic(\n benchmark, benchmark_fn, inputs, rounds, warmup_rounds\n):\n \"\"\"Wrapper for benchmark_cuda_events that uses pytest's pedantic method with CUDA events.\n\n Args:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Function to benchmark\n inputs: List of inputs to pass to benchmark_fn\n rounds: Number of rounds to run\n warmup_rounds: Number of warmup rounds\n \"\"\"\n\n def setup():\n clear_l2_cache()\n return inputs, {}\n\n def wrapped_fn(*args):\n benchmark_fn(*args[0])\n return None\n\n # Set our custom CUDA event timer\n benchmark._timer = CUDAEventTimer()\n\n benchmark.pedantic(\n wrapped_fn,\n setup=setup,\n rounds=rounds,\n warmup_rounds=warmup_rounds,\n iterations=1,\n )\n\n\nclass MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n\n def __init__(self):\n self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.MultideviceSettings","uri":"program://Fuser/class/benchmarks.python.benchmark_overlap.MultideviceSettings#L89-L124","kind":"class","name":"MultideviceSettings","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":89,"end_line":124,"context_start_line":69,"context_end_line":144,"code":" def setup():\n clear_l2_cache()\n return inputs, {}\n\n def wrapped_fn(*args):\n benchmark_fn(*args[0])\n return None\n\n # Set our custom CUDA event timer\n benchmark._timer = CUDAEventTimer()\n\n benchmark.pedantic(\n wrapped_fn,\n setup=setup,\n rounds=rounds,\n warmup_rounds=warmup_rounds,\n iterations=1,\n )\n\n\nclass MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n\n def __init__(self):\n self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor(\n self, t: torch.Tensor, dim: int, mesh: nvfuser.multidevice.DeviceMesh\n ) -> torch.Tensor:\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim, self.rank).cuda(self.rank)\n\n\n@pytest.fixture\ndef multidevice_settings():\n return MultideviceSettings()\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.ucc, CommunicatorBackend.nccl]\n)\n@pytest.mark.parametrize(\"s\", [1, 8])\n@pytest.mark.parametrize(\"m\", [2**16])\n@pytest.mark.parametrize(\"k\", [2**12, 2**16])\n@pytest.mark.parametrize(\"n\", [2**10])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.float32])\ndef test_overlap_allgather_matmul_stream_outermost(\n benchmark,\n multidevice_settings,\n backend_type,","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.multidevice_settings","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.multidevice_settings#L128-L129","kind":"function","name":"multidevice_settings","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":128,"end_line":129,"context_start_line":108,"context_end_line":149,"code":" @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor(\n self, t: torch.Tensor, dim: int, mesh: nvfuser.multidevice.DeviceMesh\n ) -> torch.Tensor:\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim, self.rank).cuda(self.rank)\n\n\n@pytest.fixture\ndef multidevice_settings():\n return MultideviceSettings()\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.ucc, CommunicatorBackend.nccl]\n)\n@pytest.mark.parametrize(\"s\", [1, 8])\n@pytest.mark.parametrize(\"m\", [2**16])\n@pytest.mark.parametrize(\"k\", [2**12, 2**16])\n@pytest.mark.parametrize(\"n\", [2**10])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.float32])\ndef test_overlap_allgather_matmul_stream_outermost(\n benchmark,\n multidevice_settings,\n backend_type,\n s,\n m,\n k,\n n,\n dtype,","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.test_overlap_allgather_matmul_stream_outermost","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.test_overlap_allgather_matmul_stream_outermost#L141-L242","kind":"function","name":"test_overlap_allgather_matmul_stream_outermost","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":141,"end_line":242,"context_start_line":121,"context_end_line":242,"code":" \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim, self.rank).cuda(self.rank)\n\n\n@pytest.fixture\ndef multidevice_settings():\n return MultideviceSettings()\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.ucc, CommunicatorBackend.nccl]\n)\n@pytest.mark.parametrize(\"s\", [1, 8])\n@pytest.mark.parametrize(\"m\", [2**16])\n@pytest.mark.parametrize(\"k\", [2**12, 2**16])\n@pytest.mark.parametrize(\"n\", [2**10])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.float32])\ndef test_overlap_allgather_matmul_stream_outermost(\n benchmark,\n multidevice_settings,\n backend_type,\n s,\n m,\n k,\n n,\n dtype,\n validate_output=False,\n):\n \"\"\"Test overlapping all-gather with matrix multiplication using stream parallelism.\n\n Args:\n benchmark: pytest-benchmark fixture\n multidevice_settings: Settings for multi-device execution\n backend_type: Communication backend to use\n s: Number of streams\n m: Matrix dimension m\n k: Matrix dimension k\n n: Matrix dimension n\n dtype: Data type for computation\n validate_output: Whether to validate output against reference\n \"\"\"\n\n def fusion_definition(fd, m, k, n, s, d) -> None:\n \"\"\"Fusion definition for overlapping all-gather with matrix multiplication.\n\n This fusion implements a matrix multiplication operation with overlapping\n all-gather communication, using stream parallelism for the outermost dimension.\n \"\"\"\n x = fd.define_tensor(\n shape=[s, d, m // (s * d), k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n weight = fd.define_tensor(\n shape=[n, k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n bias = fd.define_tensor(\n shape=[n], contiguity=True, dtype=torch_dtype_to_nvfuser_dtype(dtype)\n )\n out = fd.ops.linear(x, weight, bias)\n fd.add_output(out)\n return x, weight, bias, out\n\n def multidevice_schedule(fd, tensors, num_devices):\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n for tv in tensors:\n tv.set_device_mesh(mesh)\n\n x, weight, bias, out = tensors\n x.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n out.axis(0).parallelize(nvfuser.ParallelType.stream)\n\n d = multidevice_settings.size\n assert m % (s * d) == 0\n os.environ[\"UCC_CL_BASIC_TLS\"] = \"nccl\"\n torch.cuda.set_device(multidevice_settings.local_rank)\n\n # Create input tensors\n x_unsharded = torch.testing.make_tensor(\n s, d, m // (s * d), k, dtype=dtype, device=\"cpu\"\n )\n x = multidevice_settings.shard_tensor(\n x_unsharded, 1, nvfuser.multidevice.DeviceMesh(range(multidevice_settings.size))\n )\n weight = torch.testing.make_tensor(n, k, dtype=dtype, device=\"cuda\")\n bias = torch.testing.make_tensor(n, dtype=dtype, device=\"cuda\")\n inputs = [x, weight, bias]\n\n # Create fusion definition\n with FusionDefinition() as fd:\n tensors = fusion_definition(fd, m, k, n, s, d)\n multidevice_schedule(fd, tensors, d)\n\n params = nvfuser.multidevice.MultiDeviceExecutorParams()\n params.backend_type = backend_type\n params.use_allocation_cache = True\n multidevice_executor = nvfuser.multidevice.MultiDeviceExecutor(fd.fusion, params)\n\n if validate_output:\n outputs = multidevice_executor.run(inputs)\n out = outputs[0].cpu()\n assert out.dtype == dtype\n assert out.shape == torch.Size([s, d, m // (s * d), n])\n out_ref = torch.nn.functional.linear(x_unsharded, weight.cpu(), bias.cpu())\n torch.testing.assert_close(out, out_ref, rtol=float(\"inf\"), atol=1e-1)\n\n def benchmark_fn(*args):\n outputs = multidevice_executor.run(inputs)\n return outputs[0]\n\n benchmark_cuda_events_pedantic(\n benchmark,\n benchmark_fn,\n [inputs],\n warmup_rounds=BENCHMARK_CONFIG[\"warmup_rounds\"],\n rounds=BENCHMARK_CONFIG[\"rounds\"],\n )","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.__init__","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.__init__#L92-L94","kind":"function","name":"__init__","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":92,"end_line":94,"context_start_line":72,"context_end_line":114,"code":"\n def wrapped_fn(*args):\n benchmark_fn(*args[0])\n return None\n\n # Set our custom CUDA event timer\n benchmark._timer = CUDAEventTimer()\n\n benchmark.pedantic(\n wrapped_fn,\n setup=setup,\n rounds=rounds,\n warmup_rounds=warmup_rounds,\n iterations=1,\n )\n\n\nclass MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n\n def __init__(self):\n self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.__call__","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.__call__#L31-L46","kind":"function","name":"__call__","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":31,"end_line":46,"context_start_line":11,"context_end_line":66,"code":"from .core import BENCHMARK_CONFIG, clear_l2_cache\n\n# Run command:\n# export NVFUSER_BUILD_WITH_UCC=1\n# pip install --no-build-isolation -e python -v\n# mpirun -np 1 pytest benchmarks/python/benchmark_overlap.py --with-mpi\n\n\nclass CUDAEventTimer:\n \"\"\"Custom CUDA event-based timer for accurate GPU timing.\n\n This timer uses CUDA events to measure elapsed time between operations,\n providing more accurate GPU timing than CPU-based timing methods.\n \"\"\"\n\n def __init__(self):\n self.start_event = torch.cuda.Event(enable_timing=True)\n self.end_event = torch.cuda.Event(enable_timing=True)\n self.is_running = False\n\n def __call__(self):\n \"\"\"Record timing events and compute elapsed time.\n\n Returns:\n float: Elapsed time in seconds\n \"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n elapsed_ms = self.start_event.elapsed_time(self.end_event)\n self.is_running = False\n return elapsed_ms / 1000.0 # Convert ms to seconds\n else:\n self.start_event.record()\n self.is_running = True\n return 0.0\n\n def cleanup(self):\n \"\"\"Ensure timer is not running and synchronize CUDA.\"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n self.is_running = False\n\n\ndef benchmark_cuda_events_pedantic(\n benchmark, benchmark_fn, inputs, rounds, warmup_rounds\n):\n \"\"\"Wrapper for benchmark_cuda_events that uses pytest's pedantic method with CUDA events.\n\n Args:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Function to benchmark\n inputs: List of inputs to pass to benchmark_fn\n rounds: Number of rounds to run\n warmup_rounds: Number of warmup rounds","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.cleanup","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.cleanup#L48-L53","kind":"function","name":"cleanup","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":48,"end_line":53,"context_start_line":28,"context_end_line":73,"code":" self.end_event = torch.cuda.Event(enable_timing=True)\n self.is_running = False\n\n def __call__(self):\n \"\"\"Record timing events and compute elapsed time.\n\n Returns:\n float: Elapsed time in seconds\n \"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n elapsed_ms = self.start_event.elapsed_time(self.end_event)\n self.is_running = False\n return elapsed_ms / 1000.0 # Convert ms to seconds\n else:\n self.start_event.record()\n self.is_running = True\n return 0.0\n\n def cleanup(self):\n \"\"\"Ensure timer is not running and synchronize CUDA.\"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n self.is_running = False\n\n\ndef benchmark_cuda_events_pedantic(\n benchmark, benchmark_fn, inputs, rounds, warmup_rounds\n):\n \"\"\"Wrapper for benchmark_cuda_events that uses pytest's pedantic method with CUDA events.\n\n Args:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Function to benchmark\n inputs: List of inputs to pass to benchmark_fn\n rounds: Number of rounds to run\n warmup_rounds: Number of warmup rounds\n \"\"\"\n\n def setup():\n clear_l2_cache()\n return inputs, {}\n\n def wrapped_fn(*args):","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.setup","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.setup#L69-L71","kind":"function","name":"setup","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":69,"end_line":71,"context_start_line":49,"context_end_line":91,"code":" \"\"\"Ensure timer is not running and synchronize CUDA.\"\"\"\n if self.is_running:\n self.end_event.record()\n torch.cuda.synchronize()\n self.is_running = False\n\n\ndef benchmark_cuda_events_pedantic(\n benchmark, benchmark_fn, inputs, rounds, warmup_rounds\n):\n \"\"\"Wrapper for benchmark_cuda_events that uses pytest's pedantic method with CUDA events.\n\n Args:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Function to benchmark\n inputs: List of inputs to pass to benchmark_fn\n rounds: Number of rounds to run\n warmup_rounds: Number of warmup rounds\n \"\"\"\n\n def setup():\n clear_l2_cache()\n return inputs, {}\n\n def wrapped_fn(*args):\n benchmark_fn(*args[0])\n return None\n\n # Set our custom CUDA event timer\n benchmark._timer = CUDAEventTimer()\n\n benchmark.pedantic(\n wrapped_fn,\n setup=setup,\n rounds=rounds,\n warmup_rounds=warmup_rounds,\n iterations=1,\n )\n\n\nclass MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.wrapped_fn","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.wrapped_fn#L73-L75","kind":"function","name":"wrapped_fn","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":73,"end_line":75,"context_start_line":53,"context_end_line":95,"code":" self.is_running = False\n\n\ndef benchmark_cuda_events_pedantic(\n benchmark, benchmark_fn, inputs, rounds, warmup_rounds\n):\n \"\"\"Wrapper for benchmark_cuda_events that uses pytest's pedantic method with CUDA events.\n\n Args:\n benchmark: pytest-benchmark fixture\n benchmark_fn: Function to benchmark\n inputs: List of inputs to pass to benchmark_fn\n rounds: Number of rounds to run\n warmup_rounds: Number of warmup rounds\n \"\"\"\n\n def setup():\n clear_l2_cache()\n return inputs, {}\n\n def wrapped_fn(*args):\n benchmark_fn(*args[0])\n return None\n\n # Set our custom CUDA event timer\n benchmark._timer = CUDAEventTimer()\n\n benchmark.pedantic(\n wrapped_fn,\n setup=setup,\n rounds=rounds,\n warmup_rounds=warmup_rounds,\n iterations=1,\n )\n\n\nclass MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n\n def __init__(self):\n self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.communicator","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.communicator#L97-L98","kind":"function","name":"communicator","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":97,"end_line":98,"context_start_line":77,"context_end_line":118,"code":" # Set our custom CUDA event timer\n benchmark._timer = CUDAEventTimer()\n\n benchmark.pedantic(\n wrapped_fn,\n setup=setup,\n rounds=rounds,\n warmup_rounds=warmup_rounds,\n iterations=1,\n )\n\n\nclass MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n\n def __init__(self):\n self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor(\n self, t: torch.Tensor, dim: int, mesh: nvfuser.multidevice.DeviceMesh\n ) -> torch.Tensor:","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.size","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.size#L101-L102","kind":"function","name":"size","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":101,"end_line":102,"context_start_line":81,"context_end_line":122,"code":" wrapped_fn,\n setup=setup,\n rounds=rounds,\n warmup_rounds=warmup_rounds,\n iterations=1,\n )\n\n\nclass MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n\n def __init__(self):\n self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor(\n self, t: torch.Tensor, dim: int, mesh: nvfuser.multidevice.DeviceMesh\n ) -> torch.Tensor:\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.rank","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.rank#L105-L106","kind":"function","name":"rank","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":105,"end_line":106,"context_start_line":85,"context_end_line":126,"code":" iterations=1,\n )\n\n\nclass MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n\n def __init__(self):\n self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor(\n self, t: torch.Tensor, dim: int, mesh: nvfuser.multidevice.DeviceMesh\n ) -> torch.Tensor:\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim, self.rank).cuda(self.rank)\n\n","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.local_size","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.local_size#L109-L110","kind":"function","name":"local_size","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":109,"end_line":110,"context_start_line":89,"context_end_line":130,"code":"class MultideviceSettings:\n \"\"\"Settings and utilities for multi-device execution.\"\"\"\n\n def __init__(self):\n self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor(\n self, t: torch.Tensor, dim: int, mesh: nvfuser.multidevice.DeviceMesh\n ) -> torch.Tensor:\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim, self.rank).cuda(self.rank)\n\n\n@pytest.fixture\ndef multidevice_settings():\n return MultideviceSettings()\n","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.local_rank","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.local_rank#L113-L114","kind":"function","name":"local_rank","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":113,"end_line":114,"context_start_line":93,"context_end_line":134,"code":" self._communicator = nvfuser.multidevice.Communicator.instance()\n torch.manual_seed(0)\n\n @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor(\n self, t: torch.Tensor, dim: int, mesh: nvfuser.multidevice.DeviceMesh\n ) -> torch.Tensor:\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim, self.rank).cuda(self.rank)\n\n\n@pytest.fixture\ndef multidevice_settings():\n return MultideviceSettings()\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.ucc, CommunicatorBackend.nccl]","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.shard_tensor","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.shard_tensor#L116-L124","kind":"function","name":"shard_tensor","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":116,"end_line":124,"context_start_line":96,"context_end_line":144,"code":" @property\n def communicator(self):\n return self._communicator\n\n @property\n def size(self):\n return self._communicator.size()\n\n @property\n def rank(self):\n return self._communicator.rank()\n\n @property\n def local_size(self):\n return self._communicator.local_size()\n\n @property\n def local_rank(self):\n return self._communicator.local_rank()\n\n def shard_tensor(\n self, t: torch.Tensor, dim: int, mesh: nvfuser.multidevice.DeviceMesh\n ) -> torch.Tensor:\n assert t.is_cpu, (\n \"This is not strictly required but it's a general good practice \"\n \"for unit tests to create unsharded data on CPU to reduce GPU \"\n \"memory footprint.\"\n )\n return mesh.shard_tensor(t, dim, self.rank).cuda(self.rank)\n\n\n@pytest.fixture\ndef multidevice_settings():\n return MultideviceSettings()\n\n\n@pytest.mark.mpi\n@pytest.mark.parametrize(\n \"backend_type\", [CommunicatorBackend.ucc, CommunicatorBackend.nccl]\n)\n@pytest.mark.parametrize(\"s\", [1, 8])\n@pytest.mark.parametrize(\"m\", [2**16])\n@pytest.mark.parametrize(\"k\", [2**12, 2**16])\n@pytest.mark.parametrize(\"n\", [2**10])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.float32])\ndef test_overlap_allgather_matmul_stream_outermost(\n benchmark,\n multidevice_settings,\n backend_type,","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.fusion_definition","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.fusion_definition#L166-L187","kind":"function","name":"fusion_definition","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":166,"end_line":187,"context_start_line":146,"context_end_line":207,"code":" m,\n k,\n n,\n dtype,\n validate_output=False,\n):\n \"\"\"Test overlapping all-gather with matrix multiplication using stream parallelism.\n\n Args:\n benchmark: pytest-benchmark fixture\n multidevice_settings: Settings for multi-device execution\n backend_type: Communication backend to use\n s: Number of streams\n m: Matrix dimension m\n k: Matrix dimension k\n n: Matrix dimension n\n dtype: Data type for computation\n validate_output: Whether to validate output against reference\n \"\"\"\n\n def fusion_definition(fd, m, k, n, s, d) -> None:\n \"\"\"Fusion definition for overlapping all-gather with matrix multiplication.\n\n This fusion implements a matrix multiplication operation with overlapping\n all-gather communication, using stream parallelism for the outermost dimension.\n \"\"\"\n x = fd.define_tensor(\n shape=[s, d, m // (s * d), k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n weight = fd.define_tensor(\n shape=[n, k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n bias = fd.define_tensor(\n shape=[n], contiguity=True, dtype=torch_dtype_to_nvfuser_dtype(dtype)\n )\n out = fd.ops.linear(x, weight, bias)\n fd.add_output(out)\n return x, weight, bias, out\n\n def multidevice_schedule(fd, tensors, num_devices):\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n for tv in tensors:\n tv.set_device_mesh(mesh)\n\n x, weight, bias, out = tensors\n x.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n out.axis(0).parallelize(nvfuser.ParallelType.stream)\n\n d = multidevice_settings.size\n assert m % (s * d) == 0\n os.environ[\"UCC_CL_BASIC_TLS\"] = \"nccl\"\n torch.cuda.set_device(multidevice_settings.local_rank)\n\n # Create input tensors\n x_unsharded = torch.testing.make_tensor(\n s, d, m // (s * d), k, dtype=dtype, device=\"cpu\"\n )\n x = multidevice_settings.shard_tensor(","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.multidevice_schedule","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.multidevice_schedule#L189-L196","kind":"function","name":"multidevice_schedule","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":189,"end_line":196,"context_start_line":169,"context_end_line":216,"code":" This fusion implements a matrix multiplication operation with overlapping\n all-gather communication, using stream parallelism for the outermost dimension.\n \"\"\"\n x = fd.define_tensor(\n shape=[s, d, m // (s * d), k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n weight = fd.define_tensor(\n shape=[n, k],\n contiguity=True,\n dtype=torch_dtype_to_nvfuser_dtype(dtype),\n )\n bias = fd.define_tensor(\n shape=[n], contiguity=True, dtype=torch_dtype_to_nvfuser_dtype(dtype)\n )\n out = fd.ops.linear(x, weight, bias)\n fd.add_output(out)\n return x, weight, bias, out\n\n def multidevice_schedule(fd, tensors, num_devices):\n mesh = nvfuser.multidevice.DeviceMesh(range(num_devices))\n for tv in tensors:\n tv.set_device_mesh(mesh)\n\n x, weight, bias, out = tensors\n x.axis(1).parallelize(nvfuser.ParallelType.mesh_x)\n out.axis(0).parallelize(nvfuser.ParallelType.stream)\n\n d = multidevice_settings.size\n assert m % (s * d) == 0\n os.environ[\"UCC_CL_BASIC_TLS\"] = \"nccl\"\n torch.cuda.set_device(multidevice_settings.local_rank)\n\n # Create input tensors\n x_unsharded = torch.testing.make_tensor(\n s, d, m // (s * d), k, dtype=dtype, device=\"cpu\"\n )\n x = multidevice_settings.shard_tensor(\n x_unsharded, 1, nvfuser.multidevice.DeviceMesh(range(multidevice_settings.size))\n )\n weight = torch.testing.make_tensor(n, k, dtype=dtype, device=\"cuda\")\n bias = torch.testing.make_tensor(n, dtype=dtype, device=\"cuda\")\n inputs = [x, weight, bias]\n\n # Create fusion definition\n with FusionDefinition() as fd:\n tensors = fusion_definition(fd, m, k, n, s, d)","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.benchmark_overlap.benchmark_fn","uri":"program://Fuser/function/benchmarks.python.benchmark_overlap.benchmark_fn#L232-L234","kind":"function","name":"benchmark_fn","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":232,"end_line":234,"context_start_line":212,"context_end_line":242,"code":" inputs = [x, weight, bias]\n\n # Create fusion definition\n with FusionDefinition() as fd:\n tensors = fusion_definition(fd, m, k, n, s, d)\n multidevice_schedule(fd, tensors, d)\n\n params = nvfuser.multidevice.MultiDeviceExecutorParams()\n params.backend_type = backend_type\n params.use_allocation_cache = True\n multidevice_executor = nvfuser.multidevice.MultiDeviceExecutor(fd.fusion, params)\n\n if validate_output:\n outputs = multidevice_executor.run(inputs)\n out = outputs[0].cpu()\n assert out.dtype == dtype\n assert out.shape == torch.Size([s, d, m // (s * d), n])\n out_ref = torch.nn.functional.linear(x_unsharded, weight.cpu(), bias.cpu())\n torch.testing.assert_close(out, out_ref, rtol=float(\"inf\"), atol=1e-1)\n\n def benchmark_fn(*args):\n outputs = multidevice_executor.run(inputs)\n return outputs[0]\n\n benchmark_cuda_events_pedantic(\n benchmark,\n benchmark_fn,\n [inputs],\n warmup_rounds=BENCHMARK_CONFIG[\"warmup_rounds\"],\n rounds=BENCHMARK_CONFIG[\"rounds\"],\n )","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd","uri":"program://Fuser/module/benchmarks.python.test_gelu_bwd#L1-L123","kind":"module","name":"benchmarks.python.test_gelu_bwd","path":"benchmarks/python/test_gelu_bwd.py","language":"python","start_line":1,"end_line":123,"context_start_line":1,"context_end_line":123,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import gelu\n\n\ndef gelu_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n input = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n grad = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n grad = fd.ops.cast(grad, dtype=DataType.Float)\n bias = fd.ops.cast(bias, dtype=DataType.Float)\n S_079 = fd.define_scalar(0.79788456)\n S_004 = fd.define_scalar(0.044715)\n S_010 = fd.define_scalar(0.1070322243)\n bias = fd.ops.broadcast_in_dim(bias, shape=[1, input.size(-1)], broadcast_dims=[1])\n T1 = fd.ops.add(input, bias)\n T2 = fd.ops.mul(T1, S_079)\n T3 = fd.ops.mul(T1, S_004)\n T4 = fd.ops.mul(T3, T1)\n S1 = fd.define_scalar(1.0)\n T5 = fd.ops.add(S1, T4)\n T6 = fd.ops.mul(T2, T5)\n T7 = fd.ops.tanh(T6)\n S2 = fd.define_scalar(0.50)\n T8 = fd.ops.mul(T1, S2)\n T9 = fd.ops.mul(T7, T7)\n T10 = fd.ops.neg(T9)\n T11 = fd.ops.add(T10, S1)\n T12 = fd.ops.mul(T1, S_010)\n T13 = fd.ops.mul(T12, T1)\n T14 = fd.ops.add(T13, S_079)\n T15 = fd.ops.mul(T11, T14)\n T16 = fd.ops.mul(T8, T15)\n T17 = fd.ops.add(T7, S1)\n T18 = fd.ops.mul(T17, S2)\n T19 = fd.ops.add(T16, T18)\n T20 = fd.ops.mul(grad, T19)\n if dtype in PROMOTE_DTYPES:\n T20 = fd.ops.cast(T20, dtype=dtype)\n fd.add_output(T20)\n\n\ndef gelu_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = in_tensor + grad_out + bias + grad_input\n return int(dtype.itemsize * (3 * np.prod(size) + size[1]))\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n gelu_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.nn.functional.gelu(\n inputs.to(torch.double) + bias.to(torch.double), approximate=\"tanh\"\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate([inputs, grads, bias], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, grads, bias])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n fwd_fn = with_executor(executor, gelu)\n fwd_inputs = [inputs, bias]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=gelu_bwd_iobytes(size, dtype),\n )","source_hash":"9aa1462b3c712f8a9e9d5a8362b374eb4e4ccaa3b8061f1b8869c727146cabea","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd.gelu_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_gelu_bwd.gelu_bwd_fusion#L20-L63","kind":"function","name":"gelu_bwd_fusion","path":"benchmarks/python/test_gelu_bwd.py","language":"python","start_line":20,"end_line":63,"context_start_line":1,"context_end_line":83,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import gelu\n\n\ndef gelu_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n input = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n grad = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n grad = fd.ops.cast(grad, dtype=DataType.Float)\n bias = fd.ops.cast(bias, dtype=DataType.Float)\n S_079 = fd.define_scalar(0.79788456)\n S_004 = fd.define_scalar(0.044715)\n S_010 = fd.define_scalar(0.1070322243)\n bias = fd.ops.broadcast_in_dim(bias, shape=[1, input.size(-1)], broadcast_dims=[1])\n T1 = fd.ops.add(input, bias)\n T2 = fd.ops.mul(T1, S_079)\n T3 = fd.ops.mul(T1, S_004)\n T4 = fd.ops.mul(T3, T1)\n S1 = fd.define_scalar(1.0)\n T5 = fd.ops.add(S1, T4)\n T6 = fd.ops.mul(T2, T5)\n T7 = fd.ops.tanh(T6)\n S2 = fd.define_scalar(0.50)\n T8 = fd.ops.mul(T1, S2)\n T9 = fd.ops.mul(T7, T7)\n T10 = fd.ops.neg(T9)\n T11 = fd.ops.add(T10, S1)\n T12 = fd.ops.mul(T1, S_010)\n T13 = fd.ops.mul(T12, T1)\n T14 = fd.ops.add(T13, S_079)\n T15 = fd.ops.mul(T11, T14)\n T16 = fd.ops.mul(T8, T15)\n T17 = fd.ops.add(T7, S1)\n T18 = fd.ops.mul(T17, S2)\n T19 = fd.ops.add(T16, T18)\n T20 = fd.ops.mul(grad, T19)\n if dtype in PROMOTE_DTYPES:\n T20 = fd.ops.cast(T20, dtype=dtype)\n fd.add_output(T20)\n\n\ndef gelu_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = in_tensor + grad_out + bias + grad_input\n return int(dtype.itemsize * (3 * np.prod(size) + size[1]))\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)","source_hash":"9aa1462b3c712f8a9e9d5a8362b374eb4e4ccaa3b8061f1b8869c727146cabea","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd.gelu_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_gelu_bwd.gelu_bwd_iobytes#L66-L68","kind":"function","name":"gelu_bwd_iobytes","path":"benchmarks/python/test_gelu_bwd.py","language":"python","start_line":66,"end_line":68,"context_start_line":46,"context_end_line":88,"code":" T7 = fd.ops.tanh(T6)\n S2 = fd.define_scalar(0.50)\n T8 = fd.ops.mul(T1, S2)\n T9 = fd.ops.mul(T7, T7)\n T10 = fd.ops.neg(T9)\n T11 = fd.ops.add(T10, S1)\n T12 = fd.ops.mul(T1, S_010)\n T13 = fd.ops.mul(T12, T1)\n T14 = fd.ops.add(T13, S_079)\n T15 = fd.ops.mul(T11, T14)\n T16 = fd.ops.mul(T8, T15)\n T17 = fd.ops.add(T7, S1)\n T18 = fd.ops.mul(T17, S2)\n T19 = fd.ops.add(T16, T18)\n T20 = fd.ops.mul(grad, T19)\n if dtype in PROMOTE_DTYPES:\n T20 = fd.ops.cast(T20, dtype=dtype)\n fd.add_output(T20)\n\n\ndef gelu_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = in_tensor + grad_out + bias + grad_input\n return int(dtype.itemsize * (3 * np.prod(size) + size[1]))\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n gelu_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.nn.functional.gelu(","source_hash":"9aa1462b3c712f8a9e9d5a8362b374eb4e4ccaa3b8061f1b8869c727146cabea","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd.test_gelu_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_gelu_bwd.test_gelu_bwd_nvf_benchmark#L74-L95","kind":"function","name":"test_gelu_bwd_nvf_benchmark","path":"benchmarks/python/test_gelu_bwd.py","language":"python","start_line":74,"end_line":95,"context_start_line":54,"context_end_line":115,"code":" T14 = fd.ops.add(T13, S_079)\n T15 = fd.ops.mul(T11, T14)\n T16 = fd.ops.mul(T8, T15)\n T17 = fd.ops.add(T7, S1)\n T18 = fd.ops.mul(T17, S2)\n T19 = fd.ops.add(T16, T18)\n T20 = fd.ops.mul(grad, T19)\n if dtype in PROMOTE_DTYPES:\n T20 = fd.ops.cast(T20, dtype=dtype)\n fd.add_output(T20)\n\n\ndef gelu_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = in_tensor + grad_out + bias + grad_input\n return int(dtype.itemsize * (3 * np.prod(size) + size[1]))\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n gelu_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.nn.functional.gelu(\n inputs.to(torch.double) + bias.to(torch.double), approximate=\"tanh\"\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate([inputs, grads, bias], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, grads, bias])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n fwd_fn = with_executor(executor, gelu)\n fwd_inputs = [inputs, bias]","source_hash":"9aa1462b3c712f8a9e9d5a8362b374eb4e4ccaa3b8061f1b8869c727146cabea","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd.test_gelu_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_gelu_bwd.test_gelu_bwd_baseline_benchmark#L102-L123","kind":"function","name":"test_gelu_bwd_baseline_benchmark","path":"benchmarks/python/test_gelu_bwd.py","language":"python","start_line":102,"end_line":123,"context_start_line":82,"context_end_line":123,"code":" grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n gelu_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.nn.functional.gelu(\n inputs.to(torch.double) + bias.to(torch.double), approximate=\"tanh\"\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate([inputs, grads, bias], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, grads, bias])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_gelu_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n\n fwd_fn = with_executor(executor, gelu)\n fwd_inputs = [inputs, bias]\n outputs = fwd_fn(fwd_inputs)\n\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=gelu_bwd_iobytes(size, dtype),\n )","source_hash":"9aa1462b3c712f8a9e9d5a8362b374eb4e4ccaa3b8061f1b8869c727146cabea","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_fwd","uri":"program://Fuser/module/benchmarks.python.test_softmax_fwd#L1-L107","kind":"module","name":"benchmarks.python.test_softmax_fwd","path":"benchmarks/python/test_softmax_fwd.py","language":"python","start_line":1,"end_line":107,"context_start_line":1,"context_end_line":107,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import softmax\n\n\ndef softmax_fwd_fusion(\n fd: FusionDefinition, dtype: DataType, reduction_axis: int\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.max(T0, dims=[reduction_axis], keepdim=False, dtype=DataType.Null)\n\n bcast_dims = [False, False]\n bcast_dims[reduction_axis] = True\n\n T7 = fd.ops.broadcast(T2, is_broadcast_dim=bcast_dims)\n T13 = fd.ops.sub(T0, T7)\n T14 = fd.ops.exp(T13)\n T15 = fd.ops.sum(T14, dims=[reduction_axis], keepdim=False, dtype=DataType.Null)\n\n T20 = fd.ops.broadcast(T15, is_broadcast_dim=bcast_dims)\n\n T26 = fd.ops.reciprocal(T20)\n T27 = fd.ops.mul(T14, T26)\n\n if dtype in PROMOTE_DTYPES:\n T27 = fd.ops.cast(T27, dtype=dtype)\n fd.add_output(T27)\n\n\ndef softmax_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = input + output\n return int(np.prod(size) * dtype.itemsize * 2)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n softmax_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis)\n\n if not disable_validation:\n eager_output = softmax([inputs[0], reduction_axis])\n fd.validate(inputs, [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n\n benchmark_fn = with_executor(executor, softmax)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, reduction_axis],\n iobytes=softmax_fwd_iobytes(size, dtype),\n )","source_hash":"dfc3976fff2c9bcdfe20715bc99b1799f2af2c9e0b3faf23626ba2d2dbaeca00","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_fwd.softmax_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_softmax_fwd.softmax_fwd_fusion#L14-L42","kind":"function","name":"softmax_fwd_fusion","path":"benchmarks/python/test_softmax_fwd.py","language":"python","start_line":14,"end_line":42,"context_start_line":1,"context_end_line":62,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import softmax\n\n\ndef softmax_fwd_fusion(\n fd: FusionDefinition, dtype: DataType, reduction_axis: int\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.max(T0, dims=[reduction_axis], keepdim=False, dtype=DataType.Null)\n\n bcast_dims = [False, False]\n bcast_dims[reduction_axis] = True\n\n T7 = fd.ops.broadcast(T2, is_broadcast_dim=bcast_dims)\n T13 = fd.ops.sub(T0, T7)\n T14 = fd.ops.exp(T13)\n T15 = fd.ops.sum(T14, dims=[reduction_axis], keepdim=False, dtype=DataType.Null)\n\n T20 = fd.ops.broadcast(T15, is_broadcast_dim=bcast_dims)\n\n T26 = fd.ops.reciprocal(T20)\n T27 = fd.ops.mul(T14, T26)\n\n if dtype in PROMOTE_DTYPES:\n T27 = fd.ops.cast(T27, dtype=dtype)\n fd.add_output(T27)\n\n\ndef softmax_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = input + output\n return int(np.prod(size) * dtype.itemsize * 2)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,","source_hash":"dfc3976fff2c9bcdfe20715bc99b1799f2af2c9e0b3faf23626ba2d2dbaeca00","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_fwd.softmax_fwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_softmax_fwd.softmax_fwd_iobytes#L45-L47","kind":"function","name":"softmax_fwd_iobytes","path":"benchmarks/python/test_softmax_fwd.py","language":"python","start_line":45,"end_line":47,"context_start_line":25,"context_end_line":67,"code":" T2 = fd.ops.max(T0, dims=[reduction_axis], keepdim=False, dtype=DataType.Null)\n\n bcast_dims = [False, False]\n bcast_dims[reduction_axis] = True\n\n T7 = fd.ops.broadcast(T2, is_broadcast_dim=bcast_dims)\n T13 = fd.ops.sub(T0, T7)\n T14 = fd.ops.exp(T13)\n T15 = fd.ops.sum(T14, dims=[reduction_axis], keepdim=False, dtype=DataType.Null)\n\n T20 = fd.ops.broadcast(T15, is_broadcast_dim=bcast_dims)\n\n T26 = fd.ops.reciprocal(T20)\n T27 = fd.ops.mul(T14, T26)\n\n if dtype in PROMOTE_DTYPES:\n T27 = fd.ops.cast(T27, dtype=dtype)\n fd.add_output(T27)\n\n\ndef softmax_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = input + output\n return int(np.prod(size) * dtype.itemsize * 2)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(size, device=\"cuda\", dtype=dtype)]","source_hash":"dfc3976fff2c9bcdfe20715bc99b1799f2af2c9e0b3faf23626ba2d2dbaeca00","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_fwd.test_softmax_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_softmax_fwd.test_softmax_fwd_nvf_benchmark#L59-L77","kind":"function","name":"test_softmax_fwd_nvf_benchmark","path":"benchmarks/python/test_softmax_fwd.py","language":"python","start_line":59,"end_line":77,"context_start_line":39,"context_end_line":97,"code":"\n if dtype in PROMOTE_DTYPES:\n T27 = fd.ops.cast(T27, dtype=dtype)\n fd.add_output(T27)\n\n\ndef softmax_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = input + output\n return int(np.prod(size) * dtype.itemsize * 2)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(size, device=\"cuda\", dtype=dtype)]\n\n with FusionDefinition() as fd:\n softmax_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis)\n\n if not disable_validation:\n eager_output = softmax([inputs[0], reduction_axis])\n fd.validate(inputs, [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":","source_hash":"dfc3976fff2c9bcdfe20715bc99b1799f2af2c9e0b3faf23626ba2d2dbaeca00","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_softmax_fwd.test_softmax_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_softmax_fwd.test_softmax_fwd_baseline_benchmark#L90-L107","kind":"function","name":"test_softmax_fwd_baseline_benchmark","path":"benchmarks/python/test_softmax_fwd.py","language":"python","start_line":90,"end_line":107,"context_start_line":70,"context_end_line":107,"code":" softmax_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis)\n\n if not disable_validation:\n eager_output = softmax([inputs[0], reduction_axis])\n fd.validate(inputs, [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"reduction_axis\",\n [\n pytest.param(0, marks=pytest.mark.outer_persistent),\n pytest.param(1, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_softmax_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n\n benchmark_fn = with_executor(executor, softmax)\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, reduction_axis],\n iobytes=softmax_fwd_iobytes(size, dtype),\n )","source_hash":"dfc3976fff2c9bcdfe20715bc99b1799f2af2c9e0b3faf23626ba2d2dbaeca00","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd_reduction","uri":"program://Fuser/module/benchmarks.python.test_gelu_bwd_reduction#L1-L132","kind":"module","name":"benchmarks.python.test_gelu_bwd_reduction","path":"benchmarks/python/test_gelu_bwd_reduction.py","language":"python","start_line":1,"end_line":132,"context_start_line":1,"context_end_line":132,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\n\n\ndef gelu_bwd_reduction_fusion(\n fd: FusionDefinition, dtype: DataType, reduction_axis: int\n) -> None:\n input = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n grad = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n grad = fd.ops.cast(grad, dtype=DataType.Float)\n bias = fd.ops.cast(bias, dtype=DataType.Float)\n S_079 = fd.define_scalar(0.79788456)\n S_004 = fd.define_scalar(0.044715)\n S_010 = fd.define_scalar(0.1070322243)\n bias = fd.ops.broadcast_in_dim(bias, shape=[1, input.size(-1)], broadcast_dims=[1])\n T1 = fd.ops.add(input, bias)\n T2 = fd.ops.mul(T1, S_079)\n T3 = fd.ops.mul(T1, S_004)\n T4 = fd.ops.mul(T3, T1)\n S1 = fd.define_scalar(1.0)\n T5 = fd.ops.add(S1, T4)\n T6 = fd.ops.mul(T2, T5)\n T7 = fd.ops.tanh(T6)\n S2 = fd.define_scalar(0.50)\n T8 = fd.ops.mul(T1, S2)\n T9 = fd.ops.mul(T7, T7)\n T10 = fd.ops.neg(T9)\n T11 = fd.ops.add(T10, S1)\n T12 = fd.ops.mul(T1, S_010)\n T13 = fd.ops.mul(T12, T1)\n T14 = fd.ops.add(T13, S_079)\n T15 = fd.ops.mul(T11, T14)\n T16 = fd.ops.mul(T8, T15)\n T17 = fd.ops.add(T7, S1)\n T18 = fd.ops.mul(T17, S2)\n T19 = fd.ops.add(T16, T18)\n T20 = fd.ops.mul(grad, T19)\n T21 = fd.ops.sum(T20, dims=[reduction_axis], keepdim=False)\n if dtype in PROMOTE_DTYPES:\n T21 = fd.ops.cast(T21, dtype=dtype)\n fd.add_output(T21)\n\n\ndef gelu_bwd_reduction_torch(\n inputs: list,\n): # [output, grad_out, in_tensor, reduction_axis]\n eager_output, grad_out, in_tensor, reduction_axis = inputs\n eager_output.backward(grad_out, retain_graph=True)\n return in_tensor.grad.sum(reduction_axis)\n\n\ndef gelu_bwd_reduction_iobytes(size: tuple, dtype: torch.dtype, reduction_axis: int):\n # Total IO bytes = in_tensor + grad_out + bias + grad_input\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[1] + size[1 - reduction_axis])\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_gelu_bwd_reduction_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n gelu_bwd_reduction_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis\n )\n\n if not disable_validation:\n eager_output = torch.nn.functional.gelu(\n inputs.to(torch.double) + bias.to(torch.double), approximate=\"tanh\"\n )\n eager_output.backward(grads.to(torch.double))\n reduction_out = inputs.grad.to(torch.double).sum(reduction_axis)\n fd.validate([inputs, grads, bias], [reduction_out.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, grads, bias])\n\n\n@pytest.mark.parametrize(\"executor\", [\"eager\", \"torchcompile\"])\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_gelu_bwd_reduction_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n eager_output = torch.nn.functional.gelu(inputs + bias, approximate=\"tanh\")\n\n benchmark_fn = with_executor(executor, gelu_bwd_reduction_torch)\n\n run_benchmark(\n benchmark,\n benchmark_fn,\n [eager_output, grads, inputs, reduction_axis],\n iobytes=gelu_bwd_reduction_iobytes(size, dtype, reduction_axis),\n )","source_hash":"f1327b681871f3a2db047a001da7f8d65f76828ee6cc04056da447f13a143864","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd_reduction.gelu_bwd_reduction_fusion","uri":"program://Fuser/function/benchmarks.python.test_gelu_bwd_reduction.gelu_bwd_reduction_fusion#L13-L56","kind":"function","name":"gelu_bwd_reduction_fusion","path":"benchmarks/python/test_gelu_bwd_reduction.py","language":"python","start_line":13,"end_line":56,"context_start_line":1,"context_end_line":76,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\n\n\ndef gelu_bwd_reduction_fusion(\n fd: FusionDefinition, dtype: DataType, reduction_axis: int\n) -> None:\n input = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n grad = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:\n input = fd.ops.cast(input, dtype=DataType.Float)\n grad = fd.ops.cast(grad, dtype=DataType.Float)\n bias = fd.ops.cast(bias, dtype=DataType.Float)\n S_079 = fd.define_scalar(0.79788456)\n S_004 = fd.define_scalar(0.044715)\n S_010 = fd.define_scalar(0.1070322243)\n bias = fd.ops.broadcast_in_dim(bias, shape=[1, input.size(-1)], broadcast_dims=[1])\n T1 = fd.ops.add(input, bias)\n T2 = fd.ops.mul(T1, S_079)\n T3 = fd.ops.mul(T1, S_004)\n T4 = fd.ops.mul(T3, T1)\n S1 = fd.define_scalar(1.0)\n T5 = fd.ops.add(S1, T4)\n T6 = fd.ops.mul(T2, T5)\n T7 = fd.ops.tanh(T6)\n S2 = fd.define_scalar(0.50)\n T8 = fd.ops.mul(T1, S2)\n T9 = fd.ops.mul(T7, T7)\n T10 = fd.ops.neg(T9)\n T11 = fd.ops.add(T10, S1)\n T12 = fd.ops.mul(T1, S_010)\n T13 = fd.ops.mul(T12, T1)\n T14 = fd.ops.add(T13, S_079)\n T15 = fd.ops.mul(T11, T14)\n T16 = fd.ops.mul(T8, T15)\n T17 = fd.ops.add(T7, S1)\n T18 = fd.ops.mul(T17, S2)\n T19 = fd.ops.add(T16, T18)\n T20 = fd.ops.mul(grad, T19)\n T21 = fd.ops.sum(T20, dims=[reduction_axis], keepdim=False)\n if dtype in PROMOTE_DTYPES:\n T21 = fd.ops.cast(T21, dtype=dtype)\n fd.add_output(T21)\n\n\ndef gelu_bwd_reduction_torch(\n inputs: list,\n): # [output, grad_out, in_tensor, reduction_axis]\n eager_output, grad_out, in_tensor, reduction_axis = inputs\n eager_output.backward(grad_out, retain_graph=True)\n return in_tensor.grad.sum(reduction_axis)\n\n\ndef gelu_bwd_reduction_iobytes(size: tuple, dtype: torch.dtype, reduction_axis: int):\n # Total IO bytes = in_tensor + grad_out + bias + grad_input\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[1] + size[1 - reduction_axis])\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])","source_hash":"f1327b681871f3a2db047a001da7f8d65f76828ee6cc04056da447f13a143864","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd_reduction.gelu_bwd_reduction_torch","uri":"program://Fuser/function/benchmarks.python.test_gelu_bwd_reduction.gelu_bwd_reduction_torch#L59-L64","kind":"function","name":"gelu_bwd_reduction_torch","path":"benchmarks/python/test_gelu_bwd_reduction.py","language":"python","start_line":59,"end_line":64,"context_start_line":39,"context_end_line":84,"code":" S2 = fd.define_scalar(0.50)\n T8 = fd.ops.mul(T1, S2)\n T9 = fd.ops.mul(T7, T7)\n T10 = fd.ops.neg(T9)\n T11 = fd.ops.add(T10, S1)\n T12 = fd.ops.mul(T1, S_010)\n T13 = fd.ops.mul(T12, T1)\n T14 = fd.ops.add(T13, S_079)\n T15 = fd.ops.mul(T11, T14)\n T16 = fd.ops.mul(T8, T15)\n T17 = fd.ops.add(T7, S1)\n T18 = fd.ops.mul(T17, S2)\n T19 = fd.ops.add(T16, T18)\n T20 = fd.ops.mul(grad, T19)\n T21 = fd.ops.sum(T20, dims=[reduction_axis], keepdim=False)\n if dtype in PROMOTE_DTYPES:\n T21 = fd.ops.cast(T21, dtype=dtype)\n fd.add_output(T21)\n\n\ndef gelu_bwd_reduction_torch(\n inputs: list,\n): # [output, grad_out, in_tensor, reduction_axis]\n eager_output, grad_out, in_tensor, reduction_axis = inputs\n eager_output.backward(grad_out, retain_graph=True)\n return in_tensor.grad.sum(reduction_axis)\n\n\ndef gelu_bwd_reduction_iobytes(size: tuple, dtype: torch.dtype, reduction_axis: int):\n # Total IO bytes = in_tensor + grad_out + bias + grad_input\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[1] + size[1 - reduction_axis])\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_gelu_bwd_reduction_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,","source_hash":"f1327b681871f3a2db047a001da7f8d65f76828ee6cc04056da447f13a143864","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd_reduction.gelu_bwd_reduction_iobytes","uri":"program://Fuser/function/benchmarks.python.test_gelu_bwd_reduction.gelu_bwd_reduction_iobytes#L67-L71","kind":"function","name":"gelu_bwd_reduction_iobytes","path":"benchmarks/python/test_gelu_bwd_reduction.py","language":"python","start_line":67,"end_line":71,"context_start_line":47,"context_end_line":91,"code":" T15 = fd.ops.mul(T11, T14)\n T16 = fd.ops.mul(T8, T15)\n T17 = fd.ops.add(T7, S1)\n T18 = fd.ops.mul(T17, S2)\n T19 = fd.ops.add(T16, T18)\n T20 = fd.ops.mul(grad, T19)\n T21 = fd.ops.sum(T20, dims=[reduction_axis], keepdim=False)\n if dtype in PROMOTE_DTYPES:\n T21 = fd.ops.cast(T21, dtype=dtype)\n fd.add_output(T21)\n\n\ndef gelu_bwd_reduction_torch(\n inputs: list,\n): # [output, grad_out, in_tensor, reduction_axis]\n eager_output, grad_out, in_tensor, reduction_axis = inputs\n eager_output.backward(grad_out, retain_graph=True)\n return in_tensor.grad.sum(reduction_axis)\n\n\ndef gelu_bwd_reduction_iobytes(size: tuple, dtype: torch.dtype, reduction_axis: int):\n # Total IO bytes = in_tensor + grad_out + bias + grad_input\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[1] + size[1 - reduction_axis])\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_gelu_bwd_reduction_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n gelu_bwd_reduction_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis","source_hash":"f1327b681871f3a2db047a001da7f8d65f76828ee6cc04056da447f13a143864","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd_reduction.test_gelu_bwd_reduction_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_gelu_bwd_reduction.test_gelu_bwd_reduction_nvf_benchmark#L78-L103","kind":"function","name":"test_gelu_bwd_reduction_nvf_benchmark","path":"benchmarks/python/test_gelu_bwd_reduction.py","language":"python","start_line":78,"end_line":103,"context_start_line":58,"context_end_line":123,"code":"\ndef gelu_bwd_reduction_torch(\n inputs: list,\n): # [output, grad_out, in_tensor, reduction_axis]\n eager_output, grad_out, in_tensor, reduction_axis = inputs\n eager_output.backward(grad_out, retain_graph=True)\n return in_tensor.grad.sum(reduction_axis)\n\n\ndef gelu_bwd_reduction_iobytes(size: tuple, dtype: torch.dtype, reduction_axis: int):\n # Total IO bytes = in_tensor + grad_out + bias + grad_input\n return int(\n dtype.itemsize * (2 * np.prod(size) + size[1] + size[1 - reduction_axis])\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_gelu_bwd_reduction_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n with FusionDefinition() as fd:\n gelu_bwd_reduction_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis\n )\n\n if not disable_validation:\n eager_output = torch.nn.functional.gelu(\n inputs.to(torch.double) + bias.to(torch.double), approximate=\"tanh\"\n )\n eager_output.backward(grads.to(torch.double))\n reduction_out = inputs.grad.to(torch.double).sum(reduction_axis)\n fd.validate([inputs, grads, bias], [reduction_out.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, grads, bias])\n\n\n@pytest.mark.parametrize(\"executor\", [\"eager\", \"torchcompile\"])\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_gelu_bwd_reduction_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n eager_output = torch.nn.functional.gelu(inputs + bias, approximate=\"tanh\")","source_hash":"f1327b681871f3a2db047a001da7f8d65f76828ee6cc04056da447f13a143864","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_gelu_bwd_reduction.test_gelu_bwd_reduction_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_gelu_bwd_reduction.test_gelu_bwd_reduction_baseline_benchmark#L111-L132","kind":"function","name":"test_gelu_bwd_reduction_baseline_benchmark","path":"benchmarks/python/test_gelu_bwd_reduction.py","language":"python","start_line":111,"end_line":132,"context_start_line":91,"context_end_line":132,"code":" fd, torch_dtype_to_nvfuser_dtype(dtype), reduction_axis\n )\n\n if not disable_validation:\n eager_output = torch.nn.functional.gelu(\n inputs.to(torch.double) + bias.to(torch.double), approximate=\"tanh\"\n )\n eager_output.backward(grads.to(torch.double))\n reduction_out = inputs.grad.to(torch.double).sum(reduction_axis)\n fd.validate([inputs, grads, bias], [reduction_out.to(dtype)])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, grads, bias])\n\n\n@pytest.mark.parametrize(\"executor\", [\"eager\", \"torchcompile\"])\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\"reduction_axis\", [0, 1])\n@pytest.mark.reduction\ndef test_gelu_bwd_reduction_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n reduction_axis: int,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n eager_output = torch.nn.functional.gelu(inputs + bias, approximate=\"tanh\")\n\n benchmark_fn = with_executor(executor, gelu_bwd_reduction_torch)\n\n run_benchmark(\n benchmark,\n benchmark_fn,\n [eager_output, grads, inputs, reduction_axis],\n iobytes=gelu_bwd_reduction_iobytes(size, dtype, reduction_axis),\n )","source_hash":"f1327b681871f3a2db047a001da7f8d65f76828ee6cc04056da447f13a143864","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.model_configs","uri":"program://Fuser/module/benchmarks.python.model_configs#L1-L119","kind":"module","name":"benchmarks.python.model_configs","path":"benchmarks/python/model_configs.py","language":"python","start_line":1,"end_line":119,"context_start_line":1,"context_end_line":119,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom functools import partial\n\n\ndef llama_hf_cfg(config_str):\n class Config:\n def __init__(\n self, n_head, head_size, n_query_groups, rope_n_elem, batches, seq_length\n ):\n self.n_head = n_head\n self.head_size = head_size\n self.n_query_groups = n_query_groups\n self.rope_n_elem = rope_n_elem\n self.batches = batches\n self.seq_length = seq_length\n\n configs = {}\n configs[\"llama_2_7b_hf\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=32,\n rope_n_elem=128,\n batches=2,\n seq_length=4096,\n )\n configs[\"llama_3_8B\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=8,\n rope_n_elem=128,\n batches=2,\n seq_length=8192,\n )\n\n return configs[config_str]\n\n\ndef hf_qwen2_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"Qwen/Qwen2.5-7B-Instruct\")\n config.batch_size = 1\n config.seq_len = 4096\n config._attn_implementation = \"sdpa\"\n return config\n\n\ndef hf_phi3_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"microsoft/Phi-3.5-mini-instruct\")\n config.batch_size = 1\n config.seq_len = 8192\n config._attn_implementation = \"sdpa\"\n return config\n\n\ndef hf_mistral_nemo_cfg():\n import json\n from transformers.models.mistral import MistralConfig\n\n mistral_cfg_str = r\"\"\"{\n \"_name_or_path\": \"mistralai/Mistral-Nemo-Base-2407\",\n \"architectures\": [\n \"MistralForCausalLM\"\n ],\n \"attention_dropout\": 0.0,\n \"bos_token_id\": 1,\n \"eos_token_id\": 2,\n \"head_dim\": 128,\n \"hidden_act\": \"silu\",\n \"hidden_size\": 5120,\n \"initializer_range\": 0.02,\n \"intermediate_size\": 14336,\n \"max_position_embeddings\": 128000,\n \"model_type\": \"mistral\",\n \"num_attention_heads\": 32,\n \"num_hidden_layers\": 40,\n \"num_key_value_heads\": 8,\n \"rms_norm_eps\": 1e-05,\n \"rope_theta\": 1000000.0,\n \"sliding_window\": null,\n \"tie_word_embeddings\": false,\n \"torch_dtype\": \"bfloat16\",\n \"transformers_version\": \"4.43.3\",\n \"use_cache\": true,\n \"vocab_size\": 131072\n }\n \"\"\"\n\n cfg = MistralConfig.from_dict(json.loads(mistral_cfg_str))\n cfg.batch_size = 1\n cfg.seq_len = 4096\n cfg._attn_implementation = \"sdpa\"\n\n return cfg\n\n\ndef litgpt_cfg(model_name):\n import litgpt\n\n cfg = litgpt.Config.from_name(model_name)\n cfg.batch_size = 1\n cfg.seq_len = 4096\n cfg.name_or_path = model_name\n\n return cfg\n\n\nconfigs = {\n \"llama_2_7b_hf\": partial(llama_hf_cfg, config_str=\"llama_2_7b_hf\"),\n \"llama_3_8B\": partial(llama_hf_cfg, config_str=\"llama_3_8B\"),\n \"hf_qwen2\": hf_qwen2_cfg,\n \"hf_phi3\": hf_phi3_cfg,\n \"hf_mistral_nemo\": hf_mistral_nemo_cfg,\n \"litgpt\": litgpt_cfg,\n}","source_hash":"96e626b940e9570ed599803b9e58b8902ffe3aff3db9ee799233657068c5dfd9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.model_configs.llama_hf_cfg","uri":"program://Fuser/function/benchmarks.python.model_configs.llama_hf_cfg#L7-L37","kind":"function","name":"llama_hf_cfg","path":"benchmarks/python/model_configs.py","language":"python","start_line":7,"end_line":37,"context_start_line":1,"context_end_line":57,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom functools import partial\n\n\ndef llama_hf_cfg(config_str):\n class Config:\n def __init__(\n self, n_head, head_size, n_query_groups, rope_n_elem, batches, seq_length\n ):\n self.n_head = n_head\n self.head_size = head_size\n self.n_query_groups = n_query_groups\n self.rope_n_elem = rope_n_elem\n self.batches = batches\n self.seq_length = seq_length\n\n configs = {}\n configs[\"llama_2_7b_hf\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=32,\n rope_n_elem=128,\n batches=2,\n seq_length=4096,\n )\n configs[\"llama_3_8B\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=8,\n rope_n_elem=128,\n batches=2,\n seq_length=8192,\n )\n\n return configs[config_str]\n\n\ndef hf_qwen2_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"Qwen/Qwen2.5-7B-Instruct\")\n config.batch_size = 1\n config.seq_len = 4096\n config._attn_implementation = \"sdpa\"\n return config\n\n\ndef hf_phi3_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"microsoft/Phi-3.5-mini-instruct\")\n config.batch_size = 1\n config.seq_len = 8192\n config._attn_implementation = \"sdpa\"\n return config","source_hash":"96e626b940e9570ed599803b9e58b8902ffe3aff3db9ee799233657068c5dfd9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.model_configs.hf_qwen2_cfg","uri":"program://Fuser/function/benchmarks.python.model_configs.hf_qwen2_cfg#L40-L47","kind":"function","name":"hf_qwen2_cfg","path":"benchmarks/python/model_configs.py","language":"python","start_line":40,"end_line":47,"context_start_line":20,"context_end_line":67,"code":" configs[\"llama_2_7b_hf\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=32,\n rope_n_elem=128,\n batches=2,\n seq_length=4096,\n )\n configs[\"llama_3_8B\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=8,\n rope_n_elem=128,\n batches=2,\n seq_length=8192,\n )\n\n return configs[config_str]\n\n\ndef hf_qwen2_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"Qwen/Qwen2.5-7B-Instruct\")\n config.batch_size = 1\n config.seq_len = 4096\n config._attn_implementation = \"sdpa\"\n return config\n\n\ndef hf_phi3_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"microsoft/Phi-3.5-mini-instruct\")\n config.batch_size = 1\n config.seq_len = 8192\n config._attn_implementation = \"sdpa\"\n return config\n\n\ndef hf_mistral_nemo_cfg():\n import json\n from transformers.models.mistral import MistralConfig\n\n mistral_cfg_str = r\"\"\"{\n \"_name_or_path\": \"mistralai/Mistral-Nemo-Base-2407\",\n \"architectures\": [\n \"MistralForCausalLM\"","source_hash":"96e626b940e9570ed599803b9e58b8902ffe3aff3db9ee799233657068c5dfd9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.model_configs.hf_phi3_cfg","uri":"program://Fuser/function/benchmarks.python.model_configs.hf_phi3_cfg#L50-L57","kind":"function","name":"hf_phi3_cfg","path":"benchmarks/python/model_configs.py","language":"python","start_line":50,"end_line":57,"context_start_line":30,"context_end_line":77,"code":" head_size=128,\n n_query_groups=8,\n rope_n_elem=128,\n batches=2,\n seq_length=8192,\n )\n\n return configs[config_str]\n\n\ndef hf_qwen2_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"Qwen/Qwen2.5-7B-Instruct\")\n config.batch_size = 1\n config.seq_len = 4096\n config._attn_implementation = \"sdpa\"\n return config\n\n\ndef hf_phi3_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"microsoft/Phi-3.5-mini-instruct\")\n config.batch_size = 1\n config.seq_len = 8192\n config._attn_implementation = \"sdpa\"\n return config\n\n\ndef hf_mistral_nemo_cfg():\n import json\n from transformers.models.mistral import MistralConfig\n\n mistral_cfg_str = r\"\"\"{\n \"_name_or_path\": \"mistralai/Mistral-Nemo-Base-2407\",\n \"architectures\": [\n \"MistralForCausalLM\"\n ],\n \"attention_dropout\": 0.0,\n \"bos_token_id\": 1,\n \"eos_token_id\": 2,\n \"head_dim\": 128,\n \"hidden_act\": \"silu\",\n \"hidden_size\": 5120,\n \"initializer_range\": 0.02,\n \"intermediate_size\": 14336,\n \"max_position_embeddings\": 128000,","source_hash":"96e626b940e9570ed599803b9e58b8902ffe3aff3db9ee799233657068c5dfd9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.model_configs.hf_mistral_nemo_cfg","uri":"program://Fuser/function/benchmarks.python.model_configs.hf_mistral_nemo_cfg#L60-L98","kind":"function","name":"hf_mistral_nemo_cfg","path":"benchmarks/python/model_configs.py","language":"python","start_line":60,"end_line":98,"context_start_line":40,"context_end_line":118,"code":"def hf_qwen2_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"Qwen/Qwen2.5-7B-Instruct\")\n config.batch_size = 1\n config.seq_len = 4096\n config._attn_implementation = \"sdpa\"\n return config\n\n\ndef hf_phi3_cfg():\n from transformers import AutoConfig\n\n config = AutoConfig.from_pretrained(\"microsoft/Phi-3.5-mini-instruct\")\n config.batch_size = 1\n config.seq_len = 8192\n config._attn_implementation = \"sdpa\"\n return config\n\n\ndef hf_mistral_nemo_cfg():\n import json\n from transformers.models.mistral import MistralConfig\n\n mistral_cfg_str = r\"\"\"{\n \"_name_or_path\": \"mistralai/Mistral-Nemo-Base-2407\",\n \"architectures\": [\n \"MistralForCausalLM\"\n ],\n \"attention_dropout\": 0.0,\n \"bos_token_id\": 1,\n \"eos_token_id\": 2,\n \"head_dim\": 128,\n \"hidden_act\": \"silu\",\n \"hidden_size\": 5120,\n \"initializer_range\": 0.02,\n \"intermediate_size\": 14336,\n \"max_position_embeddings\": 128000,\n \"model_type\": \"mistral\",\n \"num_attention_heads\": 32,\n \"num_hidden_layers\": 40,\n \"num_key_value_heads\": 8,\n \"rms_norm_eps\": 1e-05,\n \"rope_theta\": 1000000.0,\n \"sliding_window\": null,\n \"tie_word_embeddings\": false,\n \"torch_dtype\": \"bfloat16\",\n \"transformers_version\": \"4.43.3\",\n \"use_cache\": true,\n \"vocab_size\": 131072\n }\n \"\"\"\n\n cfg = MistralConfig.from_dict(json.loads(mistral_cfg_str))\n cfg.batch_size = 1\n cfg.seq_len = 4096\n cfg._attn_implementation = \"sdpa\"\n\n return cfg\n\n\ndef litgpt_cfg(model_name):\n import litgpt\n\n cfg = litgpt.Config.from_name(model_name)\n cfg.batch_size = 1\n cfg.seq_len = 4096\n cfg.name_or_path = model_name\n\n return cfg\n\n\nconfigs = {\n \"llama_2_7b_hf\": partial(llama_hf_cfg, config_str=\"llama_2_7b_hf\"),\n \"llama_3_8B\": partial(llama_hf_cfg, config_str=\"llama_3_8B\"),\n \"hf_qwen2\": hf_qwen2_cfg,\n \"hf_phi3\": hf_phi3_cfg,\n \"hf_mistral_nemo\": hf_mistral_nemo_cfg,\n \"litgpt\": litgpt_cfg,","source_hash":"96e626b940e9570ed599803b9e58b8902ffe3aff3db9ee799233657068c5dfd9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.model_configs.litgpt_cfg","uri":"program://Fuser/function/benchmarks.python.model_configs.litgpt_cfg#L101-L109","kind":"function","name":"litgpt_cfg","path":"benchmarks/python/model_configs.py","language":"python","start_line":101,"end_line":109,"context_start_line":81,"context_end_line":119,"code":" \"num_key_value_heads\": 8,\n \"rms_norm_eps\": 1e-05,\n \"rope_theta\": 1000000.0,\n \"sliding_window\": null,\n \"tie_word_embeddings\": false,\n \"torch_dtype\": \"bfloat16\",\n \"transformers_version\": \"4.43.3\",\n \"use_cache\": true,\n \"vocab_size\": 131072\n }\n \"\"\"\n\n cfg = MistralConfig.from_dict(json.loads(mistral_cfg_str))\n cfg.batch_size = 1\n cfg.seq_len = 4096\n cfg._attn_implementation = \"sdpa\"\n\n return cfg\n\n\ndef litgpt_cfg(model_name):\n import litgpt\n\n cfg = litgpt.Config.from_name(model_name)\n cfg.batch_size = 1\n cfg.seq_len = 4096\n cfg.name_or_path = model_name\n\n return cfg\n\n\nconfigs = {\n \"llama_2_7b_hf\": partial(llama_hf_cfg, config_str=\"llama_2_7b_hf\"),\n \"llama_3_8B\": partial(llama_hf_cfg, config_str=\"llama_3_8B\"),\n \"hf_qwen2\": hf_qwen2_cfg,\n \"hf_phi3\": hf_phi3_cfg,\n \"hf_mistral_nemo\": hf_mistral_nemo_cfg,\n \"litgpt\": litgpt_cfg,\n}","source_hash":"96e626b940e9570ed599803b9e58b8902ffe3aff3db9ee799233657068c5dfd9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.model_configs.Config","uri":"program://Fuser/class/benchmarks.python.model_configs.Config#L8-L17","kind":"class","name":"Config","path":"benchmarks/python/model_configs.py","language":"python","start_line":8,"end_line":17,"context_start_line":1,"context_end_line":37,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom functools import partial\n\n\ndef llama_hf_cfg(config_str):\n class Config:\n def __init__(\n self, n_head, head_size, n_query_groups, rope_n_elem, batches, seq_length\n ):\n self.n_head = n_head\n self.head_size = head_size\n self.n_query_groups = n_query_groups\n self.rope_n_elem = rope_n_elem\n self.batches = batches\n self.seq_length = seq_length\n\n configs = {}\n configs[\"llama_2_7b_hf\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=32,\n rope_n_elem=128,\n batches=2,\n seq_length=4096,\n )\n configs[\"llama_3_8B\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=8,\n rope_n_elem=128,\n batches=2,\n seq_length=8192,\n )\n\n return configs[config_str]","source_hash":"96e626b940e9570ed599803b9e58b8902ffe3aff3db9ee799233657068c5dfd9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.model_configs.__init__","uri":"program://Fuser/function/benchmarks.python.model_configs.__init__#L9-L17","kind":"function","name":"__init__","path":"benchmarks/python/model_configs.py","language":"python","start_line":9,"end_line":17,"context_start_line":1,"context_end_line":37,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom functools import partial\n\n\ndef llama_hf_cfg(config_str):\n class Config:\n def __init__(\n self, n_head, head_size, n_query_groups, rope_n_elem, batches, seq_length\n ):\n self.n_head = n_head\n self.head_size = head_size\n self.n_query_groups = n_query_groups\n self.rope_n_elem = rope_n_elem\n self.batches = batches\n self.seq_length = seq_length\n\n configs = {}\n configs[\"llama_2_7b_hf\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=32,\n rope_n_elem=128,\n batches=2,\n seq_length=4096,\n )\n configs[\"llama_3_8B\"] = Config(\n n_head=32,\n head_size=128,\n n_query_groups=8,\n rope_n_elem=128,\n batches=2,\n seq_length=8192,\n )\n\n return configs[config_str]","source_hash":"96e626b940e9570ed599803b9e58b8902ffe3aff3db9ee799233657068c5dfd9","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_bwd","uri":"program://Fuser/module/benchmarks.python.test_layernorm_bwd#L1-L185","kind":"module","name":"benchmarks.python.test_layernorm_bwd","path":"benchmarks/python/test_layernorm_bwd.py","language":"python","start_line":1,"end_line":185,"context_start_line":1,"context_end_line":185,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import layernorm\n\n\ndef layernorm_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n )\n\n T4 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n\n T9 = fd.ops.broadcast_in_dim(T2, shape=[T0.size(0), 1], broadcast_dims=[0])\n V12 = T0.shape()\n T13 = fd.ops.broadcast_in_dim(T9, shape=V12, broadcast_dims=[0, 1])\n T14 = fd.ops.sub(T0, T13)\n\n T18 = fd.ops.broadcast_in_dim(T3, shape=V12, broadcast_dims=[0, 1])\n T19 = fd.ops.mul(T14, T18)\n\n T23 = fd.ops.broadcast_in_dim(T4, shape=V12, broadcast_dims=[1])\n T28 = fd.ops.sum(T1, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T30 = fd.ops.mul(T1, T23)\n T31 = fd.ops.mul(T1, T19)\n T32 = fd.ops.sum(T31, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T34 = fd.ops.mul(T30, T18)\n T35 = fd.ops.mul(T30, T14)\n T36 = fd.ops.sum(T35, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T40 = fd.ops.broadcast_in_dim(T36, shape=[T0.size(0), 1], broadcast_dims=[0])\n T41 = fd.ops.neg(T34)\n T42 = fd.ops.sum(T41, dims=[1], keepdim=False, dtype=DataType.Null)\n T46 = fd.ops.broadcast_in_dim(T42, shape=[T0.size(0), 1], broadcast_dims=[0])\n S47 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T48 = fd.ops.mul(S47, T40)\n S49 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T50 = fd.ops.pow(T3, S49)\n T51 = fd.ops.mul(T48, T50)\n T54 = fd.ops.sum(T46, dims=[1], keepdim=False, dtype=DataType.Null)\n T55 = fd.ops.sum(T51, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T59 = fd.ops.broadcast_in_dim(T55, shape=[T0.size(0), 1], broadcast_dims=[0])\n T63 = fd.ops.broadcast_in_dim(T59, shape=V12, broadcast_dims=[0, 1])\n T67 = fd.ops.broadcast_in_dim(T2, shape=[T0.size(0), 1], broadcast_dims=[0])\n T71 = fd.ops.broadcast_in_dim(T67, shape=V12, broadcast_dims=[0, 1])\n\n S72 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T73 = fd.ops.mul(S72, T63)\n T74 = fd.ops.sub(T0, T71)\n T75 = fd.ops.mul(T73, T74)\n\n S77 = fd.ops.reciprocal(T0.size(1))\n T78 = fd.ops.mul(T75, S77)\n T82 = fd.ops.broadcast_in_dim(T54, shape=[T0.size(0), 1], broadcast_dims=[0])\n T86 = fd.ops.broadcast_in_dim(T82, shape=V12, broadcast_dims=[0, 1])\n T88 = fd.ops.mul(S77, T86)\n T89 = fd.ops.add(T78, T88)\n T90 = fd.ops.add(T34, T89)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T90 = fd.ops.cast(T90, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T90)\n fd.add_output(T32)\n fd.add_output(T28)\n\n\ndef layernorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, mean, invstd, weigts) differ from baselines (out, grad_out)\n # Total IO bytes = in_tensor (size, dtype) + grad_out (size, dtype) + mean (size[0], float) +\n # invstd (size[0], float) + weights (size[1], dtype) +\n # grad_in (size, dtype) + grad_weights (size[1], dtype)+ grad_bias (size[1], dtype)\n return int(\n dtype.itemsize * 3 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_layernorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n mean = inputs.to(torch.float).mean(dim=-1)\n variance = inputs.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n with FusionDefinition() as fd:\n layernorm_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.nn.functional.layer_norm(\n inputs.to(torch.double),\n inputs.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate(\n [inputs, grads, mean, invstd, weights],\n [inputs.grad, weights.grad, bias.grad],\n )\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, grads, mean, invstd, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_layernorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n fwd_fn = with_executor(executor, layernorm)\n fwd_inputs = [inputs, weights, bias]\n outputs = fwd_fn(fwd_inputs)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=layernorm_bwd_iobytes(size, dtype),\n )","source_hash":"390e673a86f9c1d90d4d64edab5d9932810f308af04deeb06833854db8832b05","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_bwd.layernorm_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_layernorm_bwd.layernorm_bwd_fusion#L20-L101","kind":"function","name":"layernorm_bwd_fusion","path":"benchmarks/python/test_layernorm_bwd.py","language":"python","start_line":20,"end_line":101,"context_start_line":1,"context_end_line":121,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import layernorm\n\n\ndef layernorm_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n\n T2 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=DataType.Float, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n )\n\n T4 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n\n T9 = fd.ops.broadcast_in_dim(T2, shape=[T0.size(0), 1], broadcast_dims=[0])\n V12 = T0.shape()\n T13 = fd.ops.broadcast_in_dim(T9, shape=V12, broadcast_dims=[0, 1])\n T14 = fd.ops.sub(T0, T13)\n\n T18 = fd.ops.broadcast_in_dim(T3, shape=V12, broadcast_dims=[0, 1])\n T19 = fd.ops.mul(T14, T18)\n\n T23 = fd.ops.broadcast_in_dim(T4, shape=V12, broadcast_dims=[1])\n T28 = fd.ops.sum(T1, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T30 = fd.ops.mul(T1, T23)\n T31 = fd.ops.mul(T1, T19)\n T32 = fd.ops.sum(T31, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T34 = fd.ops.mul(T30, T18)\n T35 = fd.ops.mul(T30, T14)\n T36 = fd.ops.sum(T35, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T40 = fd.ops.broadcast_in_dim(T36, shape=[T0.size(0), 1], broadcast_dims=[0])\n T41 = fd.ops.neg(T34)\n T42 = fd.ops.sum(T41, dims=[1], keepdim=False, dtype=DataType.Null)\n T46 = fd.ops.broadcast_in_dim(T42, shape=[T0.size(0), 1], broadcast_dims=[0])\n S47 = fd.define_scalar(-0.500000, dtype=DataType.Double)\n T48 = fd.ops.mul(S47, T40)\n S49 = fd.define_scalar(3.00000, dtype=DataType.Double)\n T50 = fd.ops.pow(T3, S49)\n T51 = fd.ops.mul(T48, T50)\n T54 = fd.ops.sum(T46, dims=[1], keepdim=False, dtype=DataType.Null)\n T55 = fd.ops.sum(T51, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T59 = fd.ops.broadcast_in_dim(T55, shape=[T0.size(0), 1], broadcast_dims=[0])\n T63 = fd.ops.broadcast_in_dim(T59, shape=V12, broadcast_dims=[0, 1])\n T67 = fd.ops.broadcast_in_dim(T2, shape=[T0.size(0), 1], broadcast_dims=[0])\n T71 = fd.ops.broadcast_in_dim(T67, shape=V12, broadcast_dims=[0, 1])\n\n S72 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T73 = fd.ops.mul(S72, T63)\n T74 = fd.ops.sub(T0, T71)\n T75 = fd.ops.mul(T73, T74)\n\n S77 = fd.ops.reciprocal(T0.size(1))\n T78 = fd.ops.mul(T75, S77)\n T82 = fd.ops.broadcast_in_dim(T54, shape=[T0.size(0), 1], broadcast_dims=[0])\n T86 = fd.ops.broadcast_in_dim(T82, shape=V12, broadcast_dims=[0, 1])\n T88 = fd.ops.mul(S77, T86)\n T89 = fd.ops.add(T78, T88)\n T90 = fd.ops.add(T34, T89)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T90 = fd.ops.cast(T90, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T90)\n fd.add_output(T32)\n fd.add_output(T28)\n\n\ndef layernorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, mean, invstd, weigts) differ from baselines (out, grad_out)\n # Total IO bytes = in_tensor (size, dtype) + grad_out (size, dtype) + mean (size[0], float) +\n # invstd (size[0], float) + weights (size[1], dtype) +\n # grad_in (size, dtype) + grad_weights (size[1], dtype)+ grad_bias (size[1], dtype)\n return int(\n dtype.itemsize * 3 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_layernorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,","source_hash":"390e673a86f9c1d90d4d64edab5d9932810f308af04deeb06833854db8832b05","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_bwd.layernorm_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_layernorm_bwd.layernorm_bwd_iobytes#L104-L112","kind":"function","name":"layernorm_bwd_iobytes","path":"benchmarks/python/test_layernorm_bwd.py","language":"python","start_line":104,"end_line":112,"context_start_line":84,"context_end_line":132,"code":" T75 = fd.ops.mul(T73, T74)\n\n S77 = fd.ops.reciprocal(T0.size(1))\n T78 = fd.ops.mul(T75, S77)\n T82 = fd.ops.broadcast_in_dim(T54, shape=[T0.size(0), 1], broadcast_dims=[0])\n T86 = fd.ops.broadcast_in_dim(T82, shape=V12, broadcast_dims=[0, 1])\n T88 = fd.ops.mul(S77, T86)\n T89 = fd.ops.add(T78, T88)\n T90 = fd.ops.add(T34, T89)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n T90 = fd.ops.cast(T90, dtype=dtype)\n T32 = fd.ops.cast(T32, dtype=dtype)\n\n fd.add_output(T90)\n fd.add_output(T32)\n fd.add_output(T28)\n\n\ndef layernorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, mean, invstd, weigts) differ from baselines (out, grad_out)\n # Total IO bytes = in_tensor (size, dtype) + grad_out (size, dtype) + mean (size[0], float) +\n # invstd (size[0], float) + weights (size[1], dtype) +\n # grad_in (size, dtype) + grad_weights (size[1], dtype)+ grad_bias (size[1], dtype)\n return int(\n dtype.itemsize * 3 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_layernorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n mean = inputs.to(torch.float).mean(dim=-1)","source_hash":"390e673a86f9c1d90d4d64edab5d9932810f308af04deeb06833854db8832b05","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_bwd.test_layernorm_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_layernorm_bwd.test_layernorm_bwd_nvf_benchmark#L119-L153","kind":"function","name":"test_layernorm_bwd_nvf_benchmark","path":"benchmarks/python/test_layernorm_bwd.py","language":"python","start_line":119,"end_line":153,"context_start_line":99,"context_end_line":173,"code":" fd.add_output(T90)\n fd.add_output(T32)\n fd.add_output(T28)\n\n\ndef layernorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, mean, invstd, weigts) differ from baselines (out, grad_out)\n # Total IO bytes = in_tensor (size, dtype) + grad_out (size, dtype) + mean (size[0], float) +\n # invstd (size[0], float) + weights (size[1], dtype) +\n # grad_in (size, dtype) + grad_weights (size[1], dtype)+ grad_bias (size[1], dtype)\n return int(\n dtype.itemsize * 3 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_layernorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n mean = inputs.to(torch.float).mean(dim=-1)\n variance = inputs.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n with FusionDefinition() as fd:\n layernorm_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = torch.nn.functional.layer_norm(\n inputs.to(torch.double),\n inputs.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate(\n [inputs, grads, mean, invstd, weights],\n [inputs.grad, weights.grad, bias.grad],\n )\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, grads, mean, invstd, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_layernorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)","source_hash":"390e673a86f9c1d90d4d64edab5d9932810f308af04deeb06833854db8832b05","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_bwd.test_layernorm_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_layernorm_bwd.test_layernorm_bwd_baseline_benchmark#L161-L185","kind":"function","name":"test_layernorm_bwd_baseline_benchmark","path":"benchmarks/python/test_layernorm_bwd.py","language":"python","start_line":161,"end_line":185,"context_start_line":141,"context_end_line":185,"code":" inputs.to(torch.double),\n inputs.shape[1:],\n weight=weights.to(torch.double),\n bias=bias.to(torch.double),\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate(\n [inputs, grads, mean, invstd, weights],\n [inputs.grad, weights.grad, bias.grad],\n )\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, grads, mean, invstd, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_layernorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(*size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n fwd_fn = with_executor(executor, layernorm)\n fwd_inputs = [inputs, weights, bias]\n outputs = fwd_fn(fwd_inputs)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=layernorm_bwd_iobytes(size, dtype),\n )","source_hash":"390e673a86f9c1d90d4d64edab5d9932810f308af04deeb06833854db8832b05","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_llama4_inference","uri":"program://Fuser/module/benchmarks.python.test_llama4_inference#L1-L64","kind":"module","name":"benchmarks.python.test_llama4_inference","path":"benchmarks/python/test_llama4_inference.py","language":"python","start_line":1,"end_line":64,"context_start_line":1,"context_end_line":64,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .benchmark_inference import (\n InferenceBenchmarkConfig,\n InferenceBenchmark,\n _register_nvfp4_ops,\n)\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\n\n\n# NOTE: for some reason, changing the order of nvfp4 and cudagraph parameter breaks thunder benchmark. I suspect there's something with thunder's cache.\n@pytest.mark.parametrize(\"input_length\", [4096])\n@pytest.mark.parametrize(\"output_length\", [4])\n@pytest.mark.parametrize(\"mode\", [\"thunder\", \"inductor\"])\n@pytest.mark.parametrize(\"enable_nvfp4\", [True, False])\n@pytest.mark.parametrize(\"enable_cudagraph\", [False, True])\ndef test_llama4_inference_benchmark(\n benchmark,\n input_length: int,\n output_length: int,\n mode: str,\n enable_nvfp4: bool,\n enable_cudagraph: bool,\n):\n if mode == \"inductor\" and enable_nvfp4:\n pytest.skip(\"nvfp4 is not supported by inductor yet.\")\n\n if mode == \"thunder\" and enable_nvfp4 and enable_cudagraph:\n pytest.skip(\"FIXME: nvfp4 and cudagraph doesn't work together.\")\n\n if DEVICE_PROPERTIES[\"gpu_compute_capability_major\"] < 10:\n if enable_nvfp4:\n pytest.skip(\"nvfp4 support requires compute_capability >= 10.0\")\n if mode == \"thunder\" and enable_cudagraph:\n pytest.skip(\"cudagraph doesn't support grouped matmul\")\n\n if enable_nvfp4:\n _register_nvfp4_ops()\n\n config = InferenceBenchmarkConfig(\n model_name=\"meta-llama/Llama-4-Maverick-17B-128E\",\n batch_size=1,\n input_length=input_length,\n output_length=output_length,\n num_layers=2,\n num_iterations=5,\n warmup_iterations=5,\n mode=mode,\n enable_nvfp4=enable_nvfp4,\n fx_report_folder=None,\n enable_nv_linear=True,\n disable_moe_replacement=False,\n attn_implementation=None,\n thunder_cache=None,\n enable_cudagraph=enable_cudagraph,\n debug_moe=False,\n use_hardcoded_model=True,\n )\n inference_benchmark = InferenceBenchmark(config)\n\n inference_benchmark.run_benchmark()\n inference_benchmark.print_results()","source_hash":"eddb0808b172e6a198747f249147731453c027dea6ad0c568f8d34f6a1b2195c","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_llama4_inference.test_llama4_inference_benchmark","uri":"program://Fuser/function/benchmarks.python.test_llama4_inference.test_llama4_inference_benchmark#L19-L64","kind":"function","name":"test_llama4_inference_benchmark","path":"benchmarks/python/test_llama4_inference.py","language":"python","start_line":19,"end_line":64,"context_start_line":1,"context_end_line":64,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .benchmark_inference import (\n InferenceBenchmarkConfig,\n InferenceBenchmark,\n _register_nvfp4_ops,\n)\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\n\n\n# NOTE: for some reason, changing the order of nvfp4 and cudagraph parameter breaks thunder benchmark. I suspect there's something with thunder's cache.\n@pytest.mark.parametrize(\"input_length\", [4096])\n@pytest.mark.parametrize(\"output_length\", [4])\n@pytest.mark.parametrize(\"mode\", [\"thunder\", \"inductor\"])\n@pytest.mark.parametrize(\"enable_nvfp4\", [True, False])\n@pytest.mark.parametrize(\"enable_cudagraph\", [False, True])\ndef test_llama4_inference_benchmark(\n benchmark,\n input_length: int,\n output_length: int,\n mode: str,\n enable_nvfp4: bool,\n enable_cudagraph: bool,\n):\n if mode == \"inductor\" and enable_nvfp4:\n pytest.skip(\"nvfp4 is not supported by inductor yet.\")\n\n if mode == \"thunder\" and enable_nvfp4 and enable_cudagraph:\n pytest.skip(\"FIXME: nvfp4 and cudagraph doesn't work together.\")\n\n if DEVICE_PROPERTIES[\"gpu_compute_capability_major\"] < 10:\n if enable_nvfp4:\n pytest.skip(\"nvfp4 support requires compute_capability >= 10.0\")\n if mode == \"thunder\" and enable_cudagraph:\n pytest.skip(\"cudagraph doesn't support grouped matmul\")\n\n if enable_nvfp4:\n _register_nvfp4_ops()\n\n config = InferenceBenchmarkConfig(\n model_name=\"meta-llama/Llama-4-Maverick-17B-128E\",\n batch_size=1,\n input_length=input_length,\n output_length=output_length,\n num_layers=2,\n num_iterations=5,\n warmup_iterations=5,\n mode=mode,\n enable_nvfp4=enable_nvfp4,\n fx_report_folder=None,\n enable_nv_linear=True,\n disable_moe_replacement=False,\n attn_implementation=None,\n thunder_cache=None,\n enable_cudagraph=enable_cudagraph,\n debug_moe=False,\n use_hardcoded_model=True,\n )\n inference_benchmark = InferenceBenchmark(config)\n\n inference_benchmark.run_benchmark()\n inference_benchmark.print_results()","source_hash":"eddb0808b172e6a198747f249147731453c027dea6ad0c568f8d34f6a1b2195c","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_fwd","uri":"program://Fuser/module/benchmarks.python.test_scale_bias_relu_fwd#L1-L106","kind":"module","name":"benchmarks.python.test_scale_bias_relu_fwd","path":"benchmarks/python/test_scale_bias_relu_fwd.py","language":"python","start_line":1,"end_line":106,"context_start_line":1,"context_end_line":106,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import scale_bias_relu\n\n\ndef sbr_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n):\n T0 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n V7 = T2.shape()\n T8 = fd.ops.broadcast_in_dim(T1, shape=V7, broadcast_dims=[1])\n T11 = fd.ops.mul(T2, T8)\n\n T18 = fd.ops.broadcast_in_dim(T0, shape=V7, broadcast_dims=[1])\n T20 = fd.ops.add(T11, T18)\n\n if dtype in PROMOTE_DTYPES:\n T20 = fd.ops.cast(T20, dtype=dtype)\n\n S22 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T23 = fd.ops.gt(T20, S22)\n T25 = fd.ops.where(T23, T20, S22)\n\n fd.add_output(T23)\n fd.add_output(T25)\n\n\ndef sbr_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = input (dtype, size) + bias (dtype, size[-1]) + scale (dtype, size[-1])+ output (dtype, size) + bool_mask (bool, size)\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[-1])\n + torch.bool.itemsize * np.prod(size)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n with FusionDefinition() as fd:\n sbr_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = torch.nn.functional.relu(inputs * scale + bias)\n bool_mask = torch.gt(inputs * scale + bias, 0.0)\n fd.validate([bias, scale, inputs], [bool_mask, eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [bias, scale, inputs])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n benchmark_fn = with_executor(executor, scale_bias_relu)\n\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, scale, bias],\n iobytes=sbr_fwd_iobytes(size, dtype),\n )","source_hash":"d23b9f1c9eb5c42ddf2b7b27f9a6bce6da8e63e5c1285e9fe4184b814b9a4ca6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_fwd.sbr_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_scale_bias_relu_fwd.sbr_fwd_fusion#L14-L47","kind":"function","name":"sbr_fwd_fusion","path":"benchmarks/python/test_scale_bias_relu_fwd.py","language":"python","start_line":14,"end_line":47,"context_start_line":1,"context_end_line":67,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import scale_bias_relu\n\n\ndef sbr_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n):\n T0 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n V7 = T2.shape()\n T8 = fd.ops.broadcast_in_dim(T1, shape=V7, broadcast_dims=[1])\n T11 = fd.ops.mul(T2, T8)\n\n T18 = fd.ops.broadcast_in_dim(T0, shape=V7, broadcast_dims=[1])\n T20 = fd.ops.add(T11, T18)\n\n if dtype in PROMOTE_DTYPES:\n T20 = fd.ops.cast(T20, dtype=dtype)\n\n S22 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T23 = fd.ops.gt(T20, S22)\n T25 = fd.ops.where(T23, T20, S22)\n\n fd.add_output(T23)\n fd.add_output(T25)\n\n\ndef sbr_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = input (dtype, size) + bias (dtype, size[-1]) + scale (dtype, size[-1])+ output (dtype, size) + bool_mask (bool, size)\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[-1])\n + torch.bool.itemsize * np.prod(size)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):","source_hash":"d23b9f1c9eb5c42ddf2b7b27f9a6bce6da8e63e5c1285e9fe4184b814b9a4ca6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_fwd.sbr_fwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_scale_bias_relu_fwd.sbr_fwd_iobytes#L50-L55","kind":"function","name":"sbr_fwd_iobytes","path":"benchmarks/python/test_scale_bias_relu_fwd.py","language":"python","start_line":50,"end_line":55,"context_start_line":30,"context_end_line":75,"code":" T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n V7 = T2.shape()\n T8 = fd.ops.broadcast_in_dim(T1, shape=V7, broadcast_dims=[1])\n T11 = fd.ops.mul(T2, T8)\n\n T18 = fd.ops.broadcast_in_dim(T0, shape=V7, broadcast_dims=[1])\n T20 = fd.ops.add(T11, T18)\n\n if dtype in PROMOTE_DTYPES:\n T20 = fd.ops.cast(T20, dtype=dtype)\n\n S22 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T23 = fd.ops.gt(T20, S22)\n T25 = fd.ops.where(T23, T20, S22)\n\n fd.add_output(T23)\n fd.add_output(T25)\n\n\ndef sbr_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = input (dtype, size) + bias (dtype, size[-1]) + scale (dtype, size[-1])+ output (dtype, size) + bool_mask (bool, size)\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[-1])\n + torch.bool.itemsize * np.prod(size)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n with FusionDefinition() as fd:\n sbr_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = torch.nn.functional.relu(inputs * scale + bias)","source_hash":"d23b9f1c9eb5c42ddf2b7b27f9a6bce6da8e63e5c1285e9fe4184b814b9a4ca6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_fwd.test_sbr_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_scale_bias_relu_fwd.test_sbr_fwd_nvf_benchmark#L61-L80","kind":"function","name":"test_sbr_fwd_nvf_benchmark","path":"benchmarks/python/test_scale_bias_relu_fwd.py","language":"python","start_line":61,"end_line":80,"context_start_line":41,"context_end_line":100,"code":"\n S22 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T23 = fd.ops.gt(T20, S22)\n T25 = fd.ops.where(T23, T20, S22)\n\n fd.add_output(T23)\n fd.add_output(T25)\n\n\ndef sbr_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Total IO bytes = input (dtype, size) + bias (dtype, size[-1]) + scale (dtype, size[-1])+ output (dtype, size) + bool_mask (bool, size)\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[-1])\n + torch.bool.itemsize * np.prod(size)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n with FusionDefinition() as fd:\n sbr_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = torch.nn.functional.relu(inputs * scale + bias)\n bool_mask = torch.gt(inputs * scale + bias, 0.0)\n fd.validate([bias, scale, inputs], [bool_mask, eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [bias, scale, inputs])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n benchmark_fn = with_executor(executor, scale_bias_relu)\n","source_hash":"d23b9f1c9eb5c42ddf2b7b27f9a6bce6da8e63e5c1285e9fe4184b814b9a4ca6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_scale_bias_relu_fwd.test_sbr_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_scale_bias_relu_fwd.test_sbr_fwd_baseline_benchmark#L87-L106","kind":"function","name":"test_sbr_fwd_baseline_benchmark","path":"benchmarks/python/test_scale_bias_relu_fwd.py","language":"python","start_line":87,"end_line":106,"context_start_line":67,"context_end_line":106,"code":"):\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n with FusionDefinition() as fd:\n sbr_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n if not disable_validation:\n eager_output = torch.nn.functional.relu(inputs * scale + bias)\n bool_mask = torch.gt(inputs * scale + bias, 0.0)\n fd.validate([bias, scale, inputs], [bool_mask, eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [bias, scale, inputs])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.pointwise\ndef test_sbr_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(*size, device=\"cuda\", dtype=dtype, requires_grad=True)\n bias = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n scale = torch.ones(size[-1], device=\"cuda\", dtype=dtype)\n\n benchmark_fn = with_executor(executor, scale_bias_relu)\n\n run_benchmark(\n benchmark,\n benchmark_fn,\n [inputs, scale, bias],\n iobytes=sbr_fwd_iobytes(size, dtype),\n )","source_hash":"d23b9f1c9eb5c42ddf2b7b27f9a6bce6da8e63e5c1285e9fe4184b814b9a4ca6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_matmul","uri":"program://Fuser/module/benchmarks.python.test_matmul#L1-L150","kind":"module","name":"benchmarks.python.test_matmul","path":"benchmarks/python/test_matmul.py","language":"python","start_line":1,"end_line":150,"context_start_line":1,"context_end_line":150,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition\nfrom .core import run_benchmark\nimport torch\n\nimport csv\nimport functools\nimport os\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\ndef load_matmul_problems():\n with open(os.path.join(os.path.dirname(__file__), \"matmul_problems.csv\"), \"r\") as f:\n reader = csv.reader(f)\n next(reader, None) # skip header row\n rows = list((int(m), int(n), int(k), layout) for m, n, k, layout in reader)\n\n def row_mem(row):\n \"\"\"Compute gmem bytes used in a half-precision GEMM\n\n This computes only the space required for operands and output,\n ignoring intermediates like split-K buffers and assuming no bias\n terms.\n \"\"\"\n m, n, k, _ = row\n return ((m + n) * k + m * n) * 2\n\n def three_way_cmp(a, b) -> int:\n \"\"\"Perform a three-way comparison like the Python2 cmp() function\n\n This returns 0 if a == b, -1 if a < b, and 1 if a > b\n \"\"\"\n return int(a > b) - int(a < b)\n\n def mem_cmp(row1, row2):\n \"\"\"Compare two rows based on memory use\"\"\"\n return three_way_cmp(row_mem(row1), row_mem(row2))\n\n # Reverse sort by expected memory use to avoid fragmentation\n rows.sort(key=functools.cmp_to_key(mem_cmp), reverse=True)\n\n return rows\n\n\ndef maybe_skip_oom_case(m: int, n: int, k: int):\n expected_mem = (m * k + n * k + m * n) * 2 # operands plus output\n expected_mem *= 2 # account for multiple runs/deferred frees\n\n _, total = torch.cuda.mem_get_info()\n max_mem = total * 0.9\n if expected_mem > max_mem:\n pytest.skip(\n f\"Case takes more than {max_mem / (2 ** 30): .2f} GiB. Skipping to avoid OOM\"\n )\n\n\n@pytest.mark.parametrize(\"half_reduction\", [False, True], ids=[\"fullred\", \"halfred\"])\n@pytest.mark.parametrize(\"executor\", [\"eager\"])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16], ids=[\"fp16\", \"bf16\"])\n@pytest.mark.parametrize(\n \"config\", load_matmul_problems(), ids=lambda val: \"-\".join(str(v) for v in val)\n)\n@pytest.mark.matmul\ndef test_matmul_baseline_benchmark(\n benchmark,\n executor: str,\n config: tuple,\n dtype: torch.dtype,\n half_reduction: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n m, n, k, layout = config\n\n maybe_skip_oom_case(m, n, k)\n\n torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = half_reduction\n torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = half_reduction\n\n a = torch.randn(m, k, device=\"cuda\", dtype=dtype)\n b = torch.randn(k, n, device=\"cuda\", dtype=dtype)\n\n if layout == \"NT\" or layout == \"NN\":\n a = a.as_strided(size=[m, k], stride=[1, m])\n if layout == \"TN\" or layout == \"NN\":\n b = b.as_strided(size=[k, n], stride=[1, k])\n\n # NOTE: we never need to validate eager, as it is our baseline\n run_benchmark(\n benchmark,\n lambda ab: torch.matmul(*ab),\n [a, b],\n )\n\n\n@pytest.mark.parametrize(\"half_reduction\", [False, True], ids=[\"fullred\", \"halfred\"])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16], ids=[\"fp16\", \"bf16\"])\n@pytest.mark.parametrize(\n \"config\", load_matmul_problems(), ids=lambda val: \"-\".join(str(v) for v in val)\n)\n@pytest.mark.matmul\ndef test_matmul_nvf_benchmark(\n benchmark,\n config: tuple,\n dtype: torch.dtype,\n half_reduction: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n m, n, k, layout = config\n\n maybe_skip_oom_case(m, n, k)\n\n torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = half_reduction\n torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = half_reduction\n\n if half_reduction:\n # See https://github.com/NVIDIA/Fuser/pull/1719\n pytest.skip(\"Reduced precision reduction not implemented in nvFuser\")\n\n a = torch.randn(m, k, device=\"cuda\", dtype=dtype)\n b = torch.randn(k, n, device=\"cuda\", dtype=dtype)\n\n if layout == \"NT\" or layout == \"NN\":\n a = a.as_strided(size=[m, k], stride=[1, m])\n if layout == \"TN\" or layout == \"NN\":\n b = b.as_strided(size=[k, n], stride=[1, k])\n\n with FusionDefinition() as fd:\n matmul_fusion(fd, [a, b])\n\n kwargs = dict(\n _enable_options=[\"fuse_matmul\"], _disable_options=[\"matmul_expr_eval\"]\n )\n\n if not disable_validation:\n eager_output = torch.matmul(a, b)\n fd.validate([a, b], [eager_output], **kwargs)\n\n if not disable_benchmarking:\n run_benchmark(benchmark, lambda *args: fd.execute(*args, **kwargs), [a, b])","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_matmul.matmul_fusion","uri":"program://Fuser/function/benchmarks.python.test_matmul.matmul_fusion#L14-L18","kind":"function","name":"matmul_fusion","path":"benchmarks/python/test_matmul.py","language":"python","start_line":14,"end_line":18,"context_start_line":1,"context_end_line":38,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition\nfrom .core import run_benchmark\nimport torch\n\nimport csv\nimport functools\nimport os\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\ndef load_matmul_problems():\n with open(os.path.join(os.path.dirname(__file__), \"matmul_problems.csv\"), \"r\") as f:\n reader = csv.reader(f)\n next(reader, None) # skip header row\n rows = list((int(m), int(n), int(k), layout) for m, n, k, layout in reader)\n\n def row_mem(row):\n \"\"\"Compute gmem bytes used in a half-precision GEMM\n\n This computes only the space required for operands and output,\n ignoring intermediates like split-K buffers and assuming no bias\n terms.\n \"\"\"\n m, n, k, _ = row\n return ((m + n) * k + m * n) * 2\n\n def three_way_cmp(a, b) -> int:\n \"\"\"Perform a three-way comparison like the Python2 cmp() function","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_matmul.load_matmul_problems","uri":"program://Fuser/function/benchmarks.python.test_matmul.load_matmul_problems#L21-L51","kind":"function","name":"load_matmul_problems","path":"benchmarks/python/test_matmul.py","language":"python","start_line":21,"end_line":51,"context_start_line":1,"context_end_line":71,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition\nfrom .core import run_benchmark\nimport torch\n\nimport csv\nimport functools\nimport os\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\ndef load_matmul_problems():\n with open(os.path.join(os.path.dirname(__file__), \"matmul_problems.csv\"), \"r\") as f:\n reader = csv.reader(f)\n next(reader, None) # skip header row\n rows = list((int(m), int(n), int(k), layout) for m, n, k, layout in reader)\n\n def row_mem(row):\n \"\"\"Compute gmem bytes used in a half-precision GEMM\n\n This computes only the space required for operands and output,\n ignoring intermediates like split-K buffers and assuming no bias\n terms.\n \"\"\"\n m, n, k, _ = row\n return ((m + n) * k + m * n) * 2\n\n def three_way_cmp(a, b) -> int:\n \"\"\"Perform a three-way comparison like the Python2 cmp() function\n\n This returns 0 if a == b, -1 if a < b, and 1 if a > b\n \"\"\"\n return int(a > b) - int(a < b)\n\n def mem_cmp(row1, row2):\n \"\"\"Compare two rows based on memory use\"\"\"\n return three_way_cmp(row_mem(row1), row_mem(row2))\n\n # Reverse sort by expected memory use to avoid fragmentation\n rows.sort(key=functools.cmp_to_key(mem_cmp), reverse=True)\n\n return rows\n\n\ndef maybe_skip_oom_case(m: int, n: int, k: int):\n expected_mem = (m * k + n * k + m * n) * 2 # operands plus output\n expected_mem *= 2 # account for multiple runs/deferred frees\n\n _, total = torch.cuda.mem_get_info()\n max_mem = total * 0.9\n if expected_mem > max_mem:\n pytest.skip(\n f\"Case takes more than {max_mem / (2 ** 30): .2f} GiB. Skipping to avoid OOM\"\n )\n\n\n@pytest.mark.parametrize(\"half_reduction\", [False, True], ids=[\"fullred\", \"halfred\"])\n@pytest.mark.parametrize(\"executor\", [\"eager\"])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16], ids=[\"fp16\", \"bf16\"])\n@pytest.mark.parametrize(\n \"config\", load_matmul_problems(), ids=lambda val: \"-\".join(str(v) for v in val)\n)","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_matmul.maybe_skip_oom_case","uri":"program://Fuser/function/benchmarks.python.test_matmul.maybe_skip_oom_case#L54-L63","kind":"function","name":"maybe_skip_oom_case","path":"benchmarks/python/test_matmul.py","language":"python","start_line":54,"end_line":63,"context_start_line":34,"context_end_line":83,"code":" m, n, k, _ = row\n return ((m + n) * k + m * n) * 2\n\n def three_way_cmp(a, b) -> int:\n \"\"\"Perform a three-way comparison like the Python2 cmp() function\n\n This returns 0 if a == b, -1 if a < b, and 1 if a > b\n \"\"\"\n return int(a > b) - int(a < b)\n\n def mem_cmp(row1, row2):\n \"\"\"Compare two rows based on memory use\"\"\"\n return three_way_cmp(row_mem(row1), row_mem(row2))\n\n # Reverse sort by expected memory use to avoid fragmentation\n rows.sort(key=functools.cmp_to_key(mem_cmp), reverse=True)\n\n return rows\n\n\ndef maybe_skip_oom_case(m: int, n: int, k: int):\n expected_mem = (m * k + n * k + m * n) * 2 # operands plus output\n expected_mem *= 2 # account for multiple runs/deferred frees\n\n _, total = torch.cuda.mem_get_info()\n max_mem = total * 0.9\n if expected_mem > max_mem:\n pytest.skip(\n f\"Case takes more than {max_mem / (2 ** 30): .2f} GiB. Skipping to avoid OOM\"\n )\n\n\n@pytest.mark.parametrize(\"half_reduction\", [False, True], ids=[\"fullred\", \"halfred\"])\n@pytest.mark.parametrize(\"executor\", [\"eager\"])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16], ids=[\"fp16\", \"bf16\"])\n@pytest.mark.parametrize(\n \"config\", load_matmul_problems(), ids=lambda val: \"-\".join(str(v) for v in val)\n)\n@pytest.mark.matmul\ndef test_matmul_baseline_benchmark(\n benchmark,\n executor: str,\n config: tuple,\n dtype: torch.dtype,\n half_reduction: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n m, n, k, layout = config\n","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_matmul.test_matmul_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_matmul.test_matmul_baseline_benchmark#L73-L102","kind":"function","name":"test_matmul_baseline_benchmark","path":"benchmarks/python/test_matmul.py","language":"python","start_line":73,"end_line":102,"context_start_line":53,"context_end_line":122,"code":"\ndef maybe_skip_oom_case(m: int, n: int, k: int):\n expected_mem = (m * k + n * k + m * n) * 2 # operands plus output\n expected_mem *= 2 # account for multiple runs/deferred frees\n\n _, total = torch.cuda.mem_get_info()\n max_mem = total * 0.9\n if expected_mem > max_mem:\n pytest.skip(\n f\"Case takes more than {max_mem / (2 ** 30): .2f} GiB. Skipping to avoid OOM\"\n )\n\n\n@pytest.mark.parametrize(\"half_reduction\", [False, True], ids=[\"fullred\", \"halfred\"])\n@pytest.mark.parametrize(\"executor\", [\"eager\"])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16], ids=[\"fp16\", \"bf16\"])\n@pytest.mark.parametrize(\n \"config\", load_matmul_problems(), ids=lambda val: \"-\".join(str(v) for v in val)\n)\n@pytest.mark.matmul\ndef test_matmul_baseline_benchmark(\n benchmark,\n executor: str,\n config: tuple,\n dtype: torch.dtype,\n half_reduction: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n m, n, k, layout = config\n\n maybe_skip_oom_case(m, n, k)\n\n torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = half_reduction\n torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = half_reduction\n\n a = torch.randn(m, k, device=\"cuda\", dtype=dtype)\n b = torch.randn(k, n, device=\"cuda\", dtype=dtype)\n\n if layout == \"NT\" or layout == \"NN\":\n a = a.as_strided(size=[m, k], stride=[1, m])\n if layout == \"TN\" or layout == \"NN\":\n b = b.as_strided(size=[k, n], stride=[1, k])\n\n # NOTE: we never need to validate eager, as it is our baseline\n run_benchmark(\n benchmark,\n lambda ab: torch.matmul(*ab),\n [a, b],\n )\n\n\n@pytest.mark.parametrize(\"half_reduction\", [False, True], ids=[\"fullred\", \"halfred\"])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16], ids=[\"fp16\", \"bf16\"])\n@pytest.mark.parametrize(\n \"config\", load_matmul_problems(), ids=lambda val: \"-\".join(str(v) for v in val)\n)\n@pytest.mark.matmul\ndef test_matmul_nvf_benchmark(\n benchmark,\n config: tuple,\n dtype: torch.dtype,\n half_reduction: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n m, n, k, layout = config\n\n maybe_skip_oom_case(m, n, k)\n","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_matmul.test_matmul_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_matmul.test_matmul_nvf_benchmark#L111-L150","kind":"function","name":"test_matmul_nvf_benchmark","path":"benchmarks/python/test_matmul.py","language":"python","start_line":111,"end_line":150,"context_start_line":91,"context_end_line":150,"code":"\n if layout == \"NT\" or layout == \"NN\":\n a = a.as_strided(size=[m, k], stride=[1, m])\n if layout == \"TN\" or layout == \"NN\":\n b = b.as_strided(size=[k, n], stride=[1, k])\n\n # NOTE: we never need to validate eager, as it is our baseline\n run_benchmark(\n benchmark,\n lambda ab: torch.matmul(*ab),\n [a, b],\n )\n\n\n@pytest.mark.parametrize(\"half_reduction\", [False, True], ids=[\"fullred\", \"halfred\"])\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16], ids=[\"fp16\", \"bf16\"])\n@pytest.mark.parametrize(\n \"config\", load_matmul_problems(), ids=lambda val: \"-\".join(str(v) for v in val)\n)\n@pytest.mark.matmul\ndef test_matmul_nvf_benchmark(\n benchmark,\n config: tuple,\n dtype: torch.dtype,\n half_reduction: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n m, n, k, layout = config\n\n maybe_skip_oom_case(m, n, k)\n\n torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = half_reduction\n torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = half_reduction\n\n if half_reduction:\n # See https://github.com/NVIDIA/Fuser/pull/1719\n pytest.skip(\"Reduced precision reduction not implemented in nvFuser\")\n\n a = torch.randn(m, k, device=\"cuda\", dtype=dtype)\n b = torch.randn(k, n, device=\"cuda\", dtype=dtype)\n\n if layout == \"NT\" or layout == \"NN\":\n a = a.as_strided(size=[m, k], stride=[1, m])\n if layout == \"TN\" or layout == \"NN\":\n b = b.as_strided(size=[k, n], stride=[1, k])\n\n with FusionDefinition() as fd:\n matmul_fusion(fd, [a, b])\n\n kwargs = dict(\n _enable_options=[\"fuse_matmul\"], _disable_options=[\"matmul_expr_eval\"]\n )\n\n if not disable_validation:\n eager_output = torch.matmul(a, b)\n fd.validate([a, b], [eager_output], **kwargs)\n\n if not disable_benchmarking:\n run_benchmark(benchmark, lambda *args: fd.execute(*args, **kwargs), [a, b])","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_matmul.row_mem","uri":"program://Fuser/function/benchmarks.python.test_matmul.row_mem#L27-L35","kind":"function","name":"row_mem","path":"benchmarks/python/test_matmul.py","language":"python","start_line":27,"end_line":35,"context_start_line":7,"context_end_line":55,"code":"import torch\n\nimport csv\nimport functools\nimport os\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\ndef load_matmul_problems():\n with open(os.path.join(os.path.dirname(__file__), \"matmul_problems.csv\"), \"r\") as f:\n reader = csv.reader(f)\n next(reader, None) # skip header row\n rows = list((int(m), int(n), int(k), layout) for m, n, k, layout in reader)\n\n def row_mem(row):\n \"\"\"Compute gmem bytes used in a half-precision GEMM\n\n This computes only the space required for operands and output,\n ignoring intermediates like split-K buffers and assuming no bias\n terms.\n \"\"\"\n m, n, k, _ = row\n return ((m + n) * k + m * n) * 2\n\n def three_way_cmp(a, b) -> int:\n \"\"\"Perform a three-way comparison like the Python2 cmp() function\n\n This returns 0 if a == b, -1 if a < b, and 1 if a > b\n \"\"\"\n return int(a > b) - int(a < b)\n\n def mem_cmp(row1, row2):\n \"\"\"Compare two rows based on memory use\"\"\"\n return three_way_cmp(row_mem(row1), row_mem(row2))\n\n # Reverse sort by expected memory use to avoid fragmentation\n rows.sort(key=functools.cmp_to_key(mem_cmp), reverse=True)\n\n return rows\n\n\ndef maybe_skip_oom_case(m: int, n: int, k: int):\n expected_mem = (m * k + n * k + m * n) * 2 # operands plus output","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_matmul.three_way_cmp","uri":"program://Fuser/function/benchmarks.python.test_matmul.three_way_cmp#L37-L42","kind":"function","name":"three_way_cmp","path":"benchmarks/python/test_matmul.py","language":"python","start_line":37,"end_line":42,"context_start_line":17,"context_end_line":62,"code":" out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\ndef load_matmul_problems():\n with open(os.path.join(os.path.dirname(__file__), \"matmul_problems.csv\"), \"r\") as f:\n reader = csv.reader(f)\n next(reader, None) # skip header row\n rows = list((int(m), int(n), int(k), layout) for m, n, k, layout in reader)\n\n def row_mem(row):\n \"\"\"Compute gmem bytes used in a half-precision GEMM\n\n This computes only the space required for operands and output,\n ignoring intermediates like split-K buffers and assuming no bias\n terms.\n \"\"\"\n m, n, k, _ = row\n return ((m + n) * k + m * n) * 2\n\n def three_way_cmp(a, b) -> int:\n \"\"\"Perform a three-way comparison like the Python2 cmp() function\n\n This returns 0 if a == b, -1 if a < b, and 1 if a > b\n \"\"\"\n return int(a > b) - int(a < b)\n\n def mem_cmp(row1, row2):\n \"\"\"Compare two rows based on memory use\"\"\"\n return three_way_cmp(row_mem(row1), row_mem(row2))\n\n # Reverse sort by expected memory use to avoid fragmentation\n rows.sort(key=functools.cmp_to_key(mem_cmp), reverse=True)\n\n return rows\n\n\ndef maybe_skip_oom_case(m: int, n: int, k: int):\n expected_mem = (m * k + n * k + m * n) * 2 # operands plus output\n expected_mem *= 2 # account for multiple runs/deferred frees\n\n _, total = torch.cuda.mem_get_info()\n max_mem = total * 0.9\n if expected_mem > max_mem:\n pytest.skip(\n f\"Case takes more than {max_mem / (2 ** 30): .2f} GiB. Skipping to avoid OOM\"","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_matmul.mem_cmp","uri":"program://Fuser/function/benchmarks.python.test_matmul.mem_cmp#L44-L46","kind":"function","name":"mem_cmp","path":"benchmarks/python/test_matmul.py","language":"python","start_line":44,"end_line":46,"context_start_line":24,"context_end_line":66,"code":" next(reader, None) # skip header row\n rows = list((int(m), int(n), int(k), layout) for m, n, k, layout in reader)\n\n def row_mem(row):\n \"\"\"Compute gmem bytes used in a half-precision GEMM\n\n This computes only the space required for operands and output,\n ignoring intermediates like split-K buffers and assuming no bias\n terms.\n \"\"\"\n m, n, k, _ = row\n return ((m + n) * k + m * n) * 2\n\n def three_way_cmp(a, b) -> int:\n \"\"\"Perform a three-way comparison like the Python2 cmp() function\n\n This returns 0 if a == b, -1 if a < b, and 1 if a > b\n \"\"\"\n return int(a > b) - int(a < b)\n\n def mem_cmp(row1, row2):\n \"\"\"Compare two rows based on memory use\"\"\"\n return three_way_cmp(row_mem(row1), row_mem(row2))\n\n # Reverse sort by expected memory use to avoid fragmentation\n rows.sort(key=functools.cmp_to_key(mem_cmp), reverse=True)\n\n return rows\n\n\ndef maybe_skip_oom_case(m: int, n: int, k: int):\n expected_mem = (m * k + n * k + m * n) * 2 # operands plus output\n expected_mem *= 2 # account for multiple runs/deferred frees\n\n _, total = torch.cuda.mem_get_info()\n max_mem = total * 0.9\n if expected_mem > max_mem:\n pytest.skip(\n f\"Case takes more than {max_mem / (2 ** 30): .2f} GiB. Skipping to avoid OOM\"\n )\n\n\n@pytest.mark.parametrize(\"half_reduction\", [False, True], ids=[\"fullred\", \"halfred\"])","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_fwd","uri":"program://Fuser/module/benchmarks.python.test_layernorm_fwd#L1-L136","kind":"module","name":"benchmarks.python.test_layernorm_fwd","path":"benchmarks/python/test_layernorm_fwd.py","language":"python","start_line":1,"end_line":136,"context_start_line":1,"context_end_line":136,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import layernorm\n\n\ndef layernorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n eps: float = 1e-5,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T2 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n T3, T4 = fd.ops.var_mean(T0, dims=[1], correction=0, keepdim=False)\n\n T7 = fd.ops.broadcast_in_dim(T3, shape=[T0.size(0), 1], broadcast_dims=[0])\n T11 = fd.ops.broadcast_in_dim(T4, shape=[T0.size(0), 1], broadcast_dims=[0])\n\n S12 = fd.define_scalar(eps, dtype=DataType.Double)\n T13 = fd.ops.add(T7, S12)\n T14 = fd.ops.rsqrt(T13)\n\n V17 = T0.shape()\n T18 = fd.ops.broadcast_in_dim(T11, shape=V17, broadcast_dims=[0, 1])\n T19 = fd.ops.sub(T0, T18)\n T23 = fd.ops.broadcast_in_dim(T14, shape=V17, broadcast_dims=[0, 1])\n T24 = fd.ops.mul(T19, T23)\n\n T25 = fd.ops.broadcast_in_dim(T1, shape=V17, broadcast_dims=[1])\n T26 = fd.ops.mul(T24, T25)\n T27 = fd.ops.broadcast_in_dim(T2, shape=V17, broadcast_dims=[1])\n T28 = fd.ops.add(T26, T27)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n\n fd.add_output(T28)\n fd.add_output(T4)\n fd.add_output(T14)\n\n\ndef layernorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation required since nvFuser outputs (out, mean, invstd) differs from baselines (out)\n # Total IO bytes = in_tensor (size, dtype) + weights (size[1], dtype) + bias (size[1], dtype) +\n # mean (size[0], float) + invstd (size[0], float) + outputs (size, dtype)\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_layernorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n batch_size, hidden_size = size\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype),\n ]\n\n with FusionDefinition() as fd:\n layernorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = layernorm(inputs)\n mean = inputs[0].to(torch.float).mean(dim=-1)\n variance = inputs[0].to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n fd.validate(inputs, [eager_output, mean, invstd])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\nimport os\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_layernorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n assert os.environ.get(\"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\") == \"1\"\n assert (\n os.environ.get(\"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\")\n == \"1\"\n )\n batch_size, hidden_size = size\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype, requires_grad=True),\n ]\n\n benchmark_fn = with_executor(executor, layernorm)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n inputs,\n iobytes=layernorm_fwd_iobytes(size, dtype),\n )","source_hash":"16d98d2281151902ad2704739084722367a7b999208795433b6063b23ca567bb","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_fwd.layernorm_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_layernorm_fwd.layernorm_fwd_fusion#L14-L55","kind":"function","name":"layernorm_fwd_fusion","path":"benchmarks/python/test_layernorm_fwd.py","language":"python","start_line":14,"end_line":55,"context_start_line":1,"context_end_line":75,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import layernorm\n\n\ndef layernorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n eps: float = 1e-5,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T2 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n T3, T4 = fd.ops.var_mean(T0, dims=[1], correction=0, keepdim=False)\n\n T7 = fd.ops.broadcast_in_dim(T3, shape=[T0.size(0), 1], broadcast_dims=[0])\n T11 = fd.ops.broadcast_in_dim(T4, shape=[T0.size(0), 1], broadcast_dims=[0])\n\n S12 = fd.define_scalar(eps, dtype=DataType.Double)\n T13 = fd.ops.add(T7, S12)\n T14 = fd.ops.rsqrt(T13)\n\n V17 = T0.shape()\n T18 = fd.ops.broadcast_in_dim(T11, shape=V17, broadcast_dims=[0, 1])\n T19 = fd.ops.sub(T0, T18)\n T23 = fd.ops.broadcast_in_dim(T14, shape=V17, broadcast_dims=[0, 1])\n T24 = fd.ops.mul(T19, T23)\n\n T25 = fd.ops.broadcast_in_dim(T1, shape=V17, broadcast_dims=[1])\n T26 = fd.ops.mul(T24, T25)\n T27 = fd.ops.broadcast_in_dim(T2, shape=V17, broadcast_dims=[1])\n T28 = fd.ops.add(T26, T27)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n\n fd.add_output(T28)\n fd.add_output(T4)\n fd.add_output(T14)\n\n\ndef layernorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation required since nvFuser outputs (out, mean, invstd) differs from baselines (out)\n # Total IO bytes = in_tensor (size, dtype) + weights (size[1], dtype) + bias (size[1], dtype) +\n # mean (size[0], float) + invstd (size[0], float) + outputs (size, dtype)\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_layernorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,","source_hash":"16d98d2281151902ad2704739084722367a7b999208795433b6063b23ca567bb","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_fwd.layernorm_fwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_layernorm_fwd.layernorm_fwd_iobytes#L58-L65","kind":"function","name":"layernorm_fwd_iobytes","path":"benchmarks/python/test_layernorm_fwd.py","language":"python","start_line":58,"end_line":65,"context_start_line":38,"context_end_line":85,"code":"\n V17 = T0.shape()\n T18 = fd.ops.broadcast_in_dim(T11, shape=V17, broadcast_dims=[0, 1])\n T19 = fd.ops.sub(T0, T18)\n T23 = fd.ops.broadcast_in_dim(T14, shape=V17, broadcast_dims=[0, 1])\n T24 = fd.ops.mul(T19, T23)\n\n T25 = fd.ops.broadcast_in_dim(T1, shape=V17, broadcast_dims=[1])\n T26 = fd.ops.mul(T24, T25)\n T27 = fd.ops.broadcast_in_dim(T2, shape=V17, broadcast_dims=[1])\n T28 = fd.ops.add(T26, T27)\n\n if dtype in PROMOTE_DTYPES:\n T28 = fd.ops.cast(T28, dtype=dtype)\n\n fd.add_output(T28)\n fd.add_output(T4)\n fd.add_output(T14)\n\n\ndef layernorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation required since nvFuser outputs (out, mean, invstd) differs from baselines (out)\n # Total IO bytes = in_tensor (size, dtype) + weights (size[1], dtype) + bias (size[1], dtype) +\n # mean (size[0], float) + invstd (size[0], float) + outputs (size, dtype)\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_layernorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n batch_size, hidden_size = size\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype),\n ]\n","source_hash":"16d98d2281151902ad2704739084722367a7b999208795433b6063b23ca567bb","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_fwd.test_layernorm_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_layernorm_fwd.test_layernorm_fwd_nvf_benchmark#L71-L98","kind":"function","name":"test_layernorm_fwd_nvf_benchmark","path":"benchmarks/python/test_layernorm_fwd.py","language":"python","start_line":71,"end_line":98,"context_start_line":51,"context_end_line":118,"code":" T28 = fd.ops.cast(T28, dtype=dtype)\n\n fd.add_output(T28)\n fd.add_output(T4)\n fd.add_output(T14)\n\n\ndef layernorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation required since nvFuser outputs (out, mean, invstd) differs from baselines (out)\n # Total IO bytes = in_tensor (size, dtype) + weights (size[1], dtype) + bias (size[1], dtype) +\n # mean (size[0], float) + invstd (size[0], float) + outputs (size, dtype)\n return int(\n dtype.itemsize * 2 * (np.prod(size) + size[1])\n + torch.float.itemsize * 2 * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_layernorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n batch_size, hidden_size = size\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype),\n ]\n\n with FusionDefinition() as fd:\n layernorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = layernorm(inputs)\n mean = inputs[0].to(torch.float).mean(dim=-1)\n variance = inputs[0].to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n fd.validate(inputs, [eager_output, mean, invstd])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\nimport os\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_layernorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n assert os.environ.get(\"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\") == \"1\"\n assert (\n os.environ.get(\"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\")","source_hash":"16d98d2281151902ad2704739084722367a7b999208795433b6063b23ca567bb","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_layernorm_fwd.test_layernorm_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_layernorm_fwd.test_layernorm_fwd_baseline_benchmark#L108-L136","kind":"function","name":"test_layernorm_fwd_baseline_benchmark","path":"benchmarks/python/test_layernorm_fwd.py","language":"python","start_line":108,"end_line":136,"context_start_line":88,"context_end_line":136,"code":"\n if not disable_validation:\n eager_output = layernorm(inputs)\n mean = inputs[0].to(torch.float).mean(dim=-1)\n variance = inputs[0].to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n fd.validate(inputs, [eager_output, mean, invstd])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\nimport os\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_layernorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n assert os.environ.get(\"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\") == \"1\"\n assert (\n os.environ.get(\"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\")\n == \"1\"\n )\n batch_size, hidden_size = size\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(hidden_size, device=\"cuda\", dtype=dtype, requires_grad=True),\n ]\n\n benchmark_fn = with_executor(executor, layernorm)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n inputs,\n iobytes=layernorm_fwd_iobytes(size, dtype),\n )","source_hash":"16d98d2281151902ad2704739084722367a7b999208795433b6063b23ca567bb","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_bwd","uri":"program://Fuser/module/benchmarks.python.test_rmsnorm_bwd#L1-L150","kind":"module","name":"benchmarks.python.test_rmsnorm_bwd","path":"benchmarks/python/test_rmsnorm_bwd.py","language":"python","start_line":1,"end_line":150,"context_start_line":1,"context_end_line":150,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import rmsnorm\n\n\ndef rmsnorm_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n):\n T4 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T5 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n )\n T6 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T7 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n S0 = fd.define_scalar(2.0, dtype=DataType.Double)\n\n if dtype in PROMOTE_DTYPES:\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n T6 = fd.ops.cast(T6, dtype=DataType.Float)\n T7 = fd.ops.cast(T7, dtype=DataType.Float)\n\n T14 = fd.ops.broadcast_in_dim(T5, shape=T4.shape(), broadcast_dims=[0, 1])\n T15 = fd.ops.reciprocal(T14)\n T16 = fd.ops.mul(T4, T15)\n T20 = fd.ops.broadcast_in_dim(T7, shape=T4.shape(), broadcast_dims=[1])\n\n T23 = fd.ops.mul(T6, T16)\n T24 = fd.ops.mul(T6, T20)\n T25 = fd.ops.sum(T23, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T28 = fd.ops.mul(T24, T15)\n T29 = fd.ops.neg(T24)\n T30 = fd.ops.mul(T29, T4)\n T32 = fd.ops.pow(T14, S0)\n T33 = fd.ops.reciprocal(T32)\n T34 = fd.ops.mul(T30, T33)\n T35 = fd.ops.sum(T34, dims=[1], keepdim=False, dtype=DataType.Null)\n T41 = fd.ops.broadcast_in_dim(T35, shape=[T4.size(0), 1], broadcast_dims=[0])\n T43 = fd.ops.mul(S0, T5)\n T44 = fd.ops.reciprocal(T43)\n T45 = fd.ops.mul(T41, T44)\n S48 = fd.ops.reciprocal(T4.size(1))\n T49 = fd.ops.mul(T45, S48)\n T50 = fd.ops.sum(T49, dims=[1], keepdim=False, dtype=DataType.Null)\n T54 = fd.ops.broadcast_in_dim(T50, shape=[T4.size(0), 1], broadcast_dims=[0])\n T58 = fd.ops.broadcast_in_dim(T54, shape=T4.shape(), broadcast_dims=[0, 1])\n T59 = fd.ops.mul(T58, S0)\n T62 = fd.ops.mul(T59, T4)\n T63 = fd.ops.add(T28, T62)\n\n if dtype in PROMOTE_DTYPES:\n T63 = fd.ops.cast(T63, dtype=dtype)\n T25 = fd.ops.cast(T25, dtype=dtype)\n\n fd.add_output(T63)\n fd.add_output(T25)\n\n\ndef rmsnorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, rms, weigts, grad_in, grad_weights) differ from baselines (out, grad_out)\n # Total IO bytes = in_tensor (size, dtype) + grad_out (size, dtype) + rms_eps(size[0], float) + weights (size[1], dtype) +\n # grad_in (size, dtype) + grad_weights (size[1], dtype)\n return int(\n dtype.itemsize * (3 * np.prod(size) + 2 * size[1])\n + torch.float.itemsize * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_rmsnorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n squared_mean = (inputs.to(torch.float) ** 2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + eps)\n\n with FusionDefinition() as fd:\n rmsnorm_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = weights.to(torch.double) * (\n inputs.to(torch.double) / rms_eps.to(torch.double)\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate([inputs, rms_eps, grads, weights], [inputs.grad, weights.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, rms_eps, grads, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_rmsnorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, rmsnorm)\n fwd_inputs = [inputs, weights]\n outputs = fwd_fn(fwd_inputs)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=rmsnorm_bwd_iobytes(size, dtype),\n )","source_hash":"9b5b9f03f4538fac447609a4e1852e9fe34c5ec2bbc65a10cbeb7d396c839110","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_bwd.rmsnorm_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_bwd.rmsnorm_bwd_fusion#L20-L76","kind":"function","name":"rmsnorm_bwd_fusion","path":"benchmarks/python/test_rmsnorm_bwd.py","language":"python","start_line":20,"end_line":76,"context_start_line":1,"context_end_line":96,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import rmsnorm\n\n\ndef rmsnorm_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n):\n T4 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T5 = fd.define_tensor(\n shape=[-1, 1], contiguity=[True, None], dtype=DataType.Float, is_cpu=False\n )\n T6 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T7 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n S0 = fd.define_scalar(2.0, dtype=DataType.Double)\n\n if dtype in PROMOTE_DTYPES:\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n T6 = fd.ops.cast(T6, dtype=DataType.Float)\n T7 = fd.ops.cast(T7, dtype=DataType.Float)\n\n T14 = fd.ops.broadcast_in_dim(T5, shape=T4.shape(), broadcast_dims=[0, 1])\n T15 = fd.ops.reciprocal(T14)\n T16 = fd.ops.mul(T4, T15)\n T20 = fd.ops.broadcast_in_dim(T7, shape=T4.shape(), broadcast_dims=[1])\n\n T23 = fd.ops.mul(T6, T16)\n T24 = fd.ops.mul(T6, T20)\n T25 = fd.ops.sum(T23, dims=[0], keepdim=False, dtype=DataType.Null)\n\n T28 = fd.ops.mul(T24, T15)\n T29 = fd.ops.neg(T24)\n T30 = fd.ops.mul(T29, T4)\n T32 = fd.ops.pow(T14, S0)\n T33 = fd.ops.reciprocal(T32)\n T34 = fd.ops.mul(T30, T33)\n T35 = fd.ops.sum(T34, dims=[1], keepdim=False, dtype=DataType.Null)\n T41 = fd.ops.broadcast_in_dim(T35, shape=[T4.size(0), 1], broadcast_dims=[0])\n T43 = fd.ops.mul(S0, T5)\n T44 = fd.ops.reciprocal(T43)\n T45 = fd.ops.mul(T41, T44)\n S48 = fd.ops.reciprocal(T4.size(1))\n T49 = fd.ops.mul(T45, S48)\n T50 = fd.ops.sum(T49, dims=[1], keepdim=False, dtype=DataType.Null)\n T54 = fd.ops.broadcast_in_dim(T50, shape=[T4.size(0), 1], broadcast_dims=[0])\n T58 = fd.ops.broadcast_in_dim(T54, shape=T4.shape(), broadcast_dims=[0, 1])\n T59 = fd.ops.mul(T58, S0)\n T62 = fd.ops.mul(T59, T4)\n T63 = fd.ops.add(T28, T62)\n\n if dtype in PROMOTE_DTYPES:\n T63 = fd.ops.cast(T63, dtype=dtype)\n T25 = fd.ops.cast(T25, dtype=dtype)\n\n fd.add_output(T63)\n fd.add_output(T25)\n\n\ndef rmsnorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, rms, weigts, grad_in, grad_weights) differ from baselines (out, grad_out)\n # Total IO bytes = in_tensor (size, dtype) + grad_out (size, dtype) + rms_eps(size[0], float) + weights (size[1], dtype) +\n # grad_in (size, dtype) + grad_weights (size[1], dtype)\n return int(\n dtype.itemsize * (3 * np.prod(size) + 2 * size[1])\n + torch.float.itemsize * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_rmsnorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,","source_hash":"9b5b9f03f4538fac447609a4e1852e9fe34c5ec2bbc65a10cbeb7d396c839110","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_bwd.rmsnorm_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_bwd.rmsnorm_bwd_iobytes#L79-L86","kind":"function","name":"rmsnorm_bwd_iobytes","path":"benchmarks/python/test_rmsnorm_bwd.py","language":"python","start_line":79,"end_line":86,"context_start_line":59,"context_end_line":106,"code":" T43 = fd.ops.mul(S0, T5)\n T44 = fd.ops.reciprocal(T43)\n T45 = fd.ops.mul(T41, T44)\n S48 = fd.ops.reciprocal(T4.size(1))\n T49 = fd.ops.mul(T45, S48)\n T50 = fd.ops.sum(T49, dims=[1], keepdim=False, dtype=DataType.Null)\n T54 = fd.ops.broadcast_in_dim(T50, shape=[T4.size(0), 1], broadcast_dims=[0])\n T58 = fd.ops.broadcast_in_dim(T54, shape=T4.shape(), broadcast_dims=[0, 1])\n T59 = fd.ops.mul(T58, S0)\n T62 = fd.ops.mul(T59, T4)\n T63 = fd.ops.add(T28, T62)\n\n if dtype in PROMOTE_DTYPES:\n T63 = fd.ops.cast(T63, dtype=dtype)\n T25 = fd.ops.cast(T25, dtype=dtype)\n\n fd.add_output(T63)\n fd.add_output(T25)\n\n\ndef rmsnorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, rms, weigts, grad_in, grad_weights) differ from baselines (out, grad_out)\n # Total IO bytes = in_tensor (size, dtype) + grad_out (size, dtype) + rms_eps(size[0], float) + weights (size[1], dtype) +\n # grad_in (size, dtype) + grad_weights (size[1], dtype)\n return int(\n dtype.itemsize * (3 * np.prod(size) + 2 * size[1])\n + torch.float.itemsize * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_rmsnorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n squared_mean = (inputs.to(torch.float) ** 2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + eps)","source_hash":"9b5b9f03f4538fac447609a4e1852e9fe34c5ec2bbc65a10cbeb7d396c839110","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_bwd.test_rmsnorm_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_bwd.test_rmsnorm_bwd_nvf_benchmark#L93-L119","kind":"function","name":"test_rmsnorm_bwd_nvf_benchmark","path":"benchmarks/python/test_rmsnorm_bwd.py","language":"python","start_line":93,"end_line":119,"context_start_line":73,"context_end_line":139,"code":" T25 = fd.ops.cast(T25, dtype=dtype)\n\n fd.add_output(T63)\n fd.add_output(T25)\n\n\ndef rmsnorm_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOBytes computation since nvfuser input/outputs (in_tensor, grad_out, rms, weigts, grad_in, grad_weights) differ from baselines (out, grad_out)\n # Total IO bytes = in_tensor (size, dtype) + grad_out (size, dtype) + rms_eps(size[0], float) + weights (size[1], dtype) +\n # grad_in (size, dtype) + grad_weights (size[1], dtype)\n return int(\n dtype.itemsize * (3 * np.prod(size) + 2 * size[1])\n + torch.float.itemsize * size[0]\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_rmsnorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n squared_mean = (inputs.to(torch.float) ** 2).mean(1, keepdim=True)\n rms_eps = torch.sqrt(squared_mean + eps)\n\n with FusionDefinition() as fd:\n rmsnorm_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = weights.to(torch.double) * (\n inputs.to(torch.double) / rms_eps.to(torch.double)\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate([inputs, rms_eps, grads, weights], [inputs.grad, weights.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, rms_eps, grads, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_rmsnorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n # Compile the fwd fn for torchcompile","source_hash":"9b5b9f03f4538fac447609a4e1852e9fe34c5ec2bbc65a10cbeb7d396c839110","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_rmsnorm_bwd.test_rmsnorm_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_rmsnorm_bwd.test_rmsnorm_bwd_baseline_benchmark#L127-L150","kind":"function","name":"test_rmsnorm_bwd_baseline_benchmark","path":"benchmarks/python/test_rmsnorm_bwd.py","language":"python","start_line":127,"end_line":150,"context_start_line":107,"context_end_line":150,"code":"\n with FusionDefinition() as fd:\n rmsnorm_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype))\n\n if not disable_validation:\n eager_output = weights.to(torch.double) * (\n inputs.to(torch.double) / rms_eps.to(torch.double)\n )\n eager_output.backward(grads.to(torch.double))\n fd.validate([inputs, rms_eps, grads, weights], [inputs.grad, weights.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [inputs, rms_eps, grads, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_outer_persistent\n@pytest.mark.inner_persistent\ndef test_rmsnorm_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n inputs = torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True)\n grads = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype, requires_grad=True)\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, rmsnorm)\n fwd_inputs = [inputs, weights]\n outputs = fwd_fn(fwd_inputs)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=rmsnorm_bwd_iobytes(size, dtype),\n )","source_hash":"9b5b9f03f4538fac447609a4e1852e9fe34c5ec2bbc65a10cbeb7d396c839110","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_instancenorm_fwd","uri":"program://Fuser/module/benchmarks.python.test_instancenorm_fwd#L1-L53","kind":"module","name":"benchmarks.python.test_instancenorm_fwd","path":"benchmarks/python/test_instancenorm_fwd.py","language":"python","start_line":1,"end_line":53,"context_start_line":1,"context_end_line":53,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_fwd_nvf_benchmark, norm_fwd_baseline_benchmark\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n norm_fwd_nvf_benchmark(\n benchmark,\n size,\n dtype,\n \"instance_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n )\n\n\n@pytest.mark.parametrize(\"executor\", [\"eager\", \"torchcompile\"])\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_fwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_fwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"instance_norm\"\n )","source_hash":"1c1e8df938b7bfc631d76cdbcec5a4e1a62ae43a53faae1e605ae84c9264ad17","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_instancenorm_fwd.test_instancenorm_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_instancenorm_fwd.test_instancenorm_fwd_nvf_benchmark#L19-L35","kind":"function","name":"test_instancenorm_fwd_nvf_benchmark","path":"benchmarks/python/test_instancenorm_fwd.py","language":"python","start_line":19,"end_line":35,"context_start_line":1,"context_end_line":53,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_fwd_nvf_benchmark, norm_fwd_baseline_benchmark\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n channels_last: bool,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n norm_fwd_nvf_benchmark(\n benchmark,\n size,\n dtype,\n \"instance_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n )\n\n\n@pytest.mark.parametrize(\"executor\", [\"eager\", \"torchcompile\"])\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_fwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_fwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"instance_norm\"\n )","source_hash":"1c1e8df938b7bfc631d76cdbcec5a4e1a62ae43a53faae1e605ae84c9264ad17","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_instancenorm_fwd.test_instancenorm_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_instancenorm_fwd.test_instancenorm_fwd_baseline_benchmark#L48-L53","kind":"function","name":"test_instancenorm_fwd_baseline_benchmark","path":"benchmarks/python/test_instancenorm_fwd.py","language":"python","start_line":48,"end_line":53,"context_start_line":28,"context_end_line":53,"code":" benchmark,\n size,\n dtype,\n \"instance_norm\",\n channels_last,\n disable_validation,\n disable_benchmarking,\n )\n\n\n@pytest.mark.parametrize(\"executor\", [\"eager\", \"torchcompile\"])\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_fwd_baseline_benchmark(\n benchmark, size: tuple, dtype: torch.dtype, channels_last: bool, executor: str\n):\n norm_fwd_baseline_benchmark(\n benchmark, size, dtype, channels_last, executor, \"instance_norm\"\n )","source_hash":"1c1e8df938b7bfc631d76cdbcec5a4e1a62ae43a53faae1e605ae84c9264ad17","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_fwd","uri":"program://Fuser/module/benchmarks.python.test_dropout_layernorm_fwd#L1-L185","kind":"module","name":"benchmarks.python.test_dropout_layernorm_fwd","path":"benchmarks/python/test_dropout_layernorm_fwd.py","language":"python","start_line":1,"end_line":185,"context_start_line":1,"context_end_line":185,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_layernorm\n\n\ndef dropout_layernorm_fwd_fusion(\n fd: FusionDefinition, dtype: DataType, dropout_p: float, eps: float = 1e-5\n) -> None:\n \"\"\"\n Forward pass fusion definition for computing:\n output = layernorm (input2 + dropout (input1, p=dropout_p))\n\n Fusion inputs: input1, input2, weights, bias\n Fusion outputs: output, mean, invstd, dropout_mask\n \"\"\"\n T2 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T0 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n S3 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S4 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T8 = fd.ops.uniform(S3, S4, shape=T2.shape(), dtype=DataType.Float)\n S9 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T10 = fd.ops.lt(T8, S9)\n T11 = fd.ops.cast(T10, dtype=DataType.Float)\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n T3 = fd.ops.cast(T3, dtype=DataType.Float)\n\n # Dropout + Add\n T13 = fd.ops.mul(T2, T11)\n S14 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T15 = fd.ops.mul(T13, S14)\n T16 = fd.ops.add(T3, T15)\n # Layernorm\n T17, T18 = fd.ops.var_mean(T16, dims=[1], correction=0, keepdim=False)\n T22 = fd.ops.broadcast_in_dim(T17, shape=[T2.size(0), 1], broadcast_dims=[0])\n T26 = fd.ops.broadcast_in_dim(T18, shape=[T2.size(0), 1], broadcast_dims=[0])\n S27 = fd.define_scalar(eps, dtype=DataType.Double)\n T28 = fd.ops.add(T22, S27)\n T29 = fd.ops.rsqrt(T28)\n T33 = fd.ops.broadcast_in_dim(T26, shape=T2.shape(), broadcast_dims=[0, 1])\n T34 = fd.ops.sub(T16, T33)\n T38 = fd.ops.broadcast_in_dim(T29, shape=T2.shape(), broadcast_dims=[0, 1])\n T39 = fd.ops.mul(T34, T38)\n T43 = fd.ops.broadcast_in_dim(T1, shape=T2.shape(), broadcast_dims=[1])\n T45 = fd.ops.mul(T39, T43)\n T49 = fd.ops.broadcast_in_dim(T0, shape=T2.shape(), broadcast_dims=[1])\n T51 = fd.ops.add(T45, T49)\n if dtype in PROMOTE_DTYPES:\n T51 = fd.ops.cast(T51, dtype=dtype)\n\n fd.add_output(T51)\n fd.add_output(T18)\n fd.add_output(T29)\n fd.add_output(T10)\n\n\ndef dropout_layernorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs differ from baseline outputs (output).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"bias\": (size[1], dtype),\n # Outputs\n \"mean\": (size[0], torch.float),\n \"invstd\": (size[0], torch.float),\n \"outputs\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_layernorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype),\n torch.randn(size, device=\"cuda\", dtype=dtype),\n torch.ones(size[1], device=\"cuda\", dtype=dtype),\n torch.zeros(size[1], device=\"cuda\", dtype=dtype),\n ]\n\n dropout_p = 0.2\n with FusionDefinition() as fd:\n dropout_layernorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p)\n\n if not disable_validation:\n # For validating use a fusion definition with dropout_p=0.0\n with FusionDefinition() as val_fd:\n dropout_layernorm_fwd_fusion(\n val_fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p=0.0, eps=eps\n )\n\n dropout_mask = torch.ones(size, dtype=torch.bool, device=\"cuda\")\n\n # dropout + add\n x = inputs[1] + torch.nn.functional.dropout(inputs[0], p=0.0)\n # layernorm\n eager_output = torch.nn.functional.layer_norm(\n x.to(torch.float),\n inputs[0].shape[1:],\n weight=inputs[2].to(torch.float),\n bias=inputs[3].to(torch.float),\n )\n\n # mean and invstd are computed for the output of dropout + add\n mean = x.to(torch.double).mean(dim=-1)\n variance = x.to(torch.double).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n val_fd.validate(\n inputs,\n [\n eager_output.to(dtype),\n mean.to(torch.float),\n invstd.to(torch.float),\n dropout_mask,\n ],\n )\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_layernorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n dropout_p = 0.2\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.ones(size[1], device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.zeros(size[1], device=\"cuda\", dtype=dtype, requires_grad=True),\n dropout_p,\n ]\n\n benchmark_fn = with_executor(executor, dropout_layernorm)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n inputs,\n iobytes=dropout_layernorm_fwd_iobytes(size, dtype),\n )","source_hash":"27232ca209c015e59ba429b1a6426cf464c9a9435d8cc855416eba424d08f1db","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_fwd.dropout_layernorm_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_dropout_layernorm_fwd.dropout_layernorm_fwd_fusion#L19-L75","kind":"function","name":"dropout_layernorm_fwd_fusion","path":"benchmarks/python/test_dropout_layernorm_fwd.py","language":"python","start_line":19,"end_line":75,"context_start_line":1,"context_end_line":95,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_layernorm\n\n\ndef dropout_layernorm_fwd_fusion(\n fd: FusionDefinition, dtype: DataType, dropout_p: float, eps: float = 1e-5\n) -> None:\n \"\"\"\n Forward pass fusion definition for computing:\n output = layernorm (input2 + dropout (input1, p=dropout_p))\n\n Fusion inputs: input1, input2, weights, bias\n Fusion outputs: output, mean, invstd, dropout_mask\n \"\"\"\n T2 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T3 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T0 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n S3 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S4 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T8 = fd.ops.uniform(S3, S4, shape=T2.shape(), dtype=DataType.Float)\n S9 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T10 = fd.ops.lt(T8, S9)\n T11 = fd.ops.cast(T10, dtype=DataType.Float)\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n T3 = fd.ops.cast(T3, dtype=DataType.Float)\n\n # Dropout + Add\n T13 = fd.ops.mul(T2, T11)\n S14 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T15 = fd.ops.mul(T13, S14)\n T16 = fd.ops.add(T3, T15)\n # Layernorm\n T17, T18 = fd.ops.var_mean(T16, dims=[1], correction=0, keepdim=False)\n T22 = fd.ops.broadcast_in_dim(T17, shape=[T2.size(0), 1], broadcast_dims=[0])\n T26 = fd.ops.broadcast_in_dim(T18, shape=[T2.size(0), 1], broadcast_dims=[0])\n S27 = fd.define_scalar(eps, dtype=DataType.Double)\n T28 = fd.ops.add(T22, S27)\n T29 = fd.ops.rsqrt(T28)\n T33 = fd.ops.broadcast_in_dim(T26, shape=T2.shape(), broadcast_dims=[0, 1])\n T34 = fd.ops.sub(T16, T33)\n T38 = fd.ops.broadcast_in_dim(T29, shape=T2.shape(), broadcast_dims=[0, 1])\n T39 = fd.ops.mul(T34, T38)\n T43 = fd.ops.broadcast_in_dim(T1, shape=T2.shape(), broadcast_dims=[1])\n T45 = fd.ops.mul(T39, T43)\n T49 = fd.ops.broadcast_in_dim(T0, shape=T2.shape(), broadcast_dims=[1])\n T51 = fd.ops.add(T45, T49)\n if dtype in PROMOTE_DTYPES:\n T51 = fd.ops.cast(T51, dtype=dtype)\n\n fd.add_output(T51)\n fd.add_output(T18)\n fd.add_output(T29)\n fd.add_output(T10)\n\n\ndef dropout_layernorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs differ from baseline outputs (output).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"bias\": (size[1], dtype),\n # Outputs\n \"mean\": (size[0], torch.float),\n \"invstd\": (size[0], torch.float),\n \"outputs\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))","source_hash":"27232ca209c015e59ba429b1a6426cf464c9a9435d8cc855416eba424d08f1db","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_fwd.dropout_layernorm_fwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_dropout_layernorm_fwd.dropout_layernorm_fwd_iobytes#L78-L92","kind":"function","name":"dropout_layernorm_fwd_iobytes","path":"benchmarks/python/test_dropout_layernorm_fwd.py","language":"python","start_line":78,"end_line":92,"context_start_line":58,"context_end_line":112,"code":" S27 = fd.define_scalar(eps, dtype=DataType.Double)\n T28 = fd.ops.add(T22, S27)\n T29 = fd.ops.rsqrt(T28)\n T33 = fd.ops.broadcast_in_dim(T26, shape=T2.shape(), broadcast_dims=[0, 1])\n T34 = fd.ops.sub(T16, T33)\n T38 = fd.ops.broadcast_in_dim(T29, shape=T2.shape(), broadcast_dims=[0, 1])\n T39 = fd.ops.mul(T34, T38)\n T43 = fd.ops.broadcast_in_dim(T1, shape=T2.shape(), broadcast_dims=[1])\n T45 = fd.ops.mul(T39, T43)\n T49 = fd.ops.broadcast_in_dim(T0, shape=T2.shape(), broadcast_dims=[1])\n T51 = fd.ops.add(T45, T49)\n if dtype in PROMOTE_DTYPES:\n T51 = fd.ops.cast(T51, dtype=dtype)\n\n fd.add_output(T51)\n fd.add_output(T18)\n fd.add_output(T29)\n fd.add_output(T10)\n\n\ndef dropout_layernorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs differ from baseline outputs (output).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"bias\": (size[1], dtype),\n # Outputs\n \"mean\": (size[0], torch.float),\n \"invstd\": (size[0], torch.float),\n \"outputs\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_layernorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype),\n torch.randn(size, device=\"cuda\", dtype=dtype),\n torch.ones(size[1], device=\"cuda\", dtype=dtype),\n torch.zeros(size[1], device=\"cuda\", dtype=dtype),\n ]\n","source_hash":"27232ca209c015e59ba429b1a6426cf464c9a9435d8cc855416eba424d08f1db","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_fwd.test_dropout_layernorm_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_dropout_layernorm_fwd.test_dropout_layernorm_fwd_nvf_benchmark#L98-L152","kind":"function","name":"test_dropout_layernorm_fwd_nvf_benchmark","path":"benchmarks/python/test_dropout_layernorm_fwd.py","language":"python","start_line":98,"end_line":152,"context_start_line":78,"context_end_line":172,"code":"def dropout_layernorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser outputs differ from baseline outputs (output).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n \"bias\": (size[1], dtype),\n # Outputs\n \"mean\": (size[0], torch.float),\n \"invstd\": (size[0], torch.float),\n \"outputs\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_layernorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype),\n torch.randn(size, device=\"cuda\", dtype=dtype),\n torch.ones(size[1], device=\"cuda\", dtype=dtype),\n torch.zeros(size[1], device=\"cuda\", dtype=dtype),\n ]\n\n dropout_p = 0.2\n with FusionDefinition() as fd:\n dropout_layernorm_fwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p)\n\n if not disable_validation:\n # For validating use a fusion definition with dropout_p=0.0\n with FusionDefinition() as val_fd:\n dropout_layernorm_fwd_fusion(\n val_fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p=0.0, eps=eps\n )\n\n dropout_mask = torch.ones(size, dtype=torch.bool, device=\"cuda\")\n\n # dropout + add\n x = inputs[1] + torch.nn.functional.dropout(inputs[0], p=0.0)\n # layernorm\n eager_output = torch.nn.functional.layer_norm(\n x.to(torch.float),\n inputs[0].shape[1:],\n weight=inputs[2].to(torch.float),\n bias=inputs[3].to(torch.float),\n )\n\n # mean and invstd are computed for the output of dropout + add\n mean = x.to(torch.double).mean(dim=-1)\n variance = x.to(torch.double).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n val_fd.validate(\n inputs,\n [\n eager_output.to(dtype),\n mean.to(torch.float),\n invstd.to(torch.float),\n dropout_mask,\n ],\n )\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_layernorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n dropout_p = 0.2\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.ones(size[1], device=\"cuda\", dtype=dtype, requires_grad=True),","source_hash":"27232ca209c015e59ba429b1a6426cf464c9a9435d8cc855416eba424d08f1db","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_layernorm_fwd.test_dropout_layernorm_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_dropout_layernorm_fwd.test_dropout_layernorm_fwd_baseline_benchmark#L159-L185","kind":"function","name":"test_dropout_layernorm_fwd_baseline_benchmark","path":"benchmarks/python/test_dropout_layernorm_fwd.py","language":"python","start_line":159,"end_line":185,"context_start_line":139,"context_end_line":185,"code":" invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(1)\n\n val_fd.validate(\n inputs,\n [\n eager_output.to(dtype),\n mean.to(torch.float),\n invstd.to(torch.float),\n dropout_mask,\n ],\n )\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_layernorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n\n dropout_p = 0.2\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.ones(size[1], device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.zeros(size[1], device=\"cuda\", dtype=dtype, requires_grad=True),\n dropout_p,\n ]\n\n benchmark_fn = with_executor(executor, dropout_layernorm)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n inputs,\n iobytes=dropout_layernorm_fwd_iobytes(size, dtype),\n )","source_hash":"27232ca209c015e59ba429b1a6426cf464c9a9435d8cc855416eba424d08f1db","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_bwd","uri":"program://Fuser/module/benchmarks.python.test_nanogpt_attn_bwd#L1-L170","kind":"module","name":"benchmarks.python.test_nanogpt_attn_bwd","path":"benchmarks/python/test_nanogpt_attn_bwd.py","language":"python","start_line":1,"end_line":170,"context_start_line":1,"context_end_line":170,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import nanogpt_attn\n\n\n# Fusion from nanogpt attention module\n# The nvFuser defintion only includes the non-matmul computation (masked_fill + softmax + dropout)\ndef nanogpt_attn_bwd_fusion(\n fd: FusionDefinition, dtype: DataType, head_size: int, dropout_p: float\n):\n S0 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n S1 = fd.define_scalar(1 / head_size**0.5, dtype=DataType.Double)\n\n T2 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T3 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T4 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n )\n T5 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n T3 = fd.ops.cast(T3, dtype=DataType.Float)\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n\n T7 = fd.ops.mul(T2, S0)\n T8 = fd.ops.mul(T7, T4)\n T9 = fd.ops.mul(T3, T8)\n T10 = fd.ops.sum(T9, dims=[3], keepdim=False, dtype=DataType.Null)\n\n T16 = fd.ops.broadcast_in_dim(\n T10, shape=[T2.size(0), T2.size(1), T2.size(2), 1], broadcast_dims=[0, 1, 2]\n )\n\n V21 = T2.shape()\n T22 = fd.ops.broadcast_in_dim(T16, shape=V21, broadcast_dims=[0, 1, 2, 3])\n\n T23 = fd.ops.sub(T8, T22)\n T24 = fd.ops.mul(T3, T23)\n S25 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T26 = fd.ops.where(T5, S25, T24)\n T27 = fd.ops.mul(T26, S1)\n\n if dtype in PROMOTE_DTYPES:\n T27 = fd.ops.cast(T27, dtype=dtype)\n\n fd.add_output(T27)\n\n\ndef nanogpt_attn_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs (grad_out, attn, dropout_mask, bias_mask, grad_input]) differ from baseline input/outputs (output, grad_output).\n\n # Total IO bytes = grad_out ([bs, nh, seq_len, seq_len], dtype) + attn ([bs, nh, seq_len, seq_len], dtype) +\n # dropout_mask ([bs, nh, seq_len, seq_len], bool) + bias_mask ([bs, nh, seq_len, seq_len], bool) + grad_in ([bs, nh, seq_len, seq_len], dtype)\n bs, seq_len, nh, n_embd = size\n\n return int(\n bs * nh * seq_len * seq_len * (3 * dtype.itemsize + 2 * torch.bool.itemsize)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len\n )\n dropout_mask = torch.lt(\n torch.rand(batch_size, nh, seq_len, seq_len, device=\"cuda\"), 1 - dropout_p\n )\n bias_mask = bias[:, :, :seq_len, :seq_len] == 0\n bias_mask = bias_mask.broadcast_to(batch_size, nh, seq_len, seq_len)\n grads = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n attn = inputs / (hs**0.5)\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = torch.nn.functional.softmax(attn, dim=-1)\n\n with FusionDefinition() as fd:\n nanogpt_attn_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), hs, dropout_p)\n\n if not disable_validation:\n # Use dropout_mask instead of torch.nn.functional.dropout for validating results.\n out = attn * dropout_mask * 1 / (1 - dropout_p)\n out.backward(grads)\n fd.validate([grads, attn, dropout_mask, bias_mask], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [grads, attn, dropout_mask, bias_mask])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len\n )\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, nanogpt_attn)\n fwd_inputs = [inputs, bias, size, dropout_p]\n outputs = fwd_fn(fwd_inputs)\n\n grads = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=nanogpt_attn_bwd_iobytes(size, dtype),\n )","source_hash":"a882e8f9374530c6adba1bb7d73c5a932ff4b7de456f4eb28872674910a50f7f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_bwd.nanogpt_attn_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_nanogpt_attn_bwd.nanogpt_attn_bwd_fusion#L21-L78","kind":"function","name":"nanogpt_attn_bwd_fusion","path":"benchmarks/python/test_nanogpt_attn_bwd.py","language":"python","start_line":21,"end_line":78,"context_start_line":1,"context_end_line":98,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import nanogpt_attn\n\n\n# Fusion from nanogpt attention module\n# The nvFuser defintion only includes the non-matmul computation (masked_fill + softmax + dropout)\ndef nanogpt_attn_bwd_fusion(\n fd: FusionDefinition, dtype: DataType, head_size: int, dropout_p: float\n):\n S0 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n S1 = fd.define_scalar(1 / head_size**0.5, dtype=DataType.Double)\n\n T2 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T3 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,\n is_cpu=False,\n )\n T4 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n )\n T5 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[None, None, True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n T3 = fd.ops.cast(T3, dtype=DataType.Float)\n T4 = fd.ops.cast(T4, dtype=DataType.Float)\n\n T7 = fd.ops.mul(T2, S0)\n T8 = fd.ops.mul(T7, T4)\n T9 = fd.ops.mul(T3, T8)\n T10 = fd.ops.sum(T9, dims=[3], keepdim=False, dtype=DataType.Null)\n\n T16 = fd.ops.broadcast_in_dim(\n T10, shape=[T2.size(0), T2.size(1), T2.size(2), 1], broadcast_dims=[0, 1, 2]\n )\n\n V21 = T2.shape()\n T22 = fd.ops.broadcast_in_dim(T16, shape=V21, broadcast_dims=[0, 1, 2, 3])\n\n T23 = fd.ops.sub(T8, T22)\n T24 = fd.ops.mul(T3, T23)\n S25 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T26 = fd.ops.where(T5, S25, T24)\n T27 = fd.ops.mul(T26, S1)\n\n if dtype in PROMOTE_DTYPES:\n T27 = fd.ops.cast(T27, dtype=dtype)\n\n fd.add_output(T27)\n\n\ndef nanogpt_attn_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs (grad_out, attn, dropout_mask, bias_mask, grad_input]) differ from baseline input/outputs (output, grad_output).\n\n # Total IO bytes = grad_out ([bs, nh, seq_len, seq_len], dtype) + attn ([bs, nh, seq_len, seq_len], dtype) +\n # dropout_mask ([bs, nh, seq_len, seq_len], bool) + bias_mask ([bs, nh, seq_len, seq_len], bool) + grad_in ([bs, nh, seq_len, seq_len], dtype)\n bs, seq_len, nh, n_embd = size\n\n return int(\n bs * nh * seq_len * seq_len * (3 * dtype.itemsize + 2 * torch.bool.itemsize)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_bwd_nvf_benchmark(\n benchmark,\n size: tuple,","source_hash":"a882e8f9374530c6adba1bb7d73c5a932ff4b7de456f4eb28872674910a50f7f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_bwd.nanogpt_attn_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_nanogpt_attn_bwd.nanogpt_attn_bwd_iobytes#L81-L90","kind":"function","name":"nanogpt_attn_bwd_iobytes","path":"benchmarks/python/test_nanogpt_attn_bwd.py","language":"python","start_line":81,"end_line":90,"context_start_line":61,"context_end_line":110,"code":"\n T16 = fd.ops.broadcast_in_dim(\n T10, shape=[T2.size(0), T2.size(1), T2.size(2), 1], broadcast_dims=[0, 1, 2]\n )\n\n V21 = T2.shape()\n T22 = fd.ops.broadcast_in_dim(T16, shape=V21, broadcast_dims=[0, 1, 2, 3])\n\n T23 = fd.ops.sub(T8, T22)\n T24 = fd.ops.mul(T3, T23)\n S25 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T26 = fd.ops.where(T5, S25, T24)\n T27 = fd.ops.mul(T26, S1)\n\n if dtype in PROMOTE_DTYPES:\n T27 = fd.ops.cast(T27, dtype=dtype)\n\n fd.add_output(T27)\n\n\ndef nanogpt_attn_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs (grad_out, attn, dropout_mask, bias_mask, grad_input]) differ from baseline input/outputs (output, grad_output).\n\n # Total IO bytes = grad_out ([bs, nh, seq_len, seq_len], dtype) + attn ([bs, nh, seq_len, seq_len], dtype) +\n # dropout_mask ([bs, nh, seq_len, seq_len], bool) + bias_mask ([bs, nh, seq_len, seq_len], bool) + grad_in ([bs, nh, seq_len, seq_len], dtype)\n bs, seq_len, nh, n_embd = size\n\n return int(\n bs * nh * seq_len * seq_len * (3 * dtype.itemsize + 2 * torch.bool.itemsize)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len","source_hash":"a882e8f9374530c6adba1bb7d73c5a932ff4b7de456f4eb28872674910a50f7f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_bwd.test_nanogpt_attn_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_nanogpt_attn_bwd.test_nanogpt_attn_bwd_nvf_benchmark#L96-L133","kind":"function","name":"test_nanogpt_attn_bwd_nvf_benchmark","path":"benchmarks/python/test_nanogpt_attn_bwd.py","language":"python","start_line":96,"end_line":133,"context_start_line":76,"context_end_line":153,"code":" T27 = fd.ops.cast(T27, dtype=dtype)\n\n fd.add_output(T27)\n\n\ndef nanogpt_attn_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs (grad_out, attn, dropout_mask, bias_mask, grad_input]) differ from baseline input/outputs (output, grad_output).\n\n # Total IO bytes = grad_out ([bs, nh, seq_len, seq_len], dtype) + attn ([bs, nh, seq_len, seq_len], dtype) +\n # dropout_mask ([bs, nh, seq_len, seq_len], bool) + bias_mask ([bs, nh, seq_len, seq_len], bool) + grad_in ([bs, nh, seq_len, seq_len], dtype)\n bs, seq_len, nh, n_embd = size\n\n return int(\n bs * nh * seq_len * seq_len * (3 * dtype.itemsize + 2 * torch.bool.itemsize)\n )\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n hs = n_embd // nh\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len\n )\n dropout_mask = torch.lt(\n torch.rand(batch_size, nh, seq_len, seq_len, device=\"cuda\"), 1 - dropout_p\n )\n bias_mask = bias[:, :, :seq_len, :seq_len] == 0\n bias_mask = bias_mask.broadcast_to(batch_size, nh, seq_len, seq_len)\n grads = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n attn = inputs / (hs**0.5)\n attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = torch.nn.functional.softmax(attn, dim=-1)\n\n with FusionDefinition() as fd:\n nanogpt_attn_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), hs, dropout_p)\n\n if not disable_validation:\n # Use dropout_mask instead of torch.nn.functional.dropout for validating results.\n out = attn * dropout_mask * 1 / (1 - dropout_p)\n out.backward(grads)\n fd.validate([grads, attn, dropout_mask, bias_mask], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [grads, attn, dropout_mask, bias_mask])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(","source_hash":"a882e8f9374530c6adba1bb7d73c5a932ff4b7de456f4eb28872674910a50f7f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_nanogpt_attn_bwd.test_nanogpt_attn_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_nanogpt_attn_bwd.test_nanogpt_attn_bwd_baseline_benchmark#L140-L170","kind":"function","name":"test_nanogpt_attn_bwd_baseline_benchmark","path":"benchmarks/python/test_nanogpt_attn_bwd.py","language":"python","start_line":140,"end_line":170,"context_start_line":120,"context_end_line":170,"code":" attn = attn.masked_fill(bias[:, :, :seq_len, :seq_len] == 0, float(\"-inf\"))\n attn = torch.nn.functional.softmax(attn, dim=-1)\n\n with FusionDefinition() as fd:\n nanogpt_attn_bwd_fusion(fd, torch_dtype_to_nvfuser_dtype(dtype), hs, dropout_p)\n\n if not disable_validation:\n # Use dropout_mask instead of torch.nn.functional.dropout for validating results.\n out = attn * dropout_mask * 1 / (1 - dropout_p)\n out.backward(grads)\n fd.validate([grads, attn, dropout_mask, bias_mask], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [grads, attn, dropout_mask, bias_mask])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_nanogpt_attn_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n bias = torch.tril(torch.ones(seq_len, seq_len, device=\"cuda\")).view(\n 1, 1, seq_len, seq_len\n )\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, nanogpt_attn)\n fwd_inputs = [inputs, bias, size, dropout_p]\n outputs = fwd_fn(fwd_inputs)\n\n grads = torch.randn(batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=nanogpt_attn_bwd_iobytes(size, dtype),\n )","source_hash":"a882e8f9374530c6adba1bb7d73c5a932ff4b7de456f4eb28872674910a50f7f","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_fwd","uri":"program://Fuser/module/benchmarks.python.test_dropout_rmsnorm_fwd#L1-L174","kind":"module","name":"benchmarks.python.test_dropout_rmsnorm_fwd","path":"benchmarks/python/test_dropout_rmsnorm_fwd.py","language":"python","start_line":1,"end_line":174,"context_start_line":1,"context_end_line":174,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_rmsnorm\n\n\ndef dropout_rmsnorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n dropout_p: float,\n eps: float = 1e-5,\n) -> None:\n \"\"\"\n Forward pass fusion definition for computing:\n output = rmsnorm (input2 + dropout (input1, p=dropout_p))\n\n Fusion inputs: input, weights\n Fusion outputs: output, dropout_mask, rms\n \"\"\"\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T2 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n S2 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S3 = fd.define_scalar(1.00000, dtype=DataType.Double)\n\n V6 = T0.shape()\n T7 = fd.ops.uniform(S2, S3, shape=V6, dtype=DataType.Float)\n S8 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T9 = fd.ops.lt(T7, S8)\n T10 = fd.ops.cast(T9, dtype=DataType.Float)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n T12 = fd.ops.mul(T0, T10)\n S13 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T14 = fd.ops.mul(T12, S13)\n T15 = fd.ops.add(T2, T14)\n S16 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T17 = fd.ops.pow(T15, S16)\n T18 = fd.ops.sum(T17, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T22 = fd.ops.broadcast_in_dim(T18, shape=[T0.size(0), 1], broadcast_dims=[0])\n\n S24 = fd.ops.reciprocal(T0.size(1))\n T25 = fd.ops.mul(T22, S24)\n S26 = fd.define_scalar(eps, dtype=DataType.Double)\n T27 = fd.ops.add(T25, S26)\n T28 = fd.ops.sqrt(T27)\n\n T33 = fd.ops.broadcast_in_dim(T28, shape=V6, broadcast_dims=[0, 1])\n\n T35 = fd.ops.reciprocal(T33)\n T36 = fd.ops.mul(T15, T35)\n T40 = fd.ops.broadcast_in_dim(T1, shape=V6, broadcast_dims=[1])\n T42 = fd.ops.mul(T40, T36)\n\n if dtype in PROMOTE_DTYPES:\n T42 = fd.ops.cast(T42, dtype=dtype)\n\n fd.add_output(T42)\n fd.add_output(T9)\n fd.add_output(T28)\n\n\ndef dropout_rmsnorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n # Outputs\n \"rms\": (size[0], torch.float),\n \"output\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n\n dropout_p = 0.2\n\n with FusionDefinition() as fd:\n dropout_rmsnorm_fwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p, eps\n )\n\n if not disable_validation:\n # For validating use a fusion definition with dropout_p=0.0\n with FusionDefinition() as val_fd:\n dropout_rmsnorm_fwd_fusion(\n val_fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p=0.0, eps=eps\n )\n\n dropout_mask = torch.ones(size, dtype=torch.bool, device=\"cuda\")\n\n x = input2.to(torch.double) + torch.nn.functional.dropout(\n input1.to(torch.double), p=0.0\n )\n rms_eps = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + eps)\n eager_output = weights.to(torch.double) * (x / rms_eps)\n val_fd.validate(\n [input1, input2, weights],\n [eager_output.to(dtype), dropout_mask, rms_eps.to(torch.float)],\n )\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [input1, input2, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n dropout_p = 0.2\n\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.ones(size[1], device=\"cuda\", dtype=dtype, requires_grad=True),\n dropout_p,\n ]\n\n benchmark_fn = with_executor(executor, dropout_rmsnorm)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n inputs,\n iobytes=dropout_rmsnorm_fwd_iobytes(size, dtype),\n )","source_hash":"671759bef18d966ba1bbc6d355e3a522d9ea81b4997247f667bccee8109ba51d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_fwd.dropout_rmsnorm_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_dropout_rmsnorm_fwd.dropout_rmsnorm_fwd_fusion#L19-L82","kind":"function","name":"dropout_rmsnorm_fwd_fusion","path":"benchmarks/python/test_dropout_rmsnorm_fwd.py","language":"python","start_line":19,"end_line":82,"context_start_line":1,"context_end_line":102,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_rmsnorm\n\n\ndef dropout_rmsnorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n dropout_p: float,\n eps: float = 1e-5,\n) -> None:\n \"\"\"\n Forward pass fusion definition for computing:\n output = rmsnorm (input2 + dropout (input1, p=dropout_p))\n\n Fusion inputs: input, weights\n Fusion outputs: output, dropout_mask, rms\n \"\"\"\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T2 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n S2 = fd.define_scalar(0.00000, dtype=DataType.Double)\n S3 = fd.define_scalar(1.00000, dtype=DataType.Double)\n\n V6 = T0.shape()\n T7 = fd.ops.uniform(S2, S3, shape=V6, dtype=DataType.Float)\n S8 = fd.define_scalar(1 - dropout_p, dtype=DataType.Double)\n T9 = fd.ops.lt(T7, S8)\n T10 = fd.ops.cast(T9, dtype=DataType.Float)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n T2 = fd.ops.cast(T2, dtype=DataType.Float)\n\n T12 = fd.ops.mul(T0, T10)\n S13 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T14 = fd.ops.mul(T12, S13)\n T15 = fd.ops.add(T2, T14)\n S16 = fd.define_scalar(2.00000, dtype=DataType.Double)\n T17 = fd.ops.pow(T15, S16)\n T18 = fd.ops.sum(T17, dims=[1], keepdim=False, dtype=DataType.Null)\n\n T22 = fd.ops.broadcast_in_dim(T18, shape=[T0.size(0), 1], broadcast_dims=[0])\n\n S24 = fd.ops.reciprocal(T0.size(1))\n T25 = fd.ops.mul(T22, S24)\n S26 = fd.define_scalar(eps, dtype=DataType.Double)\n T27 = fd.ops.add(T25, S26)\n T28 = fd.ops.sqrt(T27)\n\n T33 = fd.ops.broadcast_in_dim(T28, shape=V6, broadcast_dims=[0, 1])\n\n T35 = fd.ops.reciprocal(T33)\n T36 = fd.ops.mul(T15, T35)\n T40 = fd.ops.broadcast_in_dim(T1, shape=V6, broadcast_dims=[1])\n T42 = fd.ops.mul(T40, T36)\n\n if dtype in PROMOTE_DTYPES:\n T42 = fd.ops.cast(T42, dtype=dtype)\n\n fd.add_output(T42)\n fd.add_output(T9)\n fd.add_output(T28)\n\n\ndef dropout_rmsnorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n # Outputs\n \"rms\": (size[0], torch.float),\n \"output\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent","source_hash":"671759bef18d966ba1bbc6d355e3a522d9ea81b4997247f667bccee8109ba51d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_fwd.dropout_rmsnorm_fwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_dropout_rmsnorm_fwd.dropout_rmsnorm_fwd_iobytes#L85-L97","kind":"function","name":"dropout_rmsnorm_fwd_iobytes","path":"benchmarks/python/test_dropout_rmsnorm_fwd.py","language":"python","start_line":85,"end_line":97,"context_start_line":65,"context_end_line":117,"code":" T25 = fd.ops.mul(T22, S24)\n S26 = fd.define_scalar(eps, dtype=DataType.Double)\n T27 = fd.ops.add(T25, S26)\n T28 = fd.ops.sqrt(T27)\n\n T33 = fd.ops.broadcast_in_dim(T28, shape=V6, broadcast_dims=[0, 1])\n\n T35 = fd.ops.reciprocal(T33)\n T36 = fd.ops.mul(T15, T35)\n T40 = fd.ops.broadcast_in_dim(T1, shape=V6, broadcast_dims=[1])\n T42 = fd.ops.mul(T40, T36)\n\n if dtype in PROMOTE_DTYPES:\n T42 = fd.ops.cast(T42, dtype=dtype)\n\n fd.add_output(T42)\n fd.add_output(T9)\n fd.add_output(T28)\n\n\ndef dropout_rmsnorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n # Outputs\n \"rms\": (size[0], torch.float),\n \"output\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n\n dropout_p = 0.2\n\n with FusionDefinition() as fd:","source_hash":"671759bef18d966ba1bbc6d355e3a522d9ea81b4997247f667bccee8109ba51d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_fwd.test_dropout_rmsnorm_fwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_dropout_rmsnorm_fwd.test_dropout_rmsnorm_fwd_nvf_benchmark#L103-L142","kind":"function","name":"test_dropout_rmsnorm_fwd_nvf_benchmark","path":"benchmarks/python/test_dropout_rmsnorm_fwd.py","language":"python","start_line":103,"end_line":142,"context_start_line":83,"context_end_line":162,"code":"\n\ndef dropout_rmsnorm_fwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs differ from baseline outputs (output).\n nvf_inp_out = {\n # Inputs\n \"input1\": (size, dtype),\n \"input2\": (size, dtype),\n \"weights\": (size[1], dtype),\n # Outputs\n \"rms\": (size[0], torch.float),\n \"output\": (size, dtype),\n \"dropout_mask\": (size, torch.bool),\n }\n return compute_total_iobytes(nvf_inp_out)\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n eps: float = 1e-5,\n):\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype)\n weights = torch.randn(size[1], device=\"cuda\", dtype=dtype)\n\n dropout_p = 0.2\n\n with FusionDefinition() as fd:\n dropout_rmsnorm_fwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p, eps\n )\n\n if not disable_validation:\n # For validating use a fusion definition with dropout_p=0.0\n with FusionDefinition() as val_fd:\n dropout_rmsnorm_fwd_fusion(\n val_fd, torch_dtype_to_nvfuser_dtype(dtype), dropout_p=0.0, eps=eps\n )\n\n dropout_mask = torch.ones(size, dtype=torch.bool, device=\"cuda\")\n\n x = input2.to(torch.double) + torch.nn.functional.dropout(\n input1.to(torch.double), p=0.0\n )\n rms_eps = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + eps)\n eager_output = weights.to(torch.double) * (x / rms_eps)\n val_fd.validate(\n [input1, input2, weights],\n [eager_output.to(dtype), dropout_mask, rms_eps.to(torch.float)],\n )\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [input1, input2, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n dropout_p = 0.2\n\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.ones(size[1], device=\"cuda\", dtype=dtype, requires_grad=True),","source_hash":"671759bef18d966ba1bbc6d355e3a522d9ea81b4997247f667bccee8109ba51d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_dropout_rmsnorm_fwd.test_dropout_rmsnorm_fwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_dropout_rmsnorm_fwd.test_dropout_rmsnorm_fwd_baseline_benchmark#L149-L174","kind":"function","name":"test_dropout_rmsnorm_fwd_baseline_benchmark","path":"benchmarks/python/test_dropout_rmsnorm_fwd.py","language":"python","start_line":149,"end_line":174,"context_start_line":129,"context_end_line":174,"code":" dropout_mask = torch.ones(size, dtype=torch.bool, device=\"cuda\")\n\n x = input2.to(torch.double) + torch.nn.functional.dropout(\n input1.to(torch.double), p=0.0\n )\n rms_eps = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + eps)\n eager_output = weights.to(torch.double) * (x / rms_eps)\n val_fd.validate(\n [input1, input2, weights],\n [eager_output.to(dtype), dropout_mask, rms_eps.to(torch.float)],\n )\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [input1, input2, weights])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=2))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_dropout_rmsnorm_fwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n dropout_p = 0.2\n\n inputs = [\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.randn(size, device=\"cuda\", dtype=dtype, requires_grad=True),\n torch.ones(size[1], device=\"cuda\", dtype=dtype, requires_grad=True),\n dropout_p,\n ]\n\n benchmark_fn = with_executor(executor, dropout_rmsnorm)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n benchmark_fn,\n inputs,\n iobytes=dropout_rmsnorm_fwd_iobytes(size, dtype),\n )","source_hash":"671759bef18d966ba1bbc6d355e3a522d9ea81b4997247f667bccee8109ba51d","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_bwd","uri":"program://Fuser/module/benchmarks.python.test_huggingface_attn_bwd#L1-L149","kind":"module","name":"benchmarks.python.test_huggingface_attn_bwd","path":"benchmarks/python/test_huggingface_attn_bwd.py","language":"python","start_line":1,"end_line":149,"context_start_line":1,"context_end_line":149,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import huggingface_attn\n\n\n# Fusion from huggingface attention implementation\n# The nvFuser defintion only includes the non-matmul computation (add + reshape + softmax + dropout)\ndef huggingface_attn_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n batch_size: int,\n num_heads: int,\n dropout_p: float,\n):\n S0 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T5 = fd.define_tensor(\n shape=[-1, -1, -1], contiguity=[True, True, True], dtype=dtype, is_cpu=False\n )\n T6 = fd.define_tensor(\n shape=[-1, -1, -1], contiguity=[True, True, True], dtype=dtype, is_cpu=False\n )\n T7 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T5 = fd.ops.cast(T5, dtype=DataType.Float)\n T6 = fd.ops.cast(T6, dtype=DataType.Float)\n T7 = fd.ops.cast(T7, dtype=DataType.Float)\n\n T10 = fd.ops.mul(T5, S0)\n T11 = fd.ops.mul(T10, T7)\n T13 = fd.ops.mul(T6, T11)\n T14 = fd.ops.sum(T13, dims=[2], keepdim=False, dtype=DataType.Null)\n\n T19 = fd.ops.broadcast_in_dim(\n T14, shape=[T5.size(0), T5.size(1), 1], broadcast_dims=[0, 1]\n )\n V24 = T5.shape()\n T25 = fd.ops.broadcast_in_dim(T19, shape=V24, broadcast_dims=[0, 1, 2])\n T27 = fd.ops.sub(T11, T25)\n T28 = fd.ops.mul(T6, T27)\n T35 = fd.ops.reshape(T28, new_shape=[batch_size, num_heads, T5.size(1), T5.size(2)])\n\n if dtype in PROMOTE_DTYPES:\n T35 = fd.ops.cast(T35, dtype=dtype)\n fd.add_output(T35)\n\n\ndef huggingface_attn_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs (grad_out, attn, dropout_mask, grad_input]) differ from baseline input/outputs (output, grad_output).\n\n # Total IO bytes = grad_output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs*nh, seq_len, seq_len], dtype) + dropout_mask ([bs*nh, seq_len, seq_len], bool) + grad_input ([bs, nh, seq_len, seq_len], dtype)\n bs, seq_len, nh, n_embd = size\n return int(bs * nh * seq_len * seq_len * (dtype.itemsize * 3 + torch.bool.itemsize))\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n dropout_mask = torch.lt(\n torch.rand(batch_size * nh, seq_len, seq_len, device=\"cuda\"), 1 - dropout_p\n )\n attention_mask = torch.zeros(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype\n )\n grads = torch.randn(batch_size * nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n attn = (inputs + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = torch.nn.functional.softmax(attn, dim=-1)\n\n with FusionDefinition() as fd:\n huggingface_attn_bwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), batch_size, nh, dropout_p\n )\n\n if not disable_validation:\n # Use dropout_mask instead of torch.nn.functional.dropout for validating results.\n out = attn * dropout_mask * 1 / (1 - dropout_p)\n out.backward(grads)\n fd.validate([grads, attn, dropout_mask], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [grads, attn, dropout_mask])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n attention_mask = torch.zeros(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype\n )\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, huggingface_attn)\n fwd_inputs = [inputs, attention_mask, size, dropout_p]\n outputs = fwd_fn(fwd_inputs)\n grads = torch.randn(batch_size * nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=huggingface_attn_bwd_iobytes(size, dtype),\n )","source_hash":"5516f3ce1b05a579d326b3c6979964b0c82231fcd94ca798f99fd2a5be824846","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_bwd.huggingface_attn_bwd_fusion","uri":"program://Fuser/function/benchmarks.python.test_huggingface_attn_bwd.huggingface_attn_bwd_fusion#L21-L63","kind":"function","name":"huggingface_attn_bwd_fusion","path":"benchmarks/python/test_huggingface_attn_bwd.py","language":"python","start_line":21,"end_line":63,"context_start_line":1,"context_end_line":83,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import huggingface_attn\n\n\n# Fusion from huggingface attention implementation\n# The nvFuser defintion only includes the non-matmul computation (add + reshape + softmax + dropout)\ndef huggingface_attn_bwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n batch_size: int,\n num_heads: int,\n dropout_p: float,\n):\n S0 = fd.define_scalar(1 / (1 - dropout_p), dtype=DataType.Double)\n T5 = fd.define_tensor(\n shape=[-1, -1, -1], contiguity=[True, True, True], dtype=dtype, is_cpu=False\n )\n T6 = fd.define_tensor(\n shape=[-1, -1, -1], contiguity=[True, True, True], dtype=dtype, is_cpu=False\n )\n T7 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Bool,\n is_cpu=False,\n )\n\n if dtype in PROMOTE_DTYPES:\n T5 = fd.ops.cast(T5, dtype=DataType.Float)\n T6 = fd.ops.cast(T6, dtype=DataType.Float)\n T7 = fd.ops.cast(T7, dtype=DataType.Float)\n\n T10 = fd.ops.mul(T5, S0)\n T11 = fd.ops.mul(T10, T7)\n T13 = fd.ops.mul(T6, T11)\n T14 = fd.ops.sum(T13, dims=[2], keepdim=False, dtype=DataType.Null)\n\n T19 = fd.ops.broadcast_in_dim(\n T14, shape=[T5.size(0), T5.size(1), 1], broadcast_dims=[0, 1]\n )\n V24 = T5.shape()\n T25 = fd.ops.broadcast_in_dim(T19, shape=V24, broadcast_dims=[0, 1, 2])\n T27 = fd.ops.sub(T11, T25)\n T28 = fd.ops.mul(T6, T27)\n T35 = fd.ops.reshape(T28, new_shape=[batch_size, num_heads, T5.size(1), T5.size(2)])\n\n if dtype in PROMOTE_DTYPES:\n T35 = fd.ops.cast(T35, dtype=dtype)\n fd.add_output(T35)\n\n\ndef huggingface_attn_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs (grad_out, attn, dropout_mask, grad_input]) differ from baseline input/outputs (output, grad_output).\n\n # Total IO bytes = grad_output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs*nh, seq_len, seq_len], dtype) + dropout_mask ([bs*nh, seq_len, seq_len], bool) + grad_input ([bs, nh, seq_len, seq_len], dtype)\n bs, seq_len, nh, n_embd = size\n return int(bs * nh * seq_len * seq_len * (dtype.itemsize * 3 + torch.bool.itemsize))\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):","source_hash":"5516f3ce1b05a579d326b3c6979964b0c82231fcd94ca798f99fd2a5be824846","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_bwd.huggingface_attn_bwd_iobytes","uri":"program://Fuser/function/benchmarks.python.test_huggingface_attn_bwd.huggingface_attn_bwd_iobytes#L66-L71","kind":"function","name":"huggingface_attn_bwd_iobytes","path":"benchmarks/python/test_huggingface_attn_bwd.py","language":"python","start_line":66,"end_line":71,"context_start_line":46,"context_end_line":91,"code":"\n T10 = fd.ops.mul(T5, S0)\n T11 = fd.ops.mul(T10, T7)\n T13 = fd.ops.mul(T6, T11)\n T14 = fd.ops.sum(T13, dims=[2], keepdim=False, dtype=DataType.Null)\n\n T19 = fd.ops.broadcast_in_dim(\n T14, shape=[T5.size(0), T5.size(1), 1], broadcast_dims=[0, 1]\n )\n V24 = T5.shape()\n T25 = fd.ops.broadcast_in_dim(T19, shape=V24, broadcast_dims=[0, 1, 2])\n T27 = fd.ops.sub(T11, T25)\n T28 = fd.ops.mul(T6, T27)\n T35 = fd.ops.reshape(T28, new_shape=[batch_size, num_heads, T5.size(1), T5.size(2)])\n\n if dtype in PROMOTE_DTYPES:\n T35 = fd.ops.cast(T35, dtype=dtype)\n fd.add_output(T35)\n\n\ndef huggingface_attn_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs (grad_out, attn, dropout_mask, grad_input]) differ from baseline input/outputs (output, grad_output).\n\n # Total IO bytes = grad_output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs*nh, seq_len, seq_len], dtype) + dropout_mask ([bs*nh, seq_len, seq_len], bool) + grad_input ([bs, nh, seq_len, seq_len], dtype)\n bs, seq_len, nh, n_embd = size\n return int(bs * nh * seq_len * seq_len * (dtype.itemsize * 3 + torch.bool.itemsize))\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n dropout_mask = torch.lt(\n torch.rand(batch_size * nh, seq_len, seq_len, device=\"cuda\"), 1 - dropout_p","source_hash":"5516f3ce1b05a579d326b3c6979964b0c82231fcd94ca798f99fd2a5be824846","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_bwd.test_huggingface_attn_bwd_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_huggingface_attn_bwd.test_huggingface_attn_bwd_nvf_benchmark#L77-L113","kind":"function","name":"test_huggingface_attn_bwd_nvf_benchmark","path":"benchmarks/python/test_huggingface_attn_bwd.py","language":"python","start_line":77,"end_line":113,"context_start_line":57,"context_end_line":133,"code":" T27 = fd.ops.sub(T11, T25)\n T28 = fd.ops.mul(T6, T27)\n T35 = fd.ops.reshape(T28, new_shape=[batch_size, num_heads, T5.size(1), T5.size(2)])\n\n if dtype in PROMOTE_DTYPES:\n T35 = fd.ops.cast(T35, dtype=dtype)\n fd.add_output(T35)\n\n\ndef huggingface_attn_bwd_iobytes(size: tuple, dtype: torch.dtype):\n # Manual IOByte computation is required since nvFuser input/outputs (grad_out, attn, dropout_mask, grad_input]) differ from baseline input/outputs (output, grad_output).\n\n # Total IO bytes = grad_output ([bs, nh, seq_len, seq_len], dtype) + attn ([bs*nh, seq_len, seq_len], dtype) + dropout_mask ([bs*nh, seq_len, seq_len], bool) + grad_input ([bs, nh, seq_len, seq_len], dtype)\n bs, seq_len, nh, n_embd = size\n return int(bs * nh * seq_len * seq_len * (dtype.itemsize * 3 + torch.bool.itemsize))\n\n\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_bwd_nvf_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n batch_size, seq_len, nh, n_embd = size\n\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n dropout_mask = torch.lt(\n torch.rand(batch_size * nh, seq_len, seq_len, device=\"cuda\"), 1 - dropout_p\n )\n attention_mask = torch.zeros(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype\n )\n grads = torch.randn(batch_size * nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n attn = (inputs + attention_mask).view(batch_size * nh, seq_len, seq_len)\n attn = torch.nn.functional.softmax(attn, dim=-1)\n\n with FusionDefinition() as fd:\n huggingface_attn_bwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), batch_size, nh, dropout_p\n )\n\n if not disable_validation:\n # Use dropout_mask instead of torch.nn.functional.dropout for validating results.\n out = attn * dropout_mask * 1 / (1 - dropout_p)\n out.backward(grads)\n fd.validate([grads, attn, dropout_mask], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [grads, attn, dropout_mask])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n attention_mask = torch.zeros(","source_hash":"5516f3ce1b05a579d326b3c6979964b0c82231fcd94ca798f99fd2a5be824846","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_huggingface_attn_bwd.test_huggingface_attn_bwd_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_huggingface_attn_bwd.test_huggingface_attn_bwd_baseline_benchmark#L120-L149","kind":"function","name":"test_huggingface_attn_bwd_baseline_benchmark","path":"benchmarks/python/test_huggingface_attn_bwd.py","language":"python","start_line":120,"end_line":149,"context_start_line":100,"context_end_line":149,"code":"\n with FusionDefinition() as fd:\n huggingface_attn_bwd_fusion(\n fd, torch_dtype_to_nvfuser_dtype(dtype), batch_size, nh, dropout_p\n )\n\n if not disable_validation:\n # Use dropout_mask instead of torch.nn.functional.dropout for validating results.\n out = attn * dropout_mask * 1 / (1 - dropout_p)\n out.backward(grads)\n fd.validate([grads, attn, dropout_mask], [inputs.grad])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, [grads, attn, dropout_mask])\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size\", generate_attn_inputs())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.inner_persistent\ndef test_huggingface_attn_bwd_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n batch_size, seq_len, nh, n_embd = size\n dropout_p = 0.2\n inputs = torch.randn(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype, requires_grad=True\n )\n attention_mask = torch.zeros(\n batch_size, nh, seq_len, seq_len, device=\"cuda\", dtype=dtype\n )\n\n # Compile the fwd fn for torchcompile\n fwd_fn = with_executor(executor, huggingface_attn)\n fwd_inputs = [inputs, attention_mask, size, dropout_p]\n outputs = fwd_fn(fwd_inputs)\n grads = torch.randn(batch_size * nh, seq_len, seq_len, device=\"cuda\", dtype=dtype)\n\n # Manually compute IOBytes: See PR #1725\n run_benchmark(\n benchmark,\n unary_bwd_torch,\n [outputs, grads, *fwd_inputs],\n iobytes=huggingface_attn_bwd_iobytes(size, dtype),\n )","source_hash":"5516f3ce1b05a579d326b3c6979964b0c82231fcd94ca798f99fd2a5be824846","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_transpose","uri":"program://Fuser/module/benchmarks.python.test_transpose#L1-L221","kind":"module","name":"benchmarks.python.test_transpose","path":"benchmarks/python/test_transpose.py","language":"python","start_line":1,"end_line":221,"context_start_line":1,"context_end_line":221,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef transpose_fusion_input_smem(\n fd: FusionDefinition,\n dtype: DataType,\n is_copy_transpose: bool,\n axes: list,\n rank: int,\n):\n \"\"\"Single input: the transposed input is read through shared memory.\"\"\"\n shape = [-1] * rank\n contiguity = [True] * rank\n T0 = fd.define_tensor(shape=shape, contiguity=contiguity, dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n\n T1 = fd.ops.permute(T0, dims=axes)\n\n if dtype in PROMOTE_DTYPES:\n T1 = fd.ops.cast(T1, dtype=dtype)\n\n S2 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T3 = fd.ops.gt(T1, S2)\n T4 = fd.ops.where(T3, T1, S2)\n # add segmenter set to avoid presegment passes setting the output as a\n # view of the input without any data movement. It leads to pointwise\n # instead of transpose scheduler.\n # we can also expose OptimizationPassGuard to python frontend and disable\n # presegmentation passes to enforce output to be contiguous and then\n # transpose scheduler will be used.\n if is_copy_transpose:\n T5 = fd.ops.segment_set(T4)\n fd.add_output(T5)\n else:\n fd.add_output(T4)\n\n\ndef transpose_fusion_output_smem(\n fd: FusionDefinition,\n dtype: DataType,\n is_copy_transpose: bool,\n axes: list,\n rank: int,\n):\n \"\"\"Two inputs: the transposed output is written through shared memory.\"\"\"\n shape = [-1] * rank\n contiguity = [True] * rank\n T0 = fd.define_tensor(shape=shape, contiguity=contiguity, dtype=dtype, is_cpu=False)\n T1 = fd.define_tensor(shape=shape, contiguity=contiguity, dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n\n T2 = fd.ops.add(T0, T1)\n T3 = fd.ops.permute(T2, dims=axes)\n\n if dtype in PROMOTE_DTYPES:\n T3 = fd.ops.cast(T3, dtype=dtype)\n\n S4 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T5 = fd.ops.gt(T3, S4)\n T6 = fd.ops.where(T5, T3, S4)\n # add segmenter set to avoid presegment passes setting the output as a\n # view of the input without any data movement. It leads to pointwise\n # instead of transpose scheduler.\n # we can also expose OptimizationPassGuard to python frontend and disable\n # presegmentation passes to enforce output to be contiguous and then\n # transpose scheduler will be used.\n if is_copy_transpose:\n T7 = fd.ops.segment_set(T6)\n fd.add_output(T7)\n else:\n fd.add_output(T6)\n\n\n# Without contiguous, transpose returns a view with swapped strides.\n# contiguous() materializes a contiguous copy of the result.\n# When compiled with thunder, contiguous version will use nvFuser's transpose scheduler, otherwise it will use the pointwise scheduler.\ndef transpose_fwd_fn(\n inputs: list,\n): # [input1, input2 (optional), axes, is_copy_transpose]\n is_copy_transpose = inputs[-1]\n axes = inputs[-2]\n if len(inputs) == 4:\n data = inputs[0] + inputs[1]\n else:\n data = inputs[0]\n relu_transpose_result = torch.nn.functional.relu(data.permute(axes))\n if is_copy_transpose:\n return relu_transpose_result.contiguous()\n else:\n return relu_transpose_result\n\n\ndef setup_input_smem(size, dtype, is_copy_transpose, axes, dims):\n \"\"\"Single input: the transposed input is read through shared memory.\"\"\"\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n nvfuser_inputs = [input1]\n\n with FusionDefinition() as fd:\n transpose_fusion_input_smem(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n is_copy_transpose,\n axes,\n rank=dims,\n )\n\n eager_inputs = [input1, axes, is_copy_transpose]\n return fd, nvfuser_inputs, eager_inputs\n\n\ndef setup_output_smem(size, dtype, is_copy_transpose, axes, dims):\n \"\"\"Two inputs: the transposed output is written through shared memory.\"\"\"\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype)\n nvfuser_inputs = [input1, input2]\n\n with FusionDefinition() as fd:\n transpose_fusion_output_smem(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n is_copy_transpose,\n axes,\n rank=dims,\n )\n\n eager_inputs = [input1, input2, axes, is_copy_transpose]\n return fd, nvfuser_inputs, eager_inputs\n\n\ndef _generate_transpose_params():\n params = []\n for dims in (2, 3):\n sizes = generate_input_sizes(dims=dims)\n if dims == 2:\n axes_list = [(1, 0)]\n else:\n axes_list = [(1, 0, 2), (2, 1, 0), (0, 2, 1)]\n for size in sizes:\n for axes in axes_list:\n params.append((size, axes, dims))\n return params\n\n\n@pytest.mark.parametrize(\"size,axes,dims\", _generate_transpose_params())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"is_copy_transpose\",\n [\n pytest.param(True, marks=pytest.mark.transpose, id=\"copy\"),\n pytest.param(False, marks=pytest.mark.pointwise, id=\"view\"),\n ],\n)\n@pytest.mark.parametrize(\n \"setup_fn\",\n [setup_input_smem, setup_output_smem],\n ids=[\"input_smem\", \"output_smem\"],\n)\ndef test_transpose_nvf_benchmark(\n benchmark,\n size: tuple,\n is_copy_transpose: bool,\n dtype: torch.dtype,\n axes: tuple,\n dims: int,\n setup_fn,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n fd, nvfuser_inputs, eager_inputs = setup_fn(\n size, dtype, is_copy_transpose, axes, dims\n )\n\n if not disable_validation:\n eager_output = transpose_fwd_fn(eager_inputs)\n fd.validate(nvfuser_inputs, [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, nvfuser_inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size,axes,dims\", _generate_transpose_params())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"is_copy_transpose\",\n [True, False],\n ids=[\"copy\", \"view\"],\n)\n@pytest.mark.parametrize(\n \"setup_fn\",\n [setup_input_smem, setup_output_smem],\n ids=[\"input_smem\", \"output_smem\"],\n)\ndef test_transpose_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n is_copy_transpose: bool,\n axes: tuple,\n dims: int,\n setup_fn,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n _, _, eager_inputs = setup_fn(size, dtype, is_copy_transpose, axes, dims)\n benchmark_fn = with_executor(executor, transpose_fwd_fn)\n run_benchmark(benchmark, benchmark_fn, eager_inputs)","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_transpose.transpose_fusion_input_smem","uri":"program://Fuser/function/benchmarks.python.test_transpose.transpose_fusion_input_smem#L12-L45","kind":"function","name":"transpose_fusion_input_smem","path":"benchmarks/python/test_transpose.py","language":"python","start_line":12,"end_line":45,"context_start_line":1,"context_end_line":65,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef transpose_fusion_input_smem(\n fd: FusionDefinition,\n dtype: DataType,\n is_copy_transpose: bool,\n axes: list,\n rank: int,\n):\n \"\"\"Single input: the transposed input is read through shared memory.\"\"\"\n shape = [-1] * rank\n contiguity = [True] * rank\n T0 = fd.define_tensor(shape=shape, contiguity=contiguity, dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n\n T1 = fd.ops.permute(T0, dims=axes)\n\n if dtype in PROMOTE_DTYPES:\n T1 = fd.ops.cast(T1, dtype=dtype)\n\n S2 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T3 = fd.ops.gt(T1, S2)\n T4 = fd.ops.where(T3, T1, S2)\n # add segmenter set to avoid presegment passes setting the output as a\n # view of the input without any data movement. It leads to pointwise\n # instead of transpose scheduler.\n # we can also expose OptimizationPassGuard to python frontend and disable\n # presegmentation passes to enforce output to be contiguous and then\n # transpose scheduler will be used.\n if is_copy_transpose:\n T5 = fd.ops.segment_set(T4)\n fd.add_output(T5)\n else:\n fd.add_output(T4)\n\n\ndef transpose_fusion_output_smem(\n fd: FusionDefinition,\n dtype: DataType,\n is_copy_transpose: bool,\n axes: list,\n rank: int,\n):\n \"\"\"Two inputs: the transposed output is written through shared memory.\"\"\"\n shape = [-1] * rank\n contiguity = [True] * rank\n T0 = fd.define_tensor(shape=shape, contiguity=contiguity, dtype=dtype, is_cpu=False)\n T1 = fd.define_tensor(shape=shape, contiguity=contiguity, dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n\n T2 = fd.ops.add(T0, T1)","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_transpose.transpose_fusion_output_smem","uri":"program://Fuser/function/benchmarks.python.test_transpose.transpose_fusion_output_smem#L48-L84","kind":"function","name":"transpose_fusion_output_smem","path":"benchmarks/python/test_transpose.py","language":"python","start_line":48,"end_line":84,"context_start_line":28,"context_end_line":104,"code":"\n if dtype in PROMOTE_DTYPES:\n T1 = fd.ops.cast(T1, dtype=dtype)\n\n S2 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T3 = fd.ops.gt(T1, S2)\n T4 = fd.ops.where(T3, T1, S2)\n # add segmenter set to avoid presegment passes setting the output as a\n # view of the input without any data movement. It leads to pointwise\n # instead of transpose scheduler.\n # we can also expose OptimizationPassGuard to python frontend and disable\n # presegmentation passes to enforce output to be contiguous and then\n # transpose scheduler will be used.\n if is_copy_transpose:\n T5 = fd.ops.segment_set(T4)\n fd.add_output(T5)\n else:\n fd.add_output(T4)\n\n\ndef transpose_fusion_output_smem(\n fd: FusionDefinition,\n dtype: DataType,\n is_copy_transpose: bool,\n axes: list,\n rank: int,\n):\n \"\"\"Two inputs: the transposed output is written through shared memory.\"\"\"\n shape = [-1] * rank\n contiguity = [True] * rank\n T0 = fd.define_tensor(shape=shape, contiguity=contiguity, dtype=dtype, is_cpu=False)\n T1 = fd.define_tensor(shape=shape, contiguity=contiguity, dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T1 = fd.ops.cast(T1, dtype=DataType.Float)\n\n T2 = fd.ops.add(T0, T1)\n T3 = fd.ops.permute(T2, dims=axes)\n\n if dtype in PROMOTE_DTYPES:\n T3 = fd.ops.cast(T3, dtype=dtype)\n\n S4 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T5 = fd.ops.gt(T3, S4)\n T6 = fd.ops.where(T5, T3, S4)\n # add segmenter set to avoid presegment passes setting the output as a\n # view of the input without any data movement. It leads to pointwise\n # instead of transpose scheduler.\n # we can also expose OptimizationPassGuard to python frontend and disable\n # presegmentation passes to enforce output to be contiguous and then\n # transpose scheduler will be used.\n if is_copy_transpose:\n T7 = fd.ops.segment_set(T6)\n fd.add_output(T7)\n else:\n fd.add_output(T6)\n\n\n# Without contiguous, transpose returns a view with swapped strides.\n# contiguous() materializes a contiguous copy of the result.\n# When compiled with thunder, contiguous version will use nvFuser's transpose scheduler, otherwise it will use the pointwise scheduler.\ndef transpose_fwd_fn(\n inputs: list,\n): # [input1, input2 (optional), axes, is_copy_transpose]\n is_copy_transpose = inputs[-1]\n axes = inputs[-2]\n if len(inputs) == 4:\n data = inputs[0] + inputs[1]\n else:\n data = inputs[0]\n relu_transpose_result = torch.nn.functional.relu(data.permute(axes))\n if is_copy_transpose:\n return relu_transpose_result.contiguous()\n else:\n return relu_transpose_result\n","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_transpose.transpose_fwd_fn","uri":"program://Fuser/function/benchmarks.python.test_transpose.transpose_fwd_fn#L90-L103","kind":"function","name":"transpose_fwd_fn","path":"benchmarks/python/test_transpose.py","language":"python","start_line":90,"end_line":103,"context_start_line":70,"context_end_line":123,"code":"\n S4 = fd.define_scalar(0.00000, dtype=DataType.Double)\n T5 = fd.ops.gt(T3, S4)\n T6 = fd.ops.where(T5, T3, S4)\n # add segmenter set to avoid presegment passes setting the output as a\n # view of the input without any data movement. It leads to pointwise\n # instead of transpose scheduler.\n # we can also expose OptimizationPassGuard to python frontend and disable\n # presegmentation passes to enforce output to be contiguous and then\n # transpose scheduler will be used.\n if is_copy_transpose:\n T7 = fd.ops.segment_set(T6)\n fd.add_output(T7)\n else:\n fd.add_output(T6)\n\n\n# Without contiguous, transpose returns a view with swapped strides.\n# contiguous() materializes a contiguous copy of the result.\n# When compiled with thunder, contiguous version will use nvFuser's transpose scheduler, otherwise it will use the pointwise scheduler.\ndef transpose_fwd_fn(\n inputs: list,\n): # [input1, input2 (optional), axes, is_copy_transpose]\n is_copy_transpose = inputs[-1]\n axes = inputs[-2]\n if len(inputs) == 4:\n data = inputs[0] + inputs[1]\n else:\n data = inputs[0]\n relu_transpose_result = torch.nn.functional.relu(data.permute(axes))\n if is_copy_transpose:\n return relu_transpose_result.contiguous()\n else:\n return relu_transpose_result\n\n\ndef setup_input_smem(size, dtype, is_copy_transpose, axes, dims):\n \"\"\"Single input: the transposed input is read through shared memory.\"\"\"\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n nvfuser_inputs = [input1]\n\n with FusionDefinition() as fd:\n transpose_fusion_input_smem(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n is_copy_transpose,\n axes,\n rank=dims,\n )\n\n eager_inputs = [input1, axes, is_copy_transpose]\n return fd, nvfuser_inputs, eager_inputs\n\n","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_transpose.setup_input_smem","uri":"program://Fuser/function/benchmarks.python.test_transpose.setup_input_smem#L106-L121","kind":"function","name":"setup_input_smem","path":"benchmarks/python/test_transpose.py","language":"python","start_line":106,"end_line":121,"context_start_line":86,"context_end_line":141,"code":"\n# Without contiguous, transpose returns a view with swapped strides.\n# contiguous() materializes a contiguous copy of the result.\n# When compiled with thunder, contiguous version will use nvFuser's transpose scheduler, otherwise it will use the pointwise scheduler.\ndef transpose_fwd_fn(\n inputs: list,\n): # [input1, input2 (optional), axes, is_copy_transpose]\n is_copy_transpose = inputs[-1]\n axes = inputs[-2]\n if len(inputs) == 4:\n data = inputs[0] + inputs[1]\n else:\n data = inputs[0]\n relu_transpose_result = torch.nn.functional.relu(data.permute(axes))\n if is_copy_transpose:\n return relu_transpose_result.contiguous()\n else:\n return relu_transpose_result\n\n\ndef setup_input_smem(size, dtype, is_copy_transpose, axes, dims):\n \"\"\"Single input: the transposed input is read through shared memory.\"\"\"\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n nvfuser_inputs = [input1]\n\n with FusionDefinition() as fd:\n transpose_fusion_input_smem(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n is_copy_transpose,\n axes,\n rank=dims,\n )\n\n eager_inputs = [input1, axes, is_copy_transpose]\n return fd, nvfuser_inputs, eager_inputs\n\n\ndef setup_output_smem(size, dtype, is_copy_transpose, axes, dims):\n \"\"\"Two inputs: the transposed output is written through shared memory.\"\"\"\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype)\n nvfuser_inputs = [input1, input2]\n\n with FusionDefinition() as fd:\n transpose_fusion_output_smem(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n is_copy_transpose,\n axes,\n rank=dims,\n )\n\n eager_inputs = [input1, input2, axes, is_copy_transpose]\n return fd, nvfuser_inputs, eager_inputs\n","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_transpose.setup_output_smem","uri":"program://Fuser/function/benchmarks.python.test_transpose.setup_output_smem#L124-L140","kind":"function","name":"setup_output_smem","path":"benchmarks/python/test_transpose.py","language":"python","start_line":124,"end_line":140,"context_start_line":104,"context_end_line":160,"code":"\n\ndef setup_input_smem(size, dtype, is_copy_transpose, axes, dims):\n \"\"\"Single input: the transposed input is read through shared memory.\"\"\"\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n nvfuser_inputs = [input1]\n\n with FusionDefinition() as fd:\n transpose_fusion_input_smem(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n is_copy_transpose,\n axes,\n rank=dims,\n )\n\n eager_inputs = [input1, axes, is_copy_transpose]\n return fd, nvfuser_inputs, eager_inputs\n\n\ndef setup_output_smem(size, dtype, is_copy_transpose, axes, dims):\n \"\"\"Two inputs: the transposed output is written through shared memory.\"\"\"\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype)\n nvfuser_inputs = [input1, input2]\n\n with FusionDefinition() as fd:\n transpose_fusion_output_smem(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n is_copy_transpose,\n axes,\n rank=dims,\n )\n\n eager_inputs = [input1, input2, axes, is_copy_transpose]\n return fd, nvfuser_inputs, eager_inputs\n\n\ndef _generate_transpose_params():\n params = []\n for dims in (2, 3):\n sizes = generate_input_sizes(dims=dims)\n if dims == 2:\n axes_list = [(1, 0)]\n else:\n axes_list = [(1, 0, 2), (2, 1, 0), (0, 2, 1)]\n for size in sizes:\n for axes in axes_list:\n params.append((size, axes, dims))\n return params\n\n\n@pytest.mark.parametrize(\"size,axes,dims\", _generate_transpose_params())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"is_copy_transpose\",","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_transpose._generate_transpose_params","uri":"program://Fuser/function/benchmarks.python.test_transpose._generate_transpose_params#L143-L154","kind":"function","name":"_generate_transpose_params","path":"benchmarks/python/test_transpose.py","language":"python","start_line":143,"end_line":154,"context_start_line":123,"context_end_line":174,"code":"\ndef setup_output_smem(size, dtype, is_copy_transpose, axes, dims):\n \"\"\"Two inputs: the transposed output is written through shared memory.\"\"\"\n input1 = torch.randn(size, device=\"cuda\", dtype=dtype)\n input2 = torch.randn(size, device=\"cuda\", dtype=dtype)\n nvfuser_inputs = [input1, input2]\n\n with FusionDefinition() as fd:\n transpose_fusion_output_smem(\n fd,\n torch_dtype_to_nvfuser_dtype(dtype),\n is_copy_transpose,\n axes,\n rank=dims,\n )\n\n eager_inputs = [input1, input2, axes, is_copy_transpose]\n return fd, nvfuser_inputs, eager_inputs\n\n\ndef _generate_transpose_params():\n params = []\n for dims in (2, 3):\n sizes = generate_input_sizes(dims=dims)\n if dims == 2:\n axes_list = [(1, 0)]\n else:\n axes_list = [(1, 0, 2), (2, 1, 0), (0, 2, 1)]\n for size in sizes:\n for axes in axes_list:\n params.append((size, axes, dims))\n return params\n\n\n@pytest.mark.parametrize(\"size,axes,dims\", _generate_transpose_params())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"is_copy_transpose\",\n [\n pytest.param(True, marks=pytest.mark.transpose, id=\"copy\"),\n pytest.param(False, marks=pytest.mark.pointwise, id=\"view\"),\n ],\n)\n@pytest.mark.parametrize(\n \"setup_fn\",\n [setup_input_smem, setup_output_smem],\n ids=[\"input_smem\", \"output_smem\"],\n)\ndef test_transpose_nvf_benchmark(\n benchmark,\n size: tuple,\n is_copy_transpose: bool,","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_transpose.test_transpose_nvf_benchmark","uri":"program://Fuser/function/benchmarks.python.test_transpose.test_transpose_nvf_benchmark#L171-L191","kind":"function","name":"test_transpose_nvf_benchmark","path":"benchmarks/python/test_transpose.py","language":"python","start_line":171,"end_line":191,"context_start_line":151,"context_end_line":211,"code":" for size in sizes:\n for axes in axes_list:\n params.append((size, axes, dims))\n return params\n\n\n@pytest.mark.parametrize(\"size,axes,dims\", _generate_transpose_params())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"is_copy_transpose\",\n [\n pytest.param(True, marks=pytest.mark.transpose, id=\"copy\"),\n pytest.param(False, marks=pytest.mark.pointwise, id=\"view\"),\n ],\n)\n@pytest.mark.parametrize(\n \"setup_fn\",\n [setup_input_smem, setup_output_smem],\n ids=[\"input_smem\", \"output_smem\"],\n)\ndef test_transpose_nvf_benchmark(\n benchmark,\n size: tuple,\n is_copy_transpose: bool,\n dtype: torch.dtype,\n axes: tuple,\n dims: int,\n setup_fn,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n fd, nvfuser_inputs, eager_inputs = setup_fn(\n size, dtype, is_copy_transpose, axes, dims\n )\n\n if not disable_validation:\n eager_output = transpose_fwd_fn(eager_inputs)\n fd.validate(nvfuser_inputs, [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, nvfuser_inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size,axes,dims\", _generate_transpose_params())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"is_copy_transpose\",\n [True, False],\n ids=[\"copy\", \"view\"],\n)\n@pytest.mark.parametrize(\n \"setup_fn\",\n [setup_input_smem, setup_output_smem],\n ids=[\"input_smem\", \"output_smem\"],\n)\ndef test_transpose_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n is_copy_transpose: bool,","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.test_transpose.test_transpose_baseline_benchmark","uri":"program://Fuser/function/benchmarks.python.test_transpose.test_transpose_baseline_benchmark#L207-L221","kind":"function","name":"test_transpose_baseline_benchmark","path":"benchmarks/python/test_transpose.py","language":"python","start_line":207,"end_line":221,"context_start_line":187,"context_end_line":221,"code":" eager_output = transpose_fwd_fn(eager_inputs)\n fd.validate(nvfuser_inputs, [eager_output])\n\n if not disable_benchmarking:\n run_benchmark(benchmark, fd.execute, nvfuser_inputs)\n\n\n@pytest.mark.parametrize(\"executor\", DEFAULT_EXECUTORS)\n@pytest.mark.parametrize(\"size,axes,dims\", _generate_transpose_params())\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"is_copy_transpose\",\n [True, False],\n ids=[\"copy\", \"view\"],\n)\n@pytest.mark.parametrize(\n \"setup_fn\",\n [setup_input_smem, setup_output_smem],\n ids=[\"input_smem\", \"output_smem\"],\n)\ndef test_transpose_baseline_benchmark(\n benchmark,\n size: tuple,\n dtype: torch.dtype,\n is_copy_transpose: bool,\n axes: tuple,\n dims: int,\n setup_fn,\n executor: str,\n):\n if executor == \"torchcompile\":\n clear_dynamo_cache()\n _, _, eager_inputs = setup_fn(size, dtype, is_copy_transpose, axes, dims)\n benchmark_fn = with_executor(executor, transpose_fwd_fn)\n run_benchmark(benchmark, benchmark_fn, eager_inputs)","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.global_params","uri":"program://Fuser/module/benchmarks.python.global_params#L1-L174","kind":"module","name":"benchmarks.python.global_params","path":"benchmarks/python/global_params.py","language":"python","start_line":1,"end_line":174,"context_start_line":1,"context_end_line":174,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\nfrom typing import Union, List, Tuple\nfrom nvfuser_direct import DataType\nfrom .core import BENCHMARK_CONFIG\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\nimport itertools\nimport os\nfrom random import sample\n\n# BENCHMARK_MODE = weekly/nightly.\nBENCHMARK_MODE = os.getenv(\"BENCHMARK_MODE\")\nif not BENCHMARK_MODE:\n BENCHMARK_MODE = \"nightly\"\n\n# Datatypes to benchmark\nFLOAT_DTYPES = [torch.float32]\n# Run only one of float16 / bfloat16.\nif DEVICE_PROPERTIES[\"gpu_compute_capability_major\"] >= 8:\n FLOAT_DTYPES.append(torch.bfloat16)\nelse:\n FLOAT_DTYPES.append(torch.float16)\n\n# Datatypes that will be promoted to Datatype.Float in Fusion Definitions\nPROMOTE_DTYPES = [DataType.BFloat16, DataType.Half]\n\n# Model Parameters from LLMs (GPT2/3, PaLM, LLama)\n\n# Embedding size: d_model, d_ff = 4 * d_model\nD_MODEL_MIN = 768\nD_MODEL_MAX = 18432\n\n# (num_heads, n_embd) configurations seen in models.\nLLM_CONFIGS = [\n (12, 768), # GPT-2 (124M), GPT-3 (125M)\n (16, 1024), # GPT-2 (350M), GPT-3 (350M)\n (20, 1280), # GPT-2 (774M)\n (16, 1536), # GPT-3 (760M)\n (25, 1600), # GPT-2 (1558M)\n (24, 2048), # GPT-3 (1.3B)\n (32, 2560), # GPT-3 (2.7B)\n (16, 4096), # PaLM (8B)\n (32, 4096), # LLaMA (7B), GPT-3 (6.7B)\n (40, 5120), # LLaMA (13B), GPT-3 (13B)\n (52, 6656), # LLaMA (30B)\n (32, 8192), # PaLM (63B)\n (64, 8192), # LLaMA (65B)\n (96, 12288), # GPT-3 (175B)\n (48, 18432), # PaLM (540B)\n]\n\n\n# Utility function to generate input sizes for benchmarks\ndef generate_input_sizes(dims: Union[int, List] = 2) -> List[Tuple]:\n \"\"\"\n The weekly vs nightly input ranges only differ for 2D inputs currently.\n Nightly input range:\n Batch size: [16, 512, 2048, 8192, 16384] Hidden size: [768, 4*18432] (step size = 256)\n Weekly input range:\n Hidden size: Additonally benchmark hidden sizes at\n [step_size + 2, step_size + 4, step_size + 8, step_size + 16] to check vectorization.\n Note: The hidden size is restricted to 2 * 18432 for the batch size 16384 to avoid OOM.\n \"\"\"\n inputs = []\n if isinstance(dims, int):\n dims = [dims]\n\n for dim in dims:\n if dim == 2:\n input_ranges = []\n\n step_size = 256\n batch_range = [16, 512, 2048, 8192]\n\n # max_hidden_size = 4 * d_model_max (max hidden size in feedforward layers)\n # NOTE: (This is not applicable to the updated implementation but leaving it here for future updates).\n # Numpy arrays are not JSON serializable so convert them to enable storing benchmark data.\n\n hidden_range = []\n for hs in range(\n D_MODEL_MIN, 4 * D_MODEL_MAX + 1, step_size\n ): # (768, 4*18432)\n hidden_range.append(hs)\n if BENCHMARK_MODE == \"weekly\":\n # Additionally benchmark hidden sizes at steps (256 + 2, 256 + 4, 256 + 8, 256 + 16)\n hidden_range.extend([hs + 2, hs + 4, hs + 8, hs + 16])\n input_ranges.append((batch_range, hidden_range))\n\n # Reduce max hidden size for largest batch size (16384) to avoid OOM in RMSNorm.\n # Sweeps hidden sizes from # (768, 2*18432) or (768, 2*18432 + 16) for weekly.\n input_ranges.append(\n ([16384], filter(lambda hs: hs <= 2 * D_MODEL_MAX + 16, hidden_range))\n )\n\n for batch_range, hidden_range in input_ranges:\n inputs.extend(list(itertools.product(batch_range, hidden_range)))\n\n elif dim == 3:\n dim_range = [2**i for i in range(1, 10)]\n inputs.extend(list(itertools.product(dim_range, repeat=3)))\n elif dim == 4:\n # TODO: Add spatial_dim = 2.\n input_ranges = []\n\n batch_range = [2**i for i in range(1, 10)] # {2, 512}\n channel_range = [2**i for i in range(1, 8)] # {2, 128}\n spatial_range = [2**i for i in range(2, 7)] # {4, 64}\n input_ranges.append((batch_range, channel_range, spatial_range))\n\n batch_range = [2**i for i in range(1, 7)] # {2, 64}\n channel_range = [2**i for i in range(1, 6)] # {2, 32}\n spatial_range = [128, 256]\n input_ranges.append((batch_range, channel_range, spatial_range))\n\n # Resnet/ResNext sizes\n batch_range = [2**i for i in range(5, 9)] # {32, 256}\n channel_range = [2**i for i in range(6, 9)] # {64, 256}\n spatial_range = [7 * 2**i for i in range(5)] # {7, 112}\n input_ranges.append((batch_range, channel_range, spatial_range))\n\n for batch_range, channel_range, spatial_range in input_ranges:\n inputs.extend(\n [\n (n, c, hw, hw)\n for (n, c, hw) in itertools.product(\n batch_range, channel_range, spatial_range\n )\n ]\n )\n\n inputs.extend(\n [\n (n, c, hw, hw)\n for (n, (c, hw)) in itertools.product(\n [128, 256],\n [\n (512, 7),\n (512, 14),\n (512, 28),\n (1024, 7),\n (1024, 14),\n (2048, 7),\n ],\n )\n ]\n )\n\n else:\n raise NotImplementedError(\n f\"Generating input sizes of dimension {dim} is not implemented\"\n )\n if BENCHMARK_CONFIG[\"num_inputs\"] is not None:\n inputs = sample(inputs, BENCHMARK_CONFIG[\"num_inputs\"])\n\n return inputs\n\n\n# Utility function to generate input sizes for attention benchmarks.\ndef generate_attn_inputs():\n batch_range = [16, 32]\n seq_lengths = [2**i for i in range(2, 10)] # {4, 512}\n inputs = [\n (batch_size, seq_len, nh, n_embd)\n for (batch_size, seq_len, (nh, n_embd)) in itertools.product(\n batch_range, seq_lengths, LLM_CONFIGS\n )\n ]\n\n if BENCHMARK_CONFIG[\"num_inputs\"] is not None:\n inputs = sample(inputs, BENCHMARK_CONFIG[\"num_inputs\"])\n\n return inputs","source_hash":"b0a8d35825929a496b67479c5542c225820ce696ff5d76d67e5d89042b90bc17","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.global_params.generate_input_sizes","uri":"program://Fuser/function/benchmarks.python.global_params.generate_input_sizes#L56-L157","kind":"function","name":"generate_input_sizes","path":"benchmarks/python/global_params.py","language":"python","start_line":56,"end_line":157,"context_start_line":36,"context_end_line":174,"code":"LLM_CONFIGS = [\n (12, 768), # GPT-2 (124M), GPT-3 (125M)\n (16, 1024), # GPT-2 (350M), GPT-3 (350M)\n (20, 1280), # GPT-2 (774M)\n (16, 1536), # GPT-3 (760M)\n (25, 1600), # GPT-2 (1558M)\n (24, 2048), # GPT-3 (1.3B)\n (32, 2560), # GPT-3 (2.7B)\n (16, 4096), # PaLM (8B)\n (32, 4096), # LLaMA (7B), GPT-3 (6.7B)\n (40, 5120), # LLaMA (13B), GPT-3 (13B)\n (52, 6656), # LLaMA (30B)\n (32, 8192), # PaLM (63B)\n (64, 8192), # LLaMA (65B)\n (96, 12288), # GPT-3 (175B)\n (48, 18432), # PaLM (540B)\n]\n\n\n# Utility function to generate input sizes for benchmarks\ndef generate_input_sizes(dims: Union[int, List] = 2) -> List[Tuple]:\n \"\"\"\n The weekly vs nightly input ranges only differ for 2D inputs currently.\n Nightly input range:\n Batch size: [16, 512, 2048, 8192, 16384] Hidden size: [768, 4*18432] (step size = 256)\n Weekly input range:\n Hidden size: Additonally benchmark hidden sizes at\n [step_size + 2, step_size + 4, step_size + 8, step_size + 16] to check vectorization.\n Note: The hidden size is restricted to 2 * 18432 for the batch size 16384 to avoid OOM.\n \"\"\"\n inputs = []\n if isinstance(dims, int):\n dims = [dims]\n\n for dim in dims:\n if dim == 2:\n input_ranges = []\n\n step_size = 256\n batch_range = [16, 512, 2048, 8192]\n\n # max_hidden_size = 4 * d_model_max (max hidden size in feedforward layers)\n # NOTE: (This is not applicable to the updated implementation but leaving it here for future updates).\n # Numpy arrays are not JSON serializable so convert them to enable storing benchmark data.\n\n hidden_range = []\n for hs in range(\n D_MODEL_MIN, 4 * D_MODEL_MAX + 1, step_size\n ): # (768, 4*18432)\n hidden_range.append(hs)\n if BENCHMARK_MODE == \"weekly\":\n # Additionally benchmark hidden sizes at steps (256 + 2, 256 + 4, 256 + 8, 256 + 16)\n hidden_range.extend([hs + 2, hs + 4, hs + 8, hs + 16])\n input_ranges.append((batch_range, hidden_range))\n\n # Reduce max hidden size for largest batch size (16384) to avoid OOM in RMSNorm.\n # Sweeps hidden sizes from # (768, 2*18432) or (768, 2*18432 + 16) for weekly.\n input_ranges.append(\n ([16384], filter(lambda hs: hs <= 2 * D_MODEL_MAX + 16, hidden_range))\n )\n\n for batch_range, hidden_range in input_ranges:\n inputs.extend(list(itertools.product(batch_range, hidden_range)))\n\n elif dim == 3:\n dim_range = [2**i for i in range(1, 10)]\n inputs.extend(list(itertools.product(dim_range, repeat=3)))\n elif dim == 4:\n # TODO: Add spatial_dim = 2.\n input_ranges = []\n\n batch_range = [2**i for i in range(1, 10)] # {2, 512}\n channel_range = [2**i for i in range(1, 8)] # {2, 128}\n spatial_range = [2**i for i in range(2, 7)] # {4, 64}\n input_ranges.append((batch_range, channel_range, spatial_range))\n\n batch_range = [2**i for i in range(1, 7)] # {2, 64}\n channel_range = [2**i for i in range(1, 6)] # {2, 32}\n spatial_range = [128, 256]\n input_ranges.append((batch_range, channel_range, spatial_range))\n\n # Resnet/ResNext sizes\n batch_range = [2**i for i in range(5, 9)] # {32, 256}\n channel_range = [2**i for i in range(6, 9)] # {64, 256}\n spatial_range = [7 * 2**i for i in range(5)] # {7, 112}\n input_ranges.append((batch_range, channel_range, spatial_range))\n\n for batch_range, channel_range, spatial_range in input_ranges:\n inputs.extend(\n [\n (n, c, hw, hw)\n for (n, c, hw) in itertools.product(\n batch_range, channel_range, spatial_range\n )\n ]\n )\n\n inputs.extend(\n [\n (n, c, hw, hw)\n for (n, (c, hw)) in itertools.product(\n [128, 256],\n [\n (512, 7),\n (512, 14),\n (512, 28),\n (1024, 7),\n (1024, 14),\n (2048, 7),\n ],\n )\n ]\n )\n\n else:\n raise NotImplementedError(\n f\"Generating input sizes of dimension {dim} is not implemented\"\n )\n if BENCHMARK_CONFIG[\"num_inputs\"] is not None:\n inputs = sample(inputs, BENCHMARK_CONFIG[\"num_inputs\"])\n\n return inputs\n\n\n# Utility function to generate input sizes for attention benchmarks.\ndef generate_attn_inputs():\n batch_range = [16, 32]\n seq_lengths = [2**i for i in range(2, 10)] # {4, 512}\n inputs = [\n (batch_size, seq_len, nh, n_embd)\n for (batch_size, seq_len, (nh, n_embd)) in itertools.product(\n batch_range, seq_lengths, LLM_CONFIGS\n )\n ]\n\n if BENCHMARK_CONFIG[\"num_inputs\"] is not None:\n inputs = sample(inputs, BENCHMARK_CONFIG[\"num_inputs\"])\n\n return inputs","source_hash":"b0a8d35825929a496b67479c5542c225820ce696ff5d76d67e5d89042b90bc17","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.global_params.generate_attn_inputs","uri":"program://Fuser/function/benchmarks.python.global_params.generate_attn_inputs#L161-L174","kind":"function","name":"generate_attn_inputs","path":"benchmarks/python/global_params.py","language":"python","start_line":161,"end_line":174,"context_start_line":141,"context_end_line":174,"code":" (512, 28),\n (1024, 7),\n (1024, 14),\n (2048, 7),\n ],\n )\n ]\n )\n\n else:\n raise NotImplementedError(\n f\"Generating input sizes of dimension {dim} is not implemented\"\n )\n if BENCHMARK_CONFIG[\"num_inputs\"] is not None:\n inputs = sample(inputs, BENCHMARK_CONFIG[\"num_inputs\"])\n\n return inputs\n\n\n# Utility function to generate input sizes for attention benchmarks.\ndef generate_attn_inputs():\n batch_range = [16, 32]\n seq_lengths = [2**i for i in range(2, 10)] # {4, 512}\n inputs = [\n (batch_size, seq_len, nh, n_embd)\n for (batch_size, seq_len, (nh, n_embd)) in itertools.product(\n batch_range, seq_lengths, LLM_CONFIGS\n )\n ]\n\n if BENCHMARK_CONFIG[\"num_inputs\"] is not None:\n inputs = sample(inputs, BENCHMARK_CONFIG[\"num_inputs\"])\n\n return inputs","source_hash":"b0a8d35825929a496b67479c5542c225820ce696ff5d76d67e5d89042b90bc17","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_many_segments_host","uri":"program://Fuser/module/benchmarks.python.host.test_many_segments_host#L1-L86","kind":"module","name":"benchmarks.python.host.test_many_segments_host","path":"benchmarks/python/host/test_many_segments_host.py","language":"python","start_line":1,"end_line":86,"context_start_line":1,"context_end_line":86,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType, PythonProfiler\nfrom ..core import run_benchmark\nimport torch\n\n\ndef many_matmul_fusion(fd: FusionDefinition) -> None:\n x = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n y = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n a = fd.ops.add(x, y)\n for _ in range(5):\n a_transpose = fd.ops.permute(a, [1, 0])\n matmul_out = fd.ops.matmul(a_transpose, y)\n add_out = fd.ops.add(a_transpose, y)\n a = fd.ops.add(matmul_out, add_out)\n fd.add_output(a)\n\n\n@pytest.mark.parametrize(\"host_bench_mode\", [\"compile\", \"steady\", \"dynamic\"])\ndef test_many_segment_benchmark(\n benchmark,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(5, 5, device=\"cuda\", dtype=torch.float) for _ in range(2)]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n # Note: Using these sizes to allow kernel reuse in dynamic.\n # Using sizes = [4, 8, 16, 32, 64, 128] led to heuristic mismatch and kernel recompilation.\n input_sizes = [5, 7, 9, 11]\n # Generate matrices of size x size dimensions\n inputs = [\n [\n torch.randn(size, size, device=\"cuda\", dtype=torch.float)\n for _ in range(2)\n ]\n for size in input_sizes\n ]\n\n with FusionDefinition() as fd:\n many_matmul_fusion(fd)\n\n def validate(input):\n x, y = input\n eager_output = x + y\n for _ in range(5):\n eager_transpose = eager_output.t()\n matmul_out = torch.matmul(eager_transpose, y)\n add_out = eager_transpose + y\n eager_output = matmul_out + add_out\n fd.validate(input, [eager_output])\n\n # Validate number of segments\n with PythonProfiler() as prof:\n fd.execute(input)\n num_segments = prof.profile.segments\n expected_segments = 12\n assert (\n num_segments == expected_segments\n ), f\"Expected {expected_segments} fusion segments, got {num_segments}.\"\n\n if not disable_validation:\n if host_bench_mode == \"dynamic\":\n # Run validate for all input sizes.\n for input in inputs:\n validate(input)\n else:\n validate(inputs)\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n None,\n inputs,\n device=f\"host:{host_bench_mode}\",\n fusion_fn=many_matmul_fusion,\n )","source_hash":"061026a239f0bc234390fc0fbab846af4af674d7e3191f3678ccb7a9510e4366","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_many_segments_host.many_matmul_fusion","uri":"program://Fuser/function/benchmarks.python.host.test_many_segments_host.many_matmul_fusion#L10-L23","kind":"function","name":"many_matmul_fusion","path":"benchmarks/python/host/test_many_segments_host.py","language":"python","start_line":10,"end_line":23,"context_start_line":1,"context_end_line":43,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType, PythonProfiler\nfrom ..core import run_benchmark\nimport torch\n\n\ndef many_matmul_fusion(fd: FusionDefinition) -> None:\n x = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n y = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n a = fd.ops.add(x, y)\n for _ in range(5):\n a_transpose = fd.ops.permute(a, [1, 0])\n matmul_out = fd.ops.matmul(a_transpose, y)\n add_out = fd.ops.add(a_transpose, y)\n a = fd.ops.add(matmul_out, add_out)\n fd.add_output(a)\n\n\n@pytest.mark.parametrize(\"host_bench_mode\", [\"compile\", \"steady\", \"dynamic\"])\ndef test_many_segment_benchmark(\n benchmark,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(5, 5, device=\"cuda\", dtype=torch.float) for _ in range(2)]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n # Note: Using these sizes to allow kernel reuse in dynamic.\n # Using sizes = [4, 8, 16, 32, 64, 128] led to heuristic mismatch and kernel recompilation.\n input_sizes = [5, 7, 9, 11]\n # Generate matrices of size x size dimensions\n inputs = [\n [\n torch.randn(size, size, device=\"cuda\", dtype=torch.float)","source_hash":"061026a239f0bc234390fc0fbab846af4af674d7e3191f3678ccb7a9510e4366","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_many_segments_host.test_many_segment_benchmark","uri":"program://Fuser/function/benchmarks.python.host.test_many_segments_host.test_many_segment_benchmark#L27-L86","kind":"function","name":"test_many_segment_benchmark","path":"benchmarks/python/host/test_many_segments_host.py","language":"python","start_line":27,"end_line":86,"context_start_line":7,"context_end_line":86,"code":"import torch\n\n\ndef many_matmul_fusion(fd: FusionDefinition) -> None:\n x = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n y = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n a = fd.ops.add(x, y)\n for _ in range(5):\n a_transpose = fd.ops.permute(a, [1, 0])\n matmul_out = fd.ops.matmul(a_transpose, y)\n add_out = fd.ops.add(a_transpose, y)\n a = fd.ops.add(matmul_out, add_out)\n fd.add_output(a)\n\n\n@pytest.mark.parametrize(\"host_bench_mode\", [\"compile\", \"steady\", \"dynamic\"])\ndef test_many_segment_benchmark(\n benchmark,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(5, 5, device=\"cuda\", dtype=torch.float) for _ in range(2)]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n # Note: Using these sizes to allow kernel reuse in dynamic.\n # Using sizes = [4, 8, 16, 32, 64, 128] led to heuristic mismatch and kernel recompilation.\n input_sizes = [5, 7, 9, 11]\n # Generate matrices of size x size dimensions\n inputs = [\n [\n torch.randn(size, size, device=\"cuda\", dtype=torch.float)\n for _ in range(2)\n ]\n for size in input_sizes\n ]\n\n with FusionDefinition() as fd:\n many_matmul_fusion(fd)\n\n def validate(input):\n x, y = input\n eager_output = x + y\n for _ in range(5):\n eager_transpose = eager_output.t()\n matmul_out = torch.matmul(eager_transpose, y)\n add_out = eager_transpose + y\n eager_output = matmul_out + add_out\n fd.validate(input, [eager_output])\n\n # Validate number of segments\n with PythonProfiler() as prof:\n fd.execute(input)\n num_segments = prof.profile.segments\n expected_segments = 12\n assert (\n num_segments == expected_segments\n ), f\"Expected {expected_segments} fusion segments, got {num_segments}.\"\n\n if not disable_validation:\n if host_bench_mode == \"dynamic\":\n # Run validate for all input sizes.\n for input in inputs:\n validate(input)\n else:\n validate(inputs)\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n None,\n inputs,\n device=f\"host:{host_bench_mode}\",\n fusion_fn=many_matmul_fusion,\n )","source_hash":"061026a239f0bc234390fc0fbab846af4af674d7e3191f3678ccb7a9510e4366","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_many_segments_host.validate","uri":"program://Fuser/function/benchmarks.python.host.test_many_segments_host.validate#L52-L69","kind":"function","name":"validate","path":"benchmarks/python/host/test_many_segments_host.py","language":"python","start_line":52,"end_line":69,"context_start_line":32,"context_end_line":86,"code":"):\n inputs = [torch.randn(5, 5, device=\"cuda\", dtype=torch.float) for _ in range(2)]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n # Note: Using these sizes to allow kernel reuse in dynamic.\n # Using sizes = [4, 8, 16, 32, 64, 128] led to heuristic mismatch and kernel recompilation.\n input_sizes = [5, 7, 9, 11]\n # Generate matrices of size x size dimensions\n inputs = [\n [\n torch.randn(size, size, device=\"cuda\", dtype=torch.float)\n for _ in range(2)\n ]\n for size in input_sizes\n ]\n\n with FusionDefinition() as fd:\n many_matmul_fusion(fd)\n\n def validate(input):\n x, y = input\n eager_output = x + y\n for _ in range(5):\n eager_transpose = eager_output.t()\n matmul_out = torch.matmul(eager_transpose, y)\n add_out = eager_transpose + y\n eager_output = matmul_out + add_out\n fd.validate(input, [eager_output])\n\n # Validate number of segments\n with PythonProfiler() as prof:\n fd.execute(input)\n num_segments = prof.profile.segments\n expected_segments = 12\n assert (\n num_segments == expected_segments\n ), f\"Expected {expected_segments} fusion segments, got {num_segments}.\"\n\n if not disable_validation:\n if host_bench_mode == \"dynamic\":\n # Run validate for all input sizes.\n for input in inputs:\n validate(input)\n else:\n validate(inputs)\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n None,\n inputs,\n device=f\"host:{host_bench_mode}\",\n fusion_fn=many_matmul_fusion,\n )","source_hash":"061026a239f0bc234390fc0fbab846af4af674d7e3191f3678ccb7a9510e4366","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_many_pointwise_ops_host","uri":"program://Fuser/module/benchmarks.python.host.test_many_pointwise_ops_host#L1-L83","kind":"module","name":"benchmarks.python.host.test_many_pointwise_ops_host","path":"benchmarks/python/host/test_many_pointwise_ops_host.py","language":"python","start_line":1,"end_line":83,"context_start_line":1,"context_end_line":83,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom ..core import run_benchmark\nimport torch\nfrom ..global_params import PROMOTE_DTYPES\nfrom functools import partial\n\n\ndef pointwise_ops_fusion(fd: FusionDefinition, dtype: DataType, num_iters: int):\n x = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n y = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n x = fd.ops.cast(x, dtype=DataType.Float)\n y = fd.ops.cast(y, dtype=DataType.Float)\n\n a = fd.ops.add(x, y)\n for _ in range(num_iters):\n x = fd.ops.cos(a)\n y = fd.ops.sin(a)\n a = fd.ops.add(x, y)\n\n if dtype in PROMOTE_DTYPES:\n a = fd.ops.cast(a, dtype=dtype)\n fd.add_output(a)\n\n\n# TODO: num_iters 32 and 128 are restricted due to issue #5531.\n# NOTE: 22 is the largest, runnable num_iters without timeout.\n@pytest.mark.parametrize(\"num_iters\", [2, 8, 16, 22])\n@pytest.mark.parametrize(\"host_bench_mode\", [\"compile\", \"steady\", \"dynamic\"])\ndef test_pointwise_ops_benchmark(\n benchmark,\n num_iters: int,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(13, device=\"cuda\", dtype=torch.float16) for _ in range(2)]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n input_sizes = [5, 10, 13, 15, 17, 20]\n inputs = [\n [torch.randn(size, device=\"cuda\", dtype=torch.float16) for _ in range(2)]\n for size in input_sizes\n ]\n\n with FusionDefinition() as fd:\n pointwise_ops_fusion(fd, torch_dtype_to_nvfuser_dtype(torch.float16), num_iters)\n\n def validate(input):\n eager_output = input[0] + input[1]\n for _ in range(num_iters):\n x = torch.cos(eager_output)\n y = torch.sin(eager_output)\n eager_output = x + y\n fd.validate(input, [eager_output])\n\n if not disable_validation:\n if host_bench_mode == \"dynamic\":\n # Run validate for all input sizes.\n for input in inputs:\n validate(input)\n else:\n validate(inputs)\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n None,\n inputs,\n device=f\"host:{host_bench_mode}\",\n fusion_fn=partial(\n pointwise_ops_fusion,\n dtype=torch_dtype_to_nvfuser_dtype(torch.float16),\n num_iters=num_iters,\n ),\n )","source_hash":"ad55953e2a586d1e39a5eb787cef142707a697376c9cfcb4631e9dd86524a702","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_many_pointwise_ops_host.pointwise_ops_fusion","uri":"program://Fuser/function/benchmarks.python.host.test_many_pointwise_ops_host.pointwise_ops_fusion#L13-L29","kind":"function","name":"pointwise_ops_fusion","path":"benchmarks/python/host/test_many_pointwise_ops_host.py","language":"python","start_line":13,"end_line":29,"context_start_line":1,"context_end_line":49,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom ..core import run_benchmark\nimport torch\nfrom ..global_params import PROMOTE_DTYPES\nfrom functools import partial\n\n\ndef pointwise_ops_fusion(fd: FusionDefinition, dtype: DataType, num_iters: int):\n x = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n y = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n x = fd.ops.cast(x, dtype=DataType.Float)\n y = fd.ops.cast(y, dtype=DataType.Float)\n\n a = fd.ops.add(x, y)\n for _ in range(num_iters):\n x = fd.ops.cos(a)\n y = fd.ops.sin(a)\n a = fd.ops.add(x, y)\n\n if dtype in PROMOTE_DTYPES:\n a = fd.ops.cast(a, dtype=dtype)\n fd.add_output(a)\n\n\n# TODO: num_iters 32 and 128 are restricted due to issue #5531.\n# NOTE: 22 is the largest, runnable num_iters without timeout.\n@pytest.mark.parametrize(\"num_iters\", [2, 8, 16, 22])\n@pytest.mark.parametrize(\"host_bench_mode\", [\"compile\", \"steady\", \"dynamic\"])\ndef test_pointwise_ops_benchmark(\n benchmark,\n num_iters: int,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(13, device=\"cuda\", dtype=torch.float16) for _ in range(2)]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n input_sizes = [5, 10, 13, 15, 17, 20]\n inputs = [\n [torch.randn(size, device=\"cuda\", dtype=torch.float16) for _ in range(2)]","source_hash":"ad55953e2a586d1e39a5eb787cef142707a697376c9cfcb4631e9dd86524a702","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_many_pointwise_ops_host.test_pointwise_ops_benchmark","uri":"program://Fuser/function/benchmarks.python.host.test_many_pointwise_ops_host.test_pointwise_ops_benchmark#L36-L83","kind":"function","name":"test_pointwise_ops_benchmark","path":"benchmarks/python/host/test_many_pointwise_ops_host.py","language":"python","start_line":36,"end_line":83,"context_start_line":16,"context_end_line":83,"code":"\n if dtype in PROMOTE_DTYPES:\n x = fd.ops.cast(x, dtype=DataType.Float)\n y = fd.ops.cast(y, dtype=DataType.Float)\n\n a = fd.ops.add(x, y)\n for _ in range(num_iters):\n x = fd.ops.cos(a)\n y = fd.ops.sin(a)\n a = fd.ops.add(x, y)\n\n if dtype in PROMOTE_DTYPES:\n a = fd.ops.cast(a, dtype=dtype)\n fd.add_output(a)\n\n\n# TODO: num_iters 32 and 128 are restricted due to issue #5531.\n# NOTE: 22 is the largest, runnable num_iters without timeout.\n@pytest.mark.parametrize(\"num_iters\", [2, 8, 16, 22])\n@pytest.mark.parametrize(\"host_bench_mode\", [\"compile\", \"steady\", \"dynamic\"])\ndef test_pointwise_ops_benchmark(\n benchmark,\n num_iters: int,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(13, device=\"cuda\", dtype=torch.float16) for _ in range(2)]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n input_sizes = [5, 10, 13, 15, 17, 20]\n inputs = [\n [torch.randn(size, device=\"cuda\", dtype=torch.float16) for _ in range(2)]\n for size in input_sizes\n ]\n\n with FusionDefinition() as fd:\n pointwise_ops_fusion(fd, torch_dtype_to_nvfuser_dtype(torch.float16), num_iters)\n\n def validate(input):\n eager_output = input[0] + input[1]\n for _ in range(num_iters):\n x = torch.cos(eager_output)\n y = torch.sin(eager_output)\n eager_output = x + y\n fd.validate(input, [eager_output])\n\n if not disable_validation:\n if host_bench_mode == \"dynamic\":\n # Run validate for all input sizes.\n for input in inputs:\n validate(input)\n else:\n validate(inputs)\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n None,\n inputs,\n device=f\"host:{host_bench_mode}\",\n fusion_fn=partial(\n pointwise_ops_fusion,\n dtype=torch_dtype_to_nvfuser_dtype(torch.float16),\n num_iters=num_iters,\n ),\n )","source_hash":"ad55953e2a586d1e39a5eb787cef142707a697376c9cfcb4631e9dd86524a702","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_many_pointwise_ops_host.validate","uri":"program://Fuser/function/benchmarks.python.host.test_many_pointwise_ops_host.validate#L56-L62","kind":"function","name":"validate","path":"benchmarks/python/host/test_many_pointwise_ops_host.py","language":"python","start_line":56,"end_line":62,"context_start_line":36,"context_end_line":82,"code":"def test_pointwise_ops_benchmark(\n benchmark,\n num_iters: int,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n inputs = [torch.randn(13, device=\"cuda\", dtype=torch.float16) for _ in range(2)]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n input_sizes = [5, 10, 13, 15, 17, 20]\n inputs = [\n [torch.randn(size, device=\"cuda\", dtype=torch.float16) for _ in range(2)]\n for size in input_sizes\n ]\n\n with FusionDefinition() as fd:\n pointwise_ops_fusion(fd, torch_dtype_to_nvfuser_dtype(torch.float16), num_iters)\n\n def validate(input):\n eager_output = input[0] + input[1]\n for _ in range(num_iters):\n x = torch.cos(eager_output)\n y = torch.sin(eager_output)\n eager_output = x + y\n fd.validate(input, [eager_output])\n\n if not disable_validation:\n if host_bench_mode == \"dynamic\":\n # Run validate for all input sizes.\n for input in inputs:\n validate(input)\n else:\n validate(inputs)\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n None,\n inputs,\n device=f\"host:{host_bench_mode}\",\n fusion_fn=partial(\n pointwise_ops_fusion,\n dtype=torch_dtype_to_nvfuser_dtype(torch.float16),\n num_iters=num_iters,\n ),","source_hash":"ad55953e2a586d1e39a5eb787cef142707a697376c9cfcb4631e9dd86524a702","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_adaptive_layernorm_host","uri":"program://Fuser/module/benchmarks.python.host.test_adaptive_layernorm_host#L1-L137","kind":"module","name":"benchmarks.python.host.test_adaptive_layernorm_host","path":"benchmarks/python/host/test_adaptive_layernorm_host.py","language":"python","start_line":1,"end_line":137,"context_start_line":1,"context_end_line":137,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom ..core import run_benchmark\nimport torch\n\n\ndef adaptive_layernorm_fwd_fusion(fd: FusionDefinition, eps: float = 1e-6) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.ops.cast(T0, dtype=DataType.Float)\n T4, T5 = fd.ops.var_mean(T3, dims=[2], correction=0, keepdim=False)\n T10 = fd.ops.broadcast_in_dim(\n T4, shape=[T0.size(0), T0.size(1), 1], broadcast_dims=[0, 1]\n )\n T15 = fd.ops.broadcast_in_dim(\n T5, shape=[T0.size(0), T0.size(1), 1], broadcast_dims=[0, 1]\n )\n S16 = fd.define_scalar(eps, dtype=DataType.Double)\n T17 = fd.ops.add(T10, S16)\n T22 = fd.ops.broadcast_in_dim(T15, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T23 = fd.ops.rsqrt(T17)\n T24 = fd.ops.sub(T3, T22)\n T29 = fd.ops.broadcast_in_dim(T23, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T30 = fd.ops.mul(T24, T29)\n T35 = fd.ops.reshape(T1, new_shape=[T1.size(0), 1, T1.size(1)])\n T36 = fd.ops.cast(T35, dtype=DataType.Float)\n S37 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T38 = fd.ops.add(S37, T36)\n T39 = fd.ops.cast(T38, dtype=DataType.Half)\n T44 = fd.ops.broadcast_in_dim(T39, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T45 = fd.ops.cast(T44, dtype=DataType.Float)\n T46 = fd.ops.mul(T30, T45)\n T51 = fd.ops.reshape(T2, new_shape=[T2.size(0), 1, T2.size(1)])\n T56 = fd.ops.broadcast_in_dim(T51, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T57 = fd.ops.cast(T56, dtype=DataType.Float)\n T58 = fd.ops.add(T46, T57)\n T59 = fd.ops.cast(T58, dtype=DataType.Half)\n fd.add_output(T5)\n fd.add_output(T23)\n fd.add_output(T59)\n\n\n# This benchmark is to particularly track nvFuser host overhead for shape\n# change (dynamic shape support) in the adapative layernorm case. Running a\n# new shape on this fusion without recompiling a new kernel can have significant overhead.\n@pytest.mark.parametrize(\"host_bench_mode\", [\"compile\", \"steady\", \"dynamic\"])\ndef test_adaptive_layernorm_fwd_benchmark(\n benchmark,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n B = 1\n T = 30 * 1024\n D = 1024\n inputs = [\n torch.randn(B, T, D, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n ]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n inputs = []\n for B in range(1, 3, 1):\n for T in range(30 * 1024, 30 * 1024 + 5 * 128, 128):\n inputs.append(\n [\n torch.randn(\n B,\n T,\n D,\n device=\"cuda\",\n dtype=torch.float16,\n requires_grad=True,\n ),\n torch.randn(\n B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True\n ),\n torch.randn(\n B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True\n ),\n ]\n )\n\n with FusionDefinition() as fd:\n adaptive_layernorm_fwd_fusion(fd)\n\n def validate(input):\n eps = 1e-6\n in_tensor, scale, shift = input\n norm_state = torch.nn.LayerNorm(D, elementwise_affine=False, eps=eps)\n norm_out = norm_state(in_tensor)\n mean = in_tensor.to(torch.float).mean(dim=-1)\n variance = in_tensor.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(-1)\n eager_output = norm_out * (1 + scale.view(-1, 1, D)) + shift.view(-1, 1, D)\n fd.validate(input, [mean, invstd, eager_output])\n\n if not disable_validation:\n if host_bench_mode == \"dynamic\":\n # Run validate for all input sizes.\n for input in inputs:\n validate(input)\n else:\n validate(inputs)\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n None,\n inputs,\n device=f\"host:{host_bench_mode}\",\n fusion_fn=adaptive_layernorm_fwd_fusion,\n )","source_hash":"b6c00e8f4d19d442976e6f3463c40f689f4325596bb2fda1a801eb54f8cc0481","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_adaptive_layernorm_host.adaptive_layernorm_fwd_fusion","uri":"program://Fuser/function/benchmarks.python.host.test_adaptive_layernorm_host.adaptive_layernorm_fwd_fusion#L10-L62","kind":"function","name":"adaptive_layernorm_fwd_fusion","path":"benchmarks/python/host/test_adaptive_layernorm_host.py","language":"python","start_line":10,"end_line":62,"context_start_line":1,"context_end_line":82,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom ..core import run_benchmark\nimport torch\n\n\ndef adaptive_layernorm_fwd_fusion(fd: FusionDefinition, eps: float = 1e-6) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T2 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[1, 0],\n )\n T3 = fd.ops.cast(T0, dtype=DataType.Float)\n T4, T5 = fd.ops.var_mean(T3, dims=[2], correction=0, keepdim=False)\n T10 = fd.ops.broadcast_in_dim(\n T4, shape=[T0.size(0), T0.size(1), 1], broadcast_dims=[0, 1]\n )\n T15 = fd.ops.broadcast_in_dim(\n T5, shape=[T0.size(0), T0.size(1), 1], broadcast_dims=[0, 1]\n )\n S16 = fd.define_scalar(eps, dtype=DataType.Double)\n T17 = fd.ops.add(T10, S16)\n T22 = fd.ops.broadcast_in_dim(T15, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T23 = fd.ops.rsqrt(T17)\n T24 = fd.ops.sub(T3, T22)\n T29 = fd.ops.broadcast_in_dim(T23, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T30 = fd.ops.mul(T24, T29)\n T35 = fd.ops.reshape(T1, new_shape=[T1.size(0), 1, T1.size(1)])\n T36 = fd.ops.cast(T35, dtype=DataType.Float)\n S37 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T38 = fd.ops.add(S37, T36)\n T39 = fd.ops.cast(T38, dtype=DataType.Half)\n T44 = fd.ops.broadcast_in_dim(T39, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T45 = fd.ops.cast(T44, dtype=DataType.Float)\n T46 = fd.ops.mul(T30, T45)\n T51 = fd.ops.reshape(T2, new_shape=[T2.size(0), 1, T2.size(1)])\n T56 = fd.ops.broadcast_in_dim(T51, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T57 = fd.ops.cast(T56, dtype=DataType.Float)\n T58 = fd.ops.add(T46, T57)\n T59 = fd.ops.cast(T58, dtype=DataType.Half)\n fd.add_output(T5)\n fd.add_output(T23)\n fd.add_output(T59)\n\n\n# This benchmark is to particularly track nvFuser host overhead for shape\n# change (dynamic shape support) in the adapative layernorm case. Running a\n# new shape on this fusion without recompiling a new kernel can have significant overhead.\n@pytest.mark.parametrize(\"host_bench_mode\", [\"compile\", \"steady\", \"dynamic\"])\ndef test_adaptive_layernorm_fwd_benchmark(\n benchmark,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n B = 1\n T = 30 * 1024\n D = 1024\n inputs = [\n torch.randn(B, T, D, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n ]","source_hash":"b6c00e8f4d19d442976e6f3463c40f689f4325596bb2fda1a801eb54f8cc0481","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_adaptive_layernorm_host.test_adaptive_layernorm_fwd_benchmark","uri":"program://Fuser/function/benchmarks.python.host.test_adaptive_layernorm_host.test_adaptive_layernorm_fwd_benchmark#L69-L137","kind":"function","name":"test_adaptive_layernorm_fwd_benchmark","path":"benchmarks/python/host/test_adaptive_layernorm_host.py","language":"python","start_line":69,"end_line":137,"context_start_line":49,"context_end_line":137,"code":" S37 = fd.define_scalar(1.00000, dtype=DataType.Double)\n T38 = fd.ops.add(S37, T36)\n T39 = fd.ops.cast(T38, dtype=DataType.Half)\n T44 = fd.ops.broadcast_in_dim(T39, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T45 = fd.ops.cast(T44, dtype=DataType.Float)\n T46 = fd.ops.mul(T30, T45)\n T51 = fd.ops.reshape(T2, new_shape=[T2.size(0), 1, T2.size(1)])\n T56 = fd.ops.broadcast_in_dim(T51, shape=T0.shape(), broadcast_dims=[0, 1, 2])\n T57 = fd.ops.cast(T56, dtype=DataType.Float)\n T58 = fd.ops.add(T46, T57)\n T59 = fd.ops.cast(T58, dtype=DataType.Half)\n fd.add_output(T5)\n fd.add_output(T23)\n fd.add_output(T59)\n\n\n# This benchmark is to particularly track nvFuser host overhead for shape\n# change (dynamic shape support) in the adapative layernorm case. Running a\n# new shape on this fusion without recompiling a new kernel can have significant overhead.\n@pytest.mark.parametrize(\"host_bench_mode\", [\"compile\", \"steady\", \"dynamic\"])\ndef test_adaptive_layernorm_fwd_benchmark(\n benchmark,\n host_bench_mode: str,\n disable_validation: bool,\n disable_benchmarking: bool,\n):\n B = 1\n T = 30 * 1024\n D = 1024\n inputs = [\n torch.randn(B, T, D, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n torch.randn(B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True),\n ]\n\n # Generate multiple inputs to measure dynamic shape overhead.\n if host_bench_mode == \"dynamic\":\n inputs = []\n for B in range(1, 3, 1):\n for T in range(30 * 1024, 30 * 1024 + 5 * 128, 128):\n inputs.append(\n [\n torch.randn(\n B,\n T,\n D,\n device=\"cuda\",\n dtype=torch.float16,\n requires_grad=True,\n ),\n torch.randn(\n B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True\n ),\n torch.randn(\n B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True\n ),\n ]\n )\n\n with FusionDefinition() as fd:\n adaptive_layernorm_fwd_fusion(fd)\n\n def validate(input):\n eps = 1e-6\n in_tensor, scale, shift = input\n norm_state = torch.nn.LayerNorm(D, elementwise_affine=False, eps=eps)\n norm_out = norm_state(in_tensor)\n mean = in_tensor.to(torch.float).mean(dim=-1)\n variance = in_tensor.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(-1)\n eager_output = norm_out * (1 + scale.view(-1, 1, D)) + shift.view(-1, 1, D)\n fd.validate(input, [mean, invstd, eager_output])\n\n if not disable_validation:\n if host_bench_mode == \"dynamic\":\n # Run validate for all input sizes.\n for input in inputs:\n validate(input)\n else:\n validate(inputs)\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n None,\n inputs,\n device=f\"host:{host_bench_mode}\",\n fusion_fn=adaptive_layernorm_fwd_fusion,\n )","source_hash":"b6c00e8f4d19d442976e6f3463c40f689f4325596bb2fda1a801eb54f8cc0481","truncated":false} {"repo_id":"Fuser","entity_id":"py:benchmarks.python.host.test_adaptive_layernorm_host.validate","uri":"program://Fuser/function/benchmarks.python.host.test_adaptive_layernorm_host.validate#L111-L120","kind":"function","name":"validate","path":"benchmarks/python/host/test_adaptive_layernorm_host.py","language":"python","start_line":111,"end_line":120,"context_start_line":91,"context_end_line":137,"code":" torch.randn(\n B,\n T,\n D,\n device=\"cuda\",\n dtype=torch.float16,\n requires_grad=True,\n ),\n torch.randn(\n B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True\n ),\n torch.randn(\n B, D, device=\"cuda\", dtype=torch.float16, requires_grad=True\n ),\n ]\n )\n\n with FusionDefinition() as fd:\n adaptive_layernorm_fwd_fusion(fd)\n\n def validate(input):\n eps = 1e-6\n in_tensor, scale, shift = input\n norm_state = torch.nn.LayerNorm(D, elementwise_affine=False, eps=eps)\n norm_out = norm_state(in_tensor)\n mean = in_tensor.to(torch.float).mean(dim=-1)\n variance = in_tensor.to(torch.float).var(dim=-1, unbiased=False)\n invstd = (1.0 / torch.sqrt(variance + eps)).unsqueeze(-1)\n eager_output = norm_out * (1 + scale.view(-1, 1, D)) + shift.view(-1, 1, D)\n fd.validate(input, [mean, invstd, eager_output])\n\n if not disable_validation:\n if host_bench_mode == \"dynamic\":\n # Run validate for all input sizes.\n for input in inputs:\n validate(input)\n else:\n validate(inputs)\n\n if not disable_benchmarking:\n run_benchmark(\n benchmark,\n None,\n inputs,\n device=f\"host:{host_bench_mode}\",\n fusion_fn=adaptive_layernorm_fwd_fusion,\n )","source_hash":"b6c00e8f4d19d442976e6f3463c40f689f4325596bb2fda1a801eb54f8cc0481","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.setup","uri":"program://Fuser/module/python.setup#L1-L110","kind":"module","name":"python.setup","path":"python/setup.py","language":"python","start_line":1,"end_line":110,"context_start_line":1,"context_end_line":110,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# Usage:\n# pip install --no-build-isolation -e python -v\n# This build command is equivalent to: python setup.py develop\n# Options:\n# -v: verbose output\n# --no-build-isolation: don't build in a temporary directory\n# -e: install in development mode\n#\n# Environment variables used during build:\n# MAX_JOBS\n# maximum number of compile jobs we should use to compile your code\n#\n# NVFUSER_BUILD_CMAKE_ONLY\n# Only generate ./build directory with cmake setup\n#\n# NVFUSER_BUILD_NO_PYTHON\n# Skips python API target `libnvfuser.so`, i.e. `_C.cpython-xxx.so`\n#\n# NVFUSER_BUILD_NO_TEST\n# Skips cpp tests `test_nvfuser`\n#\n# NVFUSER_BUILD_NO_BENCHMARK\n# Skips benchmark target `nvfuser_bench`\n#\n# NVFUSER_BUILD_NO_NINJA\n# In case you want to use make instead of ninja for build\n#\n# NVFUSER_BUILD_WITH_UCC\n# Build nvfuser with UCC support. You may need to specify environment variables of UCC_HOME, UCC_DIR, UCX_HOME, UCX_DIR.\n#\n# NVFUSER_BUILD_WITHOUT_DISTRIBUTED\n# Build nvfuser without multidevice support\n#\n# NVFUSER_BUILD_BUILD_TYPE=Debug\n# Building nvfuser in debug mode\n#\n# NVFUSER_BUILD_BUILD_TYPE=RelwithDebInfo\n# Building nvfuser in release mode with debug info, a.k.a. RelwithDebInfo\n#\n# NVFUSER_BUILD_DIR=\n# Specify in which directory to build nvfuser. If not specified, the default build directory is \"./build\".\n#\n# NVFUSER_BUILD_INSTALL_DIR=\n# Specify in which directory to install nvfuser. If not specified, the default install directory is \"./python/nvfuser\".\n#\n# NVFUSER_BUILD_VERSION_TAG=TAG\n# Specify the tag for build nvfuser version, this is used for pip wheel\n# package nightly where we might want to add a date tag\n# nvfuser-VERSION+TAG+gitSHA1-....-whl\n#\n# NVFUSER_BUILD_INSTALL_REQUIRES=pkg0[,pkg1...]\n# this is used for pip wheel build to specify package required for install\n# e.g. NVFUSER_BUILD_INSTALL_REQUIRES=nvidia-cuda-nvrtc-cu12\n#\n# NVFUSER_BUILD_NVMMH_INCLUDE_DIR=\n# Specify the location to find nvMatmulHeuristics.h\n#\n# NVFUSER_BUILD_WHEEL_NAME=NAME\n# Specify the wheel name this is used for pip wheel package where we want\n# to identify the cuda toolkit version\n#\n# NVFUSER_BUILD_CPP_STANDARD=STANDARD\n# Specify the C++ standard to use for building nvfuser. The default is C++20.\n#\n# NVFUSER_BUILD_ENABLE_PCH=1\n# Enable precompiled headers to speed up compilation. Default is OFF.\n#\n\nimport sys\n\nfrom utils import (\n BuildConfig,\n run,\n override_build_config_from_env,\n)\n\n\ndef version_tag(config):\n from tools.gen_nvfuser_version import get_version\n\n version = get_version()\n if config.overwrite_version:\n version = version.split(\"+\")[0]\n if len(config.version_tag) != 0:\n # use \".\" to be pypi friendly\n version = \".\".join([version, config.version_tag])\n return version\n\n\ndef main():\n config = BuildConfig()\n # Override build config from environment variables.\n override_build_config_from_env(config)\n\n if \"clean\" in sys.argv:\n # only disables BUILD_SETUP, but keep the argument for setuptools\n config.build_setup = False\n\n if config.cpp_standard < 20:\n raise ValueError(\"nvfuser requires C++20 standard or higher\")\n\n run(config, version_tag(config), relative_path=\"..\")\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"75afc77fdf9b893659087ed15cd2a8a5a2e77b914643223a73a8090abeec09c3","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.setup.version_tag","uri":"program://Fuser/function/python.setup.version_tag#L82-L91","kind":"function","name":"version_tag","path":"python/setup.py","language":"python","start_line":82,"end_line":91,"context_start_line":62,"context_end_line":110,"code":"# NVFUSER_BUILD_WHEEL_NAME=NAME\n# Specify the wheel name this is used for pip wheel package where we want\n# to identify the cuda toolkit version\n#\n# NVFUSER_BUILD_CPP_STANDARD=STANDARD\n# Specify the C++ standard to use for building nvfuser. The default is C++20.\n#\n# NVFUSER_BUILD_ENABLE_PCH=1\n# Enable precompiled headers to speed up compilation. Default is OFF.\n#\n\nimport sys\n\nfrom utils import (\n BuildConfig,\n run,\n override_build_config_from_env,\n)\n\n\ndef version_tag(config):\n from tools.gen_nvfuser_version import get_version\n\n version = get_version()\n if config.overwrite_version:\n version = version.split(\"+\")[0]\n if len(config.version_tag) != 0:\n # use \".\" to be pypi friendly\n version = \".\".join([version, config.version_tag])\n return version\n\n\ndef main():\n config = BuildConfig()\n # Override build config from environment variables.\n override_build_config_from_env(config)\n\n if \"clean\" in sys.argv:\n # only disables BUILD_SETUP, but keep the argument for setuptools\n config.build_setup = False\n\n if config.cpp_standard < 20:\n raise ValueError(\"nvfuser requires C++20 standard or higher\")\n\n run(config, version_tag(config), relative_path=\"..\")\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"75afc77fdf9b893659087ed15cd2a8a5a2e77b914643223a73a8090abeec09c3","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.setup.main","uri":"program://Fuser/function/python.setup.main#L94-L106","kind":"function","name":"main","path":"python/setup.py","language":"python","start_line":94,"end_line":106,"context_start_line":74,"context_end_line":110,"code":"\nfrom utils import (\n BuildConfig,\n run,\n override_build_config_from_env,\n)\n\n\ndef version_tag(config):\n from tools.gen_nvfuser_version import get_version\n\n version = get_version()\n if config.overwrite_version:\n version = version.split(\"+\")[0]\n if len(config.version_tag) != 0:\n # use \".\" to be pypi friendly\n version = \".\".join([version, config.version_tag])\n return version\n\n\ndef main():\n config = BuildConfig()\n # Override build config from environment variables.\n override_build_config_from_env(config)\n\n if \"clean\" in sys.argv:\n # only disables BUILD_SETUP, but keep the argument for setuptools\n config.build_setup = False\n\n if config.cpp_standard < 20:\n raise ValueError(\"nvfuser requires C++20 standard or higher\")\n\n run(config, version_tag(config), relative_path=\"..\")\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"75afc77fdf9b893659087ed15cd2a8a5a2e77b914643223a73a8090abeec09c3","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils","uri":"program://Fuser/module/python.utils#L1-L419","kind":"module","name":"python.utils","path":"python/utils.py","language":"python","start_line":1,"end_line":419,"context_start_line":1,"context_end_line":419,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\nimport multiprocessing\nimport subprocess\nimport sys\nimport shutil\nfrom dataclasses import dataclass, field\nimport setuptools.command.build_ext\n\n\n@dataclass\nclass BuildConfig:\n cmake_only: bool = False\n build_setup: bool = True\n no_python: bool = False\n no_cutlass: bool = False\n no_test: bool = False\n no_benchmark: bool = False\n no_ninja: bool = False\n build_with_ucc: bool = False\n build_with_asan: bool = False\n build_without_distributed: bool = False\n explicit_error_check: bool = False\n overwrite_version: bool = False\n version_tag: str = None\n build_type: str = \"Release\"\n wheel_name: str = \"nvfuser\"\n nvmmh_include_dir: str = \"\"\n build_dir: str = \"\"\n install_dir: str = \"\"\n install_requires: list = field(default_factory=list)\n extras_require: dict = field(default_factory=dict)\n cpp_standard: int = 20\n cutlass_max_jobs: int | None = None\n enable_pch: bool = False\n\n\ndef check_env_flag_bool_default(name: str, default: str = \"\") -> bool:\n if name not in os.environ:\n return default\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\ndef get_env_flag_bool(name: str) -> bool:\n assert name in os.environ\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\n# Override BuildConfig with environment variables. Only change if variable\n# exists. Do not use default to override argparse.\ndef override_build_config_from_env(config):\n # Command line arguments don't work on PEP517 builds and will be silently ignored,\n # so we need to pass those options as environment variables instead.\n if \"NVFUSER_BUILD_CMAKE_ONLY\" in os.environ:\n config.cmake_only = get_env_flag_bool(\"NVFUSER_BUILD_CMAKE_ONLY\")\n if \"NVFUSER_BUILD_SETUP\" in os.environ:\n config.build_setup = get_env_flag_bool(\"NVFUSER_BUILD_SETUP\")\n if \"NVFUSER_BUILD_NO_PYTHON\" in os.environ:\n config.no_python = get_env_flag_bool(\"NVFUSER_BUILD_NO_PYTHON\")\n if \"NVFUSER_BUILD_NO_CUTLASS\" in os.environ:\n config.no_cutlass = get_env_flag_bool(\"NVFUSER_BUILD_NO_CUTLASS\")\n if \"NVFUSER_BUILD_NO_TEST\" in os.environ:\n config.no_test = get_env_flag_bool(\"NVFUSER_BUILD_NO_TEST\")\n if \"NVFUSER_BUILD_NO_BENCHMARK\" in os.environ:\n config.no_benchmark = get_env_flag_bool(\"NVFUSER_BUILD_NO_BENCHMARK\")\n if \"NVFUSER_BUILD_NO_NINJA\" in os.environ:\n config.no_ninja = get_env_flag_bool(\"NVFUSER_BUILD_NO_NINJA\")\n if \"NVFUSER_BUILD_WITH_UCC\" in os.environ:\n config.build_with_ucc = get_env_flag_bool(\"NVFUSER_BUILD_WITH_UCC\")\n if \"NVFUSER_BUILD_WITH_ASAN\" in os.environ:\n config.build_with_asan = get_env_flag_bool(\"NVFUSER_BUILD_WITH_ASAN\")\n if \"NVFUSER_BUILD_WITHOUT_DISTRIBUTED\" in os.environ:\n config.build_without_distributed = get_env_flag_bool(\n \"NVFUSER_BUILD_WITHOUT_DISTRIBUTED\"\n )\n if \"NVFUSER_BUILD_EXPLICIT_ERROR_CHECK\" in os.environ:\n config.explicit_error_check = get_env_flag_bool(\n \"NVFUSER_BUILD_EXPLICIT_ERROR_CHECK\"\n )\n if \"NVFUSER_BUILD_OVERWRITE_VERSION\" in os.environ:\n config.overwrite_version = get_env_flag_bool(\"NVFUSER_BUILD_OVERWRITE_VERSION\")\n if \"NVFUSER_BUILD_VERSION_TAG\" in os.environ:\n config.version_tag = os.getenv(\"NVFUSER_BUILD_VERSION_TAG\")\n if \"NVFUSER_BUILD_BUILD_TYPE\" in os.environ:\n config.build_type = os.getenv(\"NVFUSER_BUILD_BUILD_TYPE\")\n if \"NVFUSER_BUILD_WHEEL_NAME\" in os.environ:\n config.wheel_name = os.getenv(\"NVFUSER_BUILD_WHEEL_NAME\")\n if \"NVFUSER_BUILD_DIR\" in os.environ:\n config.build_dir = os.getenv(\"NVFUSER_BUILD_DIR\")\n if \"NVFUSER_BUILD_INSTALL_DIR\" in os.environ:\n config.install_dir = os.getenv(\"NVFUSER_BUILD_INSTALL_DIR\")\n if \"NVFUSER_BUILD_INSTALL_REQUIRES\" in os.environ:\n config.install_requires = os.getenv(\"NVFUSER_BUILD_INSTALL_REQUIRES\").split(\",\")\n if \"NVFUSER_BUILD_EXTRAS_REQUIRE\" in os.environ:\n config.extras_require = eval(os.getenv(\"NVFUSER_BUILD_EXTRAS_REQUIRE\"))\n if \"NVFUSER_BUILD_CPP_STANDARD\" in os.environ:\n config.cpp_standard = int(os.getenv(\"NVFUSER_BUILD_CPP_STANDARD\"))\n if \"NVFUSER_BUILD_VERSION_TAG\" in os.environ:\n config.overwrite_version = True\n config.version_tag = os.getenv(\"NVFUSER_BUILD_VERSION_TAG\")\n if \"NVFUSER_CUTLASS_MAX_JOBS\" in os.environ:\n config.cutlass_max_jobs = int(os.getenv(\"NVFUSER_CUTLASS_MAX_JOBS\"))\n if \"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\" in os.environ:\n config.nvmmh_include_dir = os.getenv(\"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\")\n if \"NVFUSER_BUILD_ENABLE_PCH\" in os.environ:\n config.enable_pch = get_env_flag_bool(\"NVFUSER_BUILD_ENABLE_PCH\")\n\n\ndef get_default_install_prefix():\n cwd = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(cwd, \"nvfuser_common\")\n\n\nclass build_ext(setuptools.command.build_ext.build_ext):\n def __init__(self, *args, **kwargs):\n install_dir = kwargs.pop(\"install_dir\", \"\")\n self.install_dir = install_dir if install_dir else get_default_install_prefix()\n super().__init__(*args, **kwargs)\n\n def copy_library(self, ext, library_name):\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n libnvfuser_path = os.path.join(\n os.path.join(self.install_dir, \"lib\"), f\"{library_name}{fileext}\"\n )\n assert os.path.exists(libnvfuser_path)\n install_dst = os.path.join(self.build_lib, filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))\n self.copy_file(libnvfuser_path, install_dst)\n\n def build_extension(self, ext):\n if ext.name == \"nvfuser_direct._C_DIRECT\":\n self.copy_library(ext, \"libnvfuser_direct\")\n self.copy_shared_library(\"libnvfuser_codegen.so\")\n else:\n super().build_extension(ext)\n\n def copy_shared_library(self, lib_name):\n # Copy shared library to lib/ subdirectory for package data\n src_path = os.path.join(self.install_dir, \"lib\", lib_name)\n if os.path.exists(src_path):\n dst_dir = os.path.join(self.build_lib, \"nvfuser_common\", \"lib\")\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n dst_path = os.path.join(dst_dir, lib_name)\n self.copy_file(src_path, dst_path)\n\n\nclass concat_third_party_license:\n def __init__(self, directory=\"third_party\"):\n self.license_file = \"LICENSE\"\n self.directory = directory\n\n def __enter__(self):\n # read original license file\n with open(self.license_file, \"r\") as f:\n self.nvfuser_license_txt = f.read()\n\n licenses = {\"LICENSE\", \"LICENSE.txt\", \"LICENSE.rst\", \"COPYING.BSD\"}\n\n # aggregated license, we key on project name\n aggregated_license = {}\n for root, dirs, files in os.walk(self.directory):\n license = list(licenses & set(files))\n if license:\n project_name = root.split(\"/\")[-1]\n # let's worry about multiple license when we see it.\n assert len(license) == 1\n license_entry = os.path.join(root, license[0])\n if project_name in aggregated_license:\n # Only add it if the license is different\n aggregated_license[project_name].append(license_entry)\n else:\n aggregated_license[project_name] = [license_entry]\n return aggregated_license\n\n def __exit__(self, exception_type, exception_value, traceback):\n # restore original license file\n with open(self.license_file, \"w\") as f:\n f.write(self.nvfuser_license_txt)\n\n\ntry:\n from wheel.bdist_wheel import bdist_wheel\nexcept ImportError:\n build_whl = None\nelse:\n\n class build_whl(bdist_wheel):\n def run(self):\n with concat_third_party_license() as tp_licenses:\n if len(tp_licenses) != 0:\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\n\")\n f.write(\n \"NVIDIA/fuser depends on libraries with license listed below:\"\n )\n\n for project_name, license_files in tp_licenses.items():\n # check all license files are identical\n with open(license_files[0], \"r\") as f:\n license_ref = f.read()\n\n def check_file(file_name):\n with open(file_name, \"r\") as f:\n return f.read() == license_ref\n\n identical_flag = all(map(check_file, license_files[1:]))\n if not identical_flag:\n raise RuntimeError(\n \"inconsistent license found for project: \",\n project_name,\n \" check its license files under: \",\n license_files,\n )\n\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\nProject Name: \" + project_name)\n f.write(\"\\nLicense Files:\\n\")\n for file_name in license_files:\n f.write(\"\\t\" + file_name)\n f.write(\"\\n\" + license_ref)\n\n # generate whl before we restore LICENSE\n super().run()\n\n\ndef get_cmake_bin():\n # TODO: double check cmake version here and retrieve later version if necessary\n return \"cmake\"\n\n\ndef cmake(config, relative_path):\n from tools.memory import get_available_memory_gb\n\n # make build directories\n cwd = os.path.dirname(os.path.abspath(__file__))\n cmake_build_dir = (\n os.path.join(cwd, \"build\") if not config.build_dir else config.build_dir\n )\n if not os.path.exists(cmake_build_dir):\n os.makedirs(cmake_build_dir)\n\n install_prefix = (\n config.install_dir if config.install_dir else get_default_install_prefix()\n )\n\n from tools.gen_nvfuser_version import (\n get_pytorch_use_distributed,\n )\n\n pytorch_use_distributed = get_pytorch_use_distributed()\n\n def on_or_off(flag: bool) -> str:\n return \"ON\" if flag else \"OFF\"\n\n # generate cmake directory\n #\n # cmake options are sticky: when -DFOO=... isn't specified, cmake's option\n # FOO prefers the cached value over the default value. This behavior\n # confused me several times (e.g.\n # https://github.com/NVIDIA/Fuser/pull/4319) when I ran `pip install -e`,\n # so I chose to always pass these options even for default values. Doing so\n # explicitly overrides cached values and ensures consistent behavior across\n # clean and dirty builds.\n cmd_str = [\n get_cmake_bin(),\n f\"-DCMAKE_BUILD_TYPE={config.build_type}\",\n f\"-DCMAKE_INSTALL_PREFIX={install_prefix}\",\n f\"-DNVFUSER_CPP_STANDARD={config.cpp_standard}\",\n f\"-DUSE_DISTRIBUTED={pytorch_use_distributed}\",\n f\"-DNVFUSER_BUILD_WITH_ASAN={on_or_off(config.build_with_asan)}\",\n f\"-DNVFUSER_STANDALONE_BUILD_WITH_UCC={on_or_off(config.build_with_ucc)}\",\n f\"-DNVFUSER_EXPLICIT_ERROR_CHECK={on_or_off(config.explicit_error_check)}\",\n f\"-DBUILD_TEST={on_or_off(not config.no_test)}\",\n f\"-DBUILD_PYTHON={on_or_off(not config.no_python)}\",\n f\"-DNVFUSER_DISABLE_CUTLASS={on_or_off(config.no_cutlass)}\",\n f\"-DPython_EXECUTABLE={sys.executable}\",\n f\"-DBUILD_NVFUSER_BENCHMARK={on_or_off(not config.no_benchmark)}\",\n f\"-DNVFUSER_DISTRIBUTED={on_or_off(not config.build_without_distributed)}\",\n f\"-DNVFUSER_USE_PCH={on_or_off(config.enable_pch)}\",\n \"-B\",\n cmake_build_dir,\n ]\n if config.cutlass_max_jobs:\n cmd_str.append(f\"-DCUTLASS_MAX_JOBS={config.cutlass_max_jobs}\")\n if config.nvmmh_include_dir:\n cmd_str.append(f\"-DNVMMH_INCLUDE_DIR={config.nvmmh_include_dir}\")\n if not config.no_ninja:\n cmd_str.append(\"-G\")\n cmd_str.append(\"Ninja\")\n cmd_str.append(relative_path)\n\n print(f\"Configuring CMake with {' '.join(cmd_str)}\")\n subprocess.check_call(cmd_str)\n\n max_jobs = multiprocessing.cpu_count()\n mem_gb_per_task = 3 # Currently compilation of nvFuser souce code takes ~3GB of memory per task, we should adjust this value if it changes in the future.\n available_mem = get_available_memory_gb()\n if available_mem > 0:\n max_jobs_mem = int(available_mem / mem_gb_per_task)\n max_jobs = min(max_jobs, max_jobs_mem)\n\n if not config.cmake_only:\n # build binary\n max_jobs = os.getenv(\"MAX_JOBS\", str(max_jobs))\n print(f\"Using {max_jobs} jobs for compilation\")\n cmd_str = [\n get_cmake_bin(),\n \"--build\",\n cmake_build_dir,\n \"--target\",\n \"install\",\n \"--\",\n \"-j\",\n max_jobs,\n ]\n subprocess.check_call(cmd_str)\n\n\ndef create_clean(relative_path):\n class clean(setuptools.Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n import glob\n\n gitignore_path = os.path.join(relative_path, \".gitignore\")\n assert os.path.exists(gitignore_path)\n with open(gitignore_path, \"r\") as f:\n ignores = f.read()\n for entry in ignores.split(\"\\n\"):\n # ignore comment in .gitignore\n if len(entry) >= 1 and entry[0] != \"#\":\n for filename in glob.glob(entry):\n print(\"removing: \", filename)\n try:\n os.remove(filename)\n except OSError:\n shutil.rmtree(filename, ignore_errors=True)\n\n return clean\n\n\ndef run(config, version_tag, relative_path):\n from setuptools import Extension, setup, find_packages\n\n # NOTE(crcrpar): Deliberately build basically two dynamic libraries here so that they can\n # be treated as \"nvfuser_package_data\".\n if config.build_setup:\n cmake(config, relative_path)\n if not config.cmake_only:\n # NOTE: package include files for cmake\n # TODO(crcrpar): Better avoid hardcoding `libnvfuser_codegen.so`\n # might can be treated by using `exclude_package_data`.\n nvfuser_common_package_data = [\n \"lib/libnvfuser_codegen.so\",\n \"lib/libnvf_cutlass.so\",\n \"include/nvfuser/*.h\",\n \"include/nvfuser/struct.inl\",\n \"include/nvfuser/C++20/type_traits\",\n \"include/nvfuser/device_lower/*.h\",\n \"include/nvfuser/device_lower/analysis/*.h\",\n \"include/nvfuser/device_lower/pass/*.h\",\n \"include/nvfuser/dynamic_type/*\",\n \"include/nvfuser/dynamic_type/C++20/*\",\n \"include/nvfuser/kernel_db/*.h\",\n \"include/nvfuser/multidevice/*.h\",\n \"include/nvfuser/ops/*.h\",\n \"include/nvfuser/ir/*.h\",\n \"include/nvfuser/scheduler/*.h\",\n \"include/nvfuser/host_ir/*.h\",\n \"include/nvfuser/id_model/*.h\",\n \"share/cmake/nvfuser/NvfuserConfig*\",\n # TODO(crcrpar): it'd be better to ship the following two binaries.\n # Would need some change in CMakeLists.txt.\n # \"bin/test_nvfuser\",\n # \"bin/nvfuser_bench\"\n ]\n\n setup(\n name=config.wheel_name,\n version=version_tag,\n url=\"https://github.com/NVIDIA/Fuser\",\n description=\"A Fusion Code Generator for NVIDIA GPUs (commonly known as 'nvFuser')\",\n packages=find_packages(),\n ext_modules=[\n Extension(name=\"nvfuser_direct._C_DIRECT\", sources=[]),\n ],\n license_files=(\"LICENSE\",),\n cmdclass={\n \"bdist_wheel\": build_whl,\n \"build_ext\": lambda *args, **kwargs: build_ext(\n *args, install_dir=config.install_dir, **kwargs\n ),\n \"clean\": create_clean(relative_path),\n },\n package_data={\n \"nvfuser_common\": nvfuser_common_package_data,\n },\n install_requires=config.install_requires,\n extras_require={\n \"test\": [\"numpy\", \"expecttest\", \"pytest\"],\n **config.extras_require,\n },\n license=\"BSD-3-Clause\",\n )","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.BuildConfig","uri":"program://Fuser/class/python.utils.BuildConfig#L15-L38","kind":"class","name":"BuildConfig","path":"python/utils.py","language":"python","start_line":15,"end_line":38,"context_start_line":1,"context_end_line":58,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\nimport multiprocessing\nimport subprocess\nimport sys\nimport shutil\nfrom dataclasses import dataclass, field\nimport setuptools.command.build_ext\n\n\n@dataclass\nclass BuildConfig:\n cmake_only: bool = False\n build_setup: bool = True\n no_python: bool = False\n no_cutlass: bool = False\n no_test: bool = False\n no_benchmark: bool = False\n no_ninja: bool = False\n build_with_ucc: bool = False\n build_with_asan: bool = False\n build_without_distributed: bool = False\n explicit_error_check: bool = False\n overwrite_version: bool = False\n version_tag: str = None\n build_type: str = \"Release\"\n wheel_name: str = \"nvfuser\"\n nvmmh_include_dir: str = \"\"\n build_dir: str = \"\"\n install_dir: str = \"\"\n install_requires: list = field(default_factory=list)\n extras_require: dict = field(default_factory=dict)\n cpp_standard: int = 20\n cutlass_max_jobs: int | None = None\n enable_pch: bool = False\n\n\ndef check_env_flag_bool_default(name: str, default: str = \"\") -> bool:\n if name not in os.environ:\n return default\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\ndef get_env_flag_bool(name: str) -> bool:\n assert name in os.environ\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\n# Override BuildConfig with environment variables. Only change if variable\n# exists. Do not use default to override argparse.\ndef override_build_config_from_env(config):\n # Command line arguments don't work on PEP517 builds and will be silently ignored,\n # so we need to pass those options as environment variables instead.\n if \"NVFUSER_BUILD_CMAKE_ONLY\" in os.environ:\n config.cmake_only = get_env_flag_bool(\"NVFUSER_BUILD_CMAKE_ONLY\")","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.check_env_flag_bool_default","uri":"program://Fuser/function/python.utils.check_env_flag_bool_default#L41-L44","kind":"function","name":"check_env_flag_bool_default","path":"python/utils.py","language":"python","start_line":41,"end_line":44,"context_start_line":21,"context_end_line":64,"code":" no_benchmark: bool = False\n no_ninja: bool = False\n build_with_ucc: bool = False\n build_with_asan: bool = False\n build_without_distributed: bool = False\n explicit_error_check: bool = False\n overwrite_version: bool = False\n version_tag: str = None\n build_type: str = \"Release\"\n wheel_name: str = \"nvfuser\"\n nvmmh_include_dir: str = \"\"\n build_dir: str = \"\"\n install_dir: str = \"\"\n install_requires: list = field(default_factory=list)\n extras_require: dict = field(default_factory=dict)\n cpp_standard: int = 20\n cutlass_max_jobs: int | None = None\n enable_pch: bool = False\n\n\ndef check_env_flag_bool_default(name: str, default: str = \"\") -> bool:\n if name not in os.environ:\n return default\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\ndef get_env_flag_bool(name: str) -> bool:\n assert name in os.environ\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\n# Override BuildConfig with environment variables. Only change if variable\n# exists. Do not use default to override argparse.\ndef override_build_config_from_env(config):\n # Command line arguments don't work on PEP517 builds and will be silently ignored,\n # so we need to pass those options as environment variables instead.\n if \"NVFUSER_BUILD_CMAKE_ONLY\" in os.environ:\n config.cmake_only = get_env_flag_bool(\"NVFUSER_BUILD_CMAKE_ONLY\")\n if \"NVFUSER_BUILD_SETUP\" in os.environ:\n config.build_setup = get_env_flag_bool(\"NVFUSER_BUILD_SETUP\")\n if \"NVFUSER_BUILD_NO_PYTHON\" in os.environ:\n config.no_python = get_env_flag_bool(\"NVFUSER_BUILD_NO_PYTHON\")\n if \"NVFUSER_BUILD_NO_CUTLASS\" in os.environ:\n config.no_cutlass = get_env_flag_bool(\"NVFUSER_BUILD_NO_CUTLASS\")","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.get_env_flag_bool","uri":"program://Fuser/function/python.utils.get_env_flag_bool#L47-L49","kind":"function","name":"get_env_flag_bool","path":"python/utils.py","language":"python","start_line":47,"end_line":49,"context_start_line":27,"context_end_line":69,"code":" overwrite_version: bool = False\n version_tag: str = None\n build_type: str = \"Release\"\n wheel_name: str = \"nvfuser\"\n nvmmh_include_dir: str = \"\"\n build_dir: str = \"\"\n install_dir: str = \"\"\n install_requires: list = field(default_factory=list)\n extras_require: dict = field(default_factory=dict)\n cpp_standard: int = 20\n cutlass_max_jobs: int | None = None\n enable_pch: bool = False\n\n\ndef check_env_flag_bool_default(name: str, default: str = \"\") -> bool:\n if name not in os.environ:\n return default\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\ndef get_env_flag_bool(name: str) -> bool:\n assert name in os.environ\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\n# Override BuildConfig with environment variables. Only change if variable\n# exists. Do not use default to override argparse.\ndef override_build_config_from_env(config):\n # Command line arguments don't work on PEP517 builds and will be silently ignored,\n # so we need to pass those options as environment variables instead.\n if \"NVFUSER_BUILD_CMAKE_ONLY\" in os.environ:\n config.cmake_only = get_env_flag_bool(\"NVFUSER_BUILD_CMAKE_ONLY\")\n if \"NVFUSER_BUILD_SETUP\" in os.environ:\n config.build_setup = get_env_flag_bool(\"NVFUSER_BUILD_SETUP\")\n if \"NVFUSER_BUILD_NO_PYTHON\" in os.environ:\n config.no_python = get_env_flag_bool(\"NVFUSER_BUILD_NO_PYTHON\")\n if \"NVFUSER_BUILD_NO_CUTLASS\" in os.environ:\n config.no_cutlass = get_env_flag_bool(\"NVFUSER_BUILD_NO_CUTLASS\")\n if \"NVFUSER_BUILD_NO_TEST\" in os.environ:\n config.no_test = get_env_flag_bool(\"NVFUSER_BUILD_NO_TEST\")\n if \"NVFUSER_BUILD_NO_BENCHMARK\" in os.environ:\n config.no_benchmark = get_env_flag_bool(\"NVFUSER_BUILD_NO_BENCHMARK\")\n if \"NVFUSER_BUILD_NO_NINJA\" in os.environ:","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.override_build_config_from_env","uri":"program://Fuser/function/python.utils.override_build_config_from_env#L54-L109","kind":"function","name":"override_build_config_from_env","path":"python/utils.py","language":"python","start_line":54,"end_line":109,"context_start_line":34,"context_end_line":129,"code":" install_requires: list = field(default_factory=list)\n extras_require: dict = field(default_factory=dict)\n cpp_standard: int = 20\n cutlass_max_jobs: int | None = None\n enable_pch: bool = False\n\n\ndef check_env_flag_bool_default(name: str, default: str = \"\") -> bool:\n if name not in os.environ:\n return default\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\ndef get_env_flag_bool(name: str) -> bool:\n assert name in os.environ\n return os.getenv(name).upper() in [\"ON\", \"1\", \"YES\", \"TRUE\", \"Y\"]\n\n\n# Override BuildConfig with environment variables. Only change if variable\n# exists. Do not use default to override argparse.\ndef override_build_config_from_env(config):\n # Command line arguments don't work on PEP517 builds and will be silently ignored,\n # so we need to pass those options as environment variables instead.\n if \"NVFUSER_BUILD_CMAKE_ONLY\" in os.environ:\n config.cmake_only = get_env_flag_bool(\"NVFUSER_BUILD_CMAKE_ONLY\")\n if \"NVFUSER_BUILD_SETUP\" in os.environ:\n config.build_setup = get_env_flag_bool(\"NVFUSER_BUILD_SETUP\")\n if \"NVFUSER_BUILD_NO_PYTHON\" in os.environ:\n config.no_python = get_env_flag_bool(\"NVFUSER_BUILD_NO_PYTHON\")\n if \"NVFUSER_BUILD_NO_CUTLASS\" in os.environ:\n config.no_cutlass = get_env_flag_bool(\"NVFUSER_BUILD_NO_CUTLASS\")\n if \"NVFUSER_BUILD_NO_TEST\" in os.environ:\n config.no_test = get_env_flag_bool(\"NVFUSER_BUILD_NO_TEST\")\n if \"NVFUSER_BUILD_NO_BENCHMARK\" in os.environ:\n config.no_benchmark = get_env_flag_bool(\"NVFUSER_BUILD_NO_BENCHMARK\")\n if \"NVFUSER_BUILD_NO_NINJA\" in os.environ:\n config.no_ninja = get_env_flag_bool(\"NVFUSER_BUILD_NO_NINJA\")\n if \"NVFUSER_BUILD_WITH_UCC\" in os.environ:\n config.build_with_ucc = get_env_flag_bool(\"NVFUSER_BUILD_WITH_UCC\")\n if \"NVFUSER_BUILD_WITH_ASAN\" in os.environ:\n config.build_with_asan = get_env_flag_bool(\"NVFUSER_BUILD_WITH_ASAN\")\n if \"NVFUSER_BUILD_WITHOUT_DISTRIBUTED\" in os.environ:\n config.build_without_distributed = get_env_flag_bool(\n \"NVFUSER_BUILD_WITHOUT_DISTRIBUTED\"\n )\n if \"NVFUSER_BUILD_EXPLICIT_ERROR_CHECK\" in os.environ:\n config.explicit_error_check = get_env_flag_bool(\n \"NVFUSER_BUILD_EXPLICIT_ERROR_CHECK\"\n )\n if \"NVFUSER_BUILD_OVERWRITE_VERSION\" in os.environ:\n config.overwrite_version = get_env_flag_bool(\"NVFUSER_BUILD_OVERWRITE_VERSION\")\n if \"NVFUSER_BUILD_VERSION_TAG\" in os.environ:\n config.version_tag = os.getenv(\"NVFUSER_BUILD_VERSION_TAG\")\n if \"NVFUSER_BUILD_BUILD_TYPE\" in os.environ:\n config.build_type = os.getenv(\"NVFUSER_BUILD_BUILD_TYPE\")\n if \"NVFUSER_BUILD_WHEEL_NAME\" in os.environ:\n config.wheel_name = os.getenv(\"NVFUSER_BUILD_WHEEL_NAME\")\n if \"NVFUSER_BUILD_DIR\" in os.environ:\n config.build_dir = os.getenv(\"NVFUSER_BUILD_DIR\")\n if \"NVFUSER_BUILD_INSTALL_DIR\" in os.environ:\n config.install_dir = os.getenv(\"NVFUSER_BUILD_INSTALL_DIR\")\n if \"NVFUSER_BUILD_INSTALL_REQUIRES\" in os.environ:\n config.install_requires = os.getenv(\"NVFUSER_BUILD_INSTALL_REQUIRES\").split(\",\")\n if \"NVFUSER_BUILD_EXTRAS_REQUIRE\" in os.environ:\n config.extras_require = eval(os.getenv(\"NVFUSER_BUILD_EXTRAS_REQUIRE\"))\n if \"NVFUSER_BUILD_CPP_STANDARD\" in os.environ:\n config.cpp_standard = int(os.getenv(\"NVFUSER_BUILD_CPP_STANDARD\"))\n if \"NVFUSER_BUILD_VERSION_TAG\" in os.environ:\n config.overwrite_version = True\n config.version_tag = os.getenv(\"NVFUSER_BUILD_VERSION_TAG\")\n if \"NVFUSER_CUTLASS_MAX_JOBS\" in os.environ:\n config.cutlass_max_jobs = int(os.getenv(\"NVFUSER_CUTLASS_MAX_JOBS\"))\n if \"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\" in os.environ:\n config.nvmmh_include_dir = os.getenv(\"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\")\n if \"NVFUSER_BUILD_ENABLE_PCH\" in os.environ:\n config.enable_pch = get_env_flag_bool(\"NVFUSER_BUILD_ENABLE_PCH\")\n\n\ndef get_default_install_prefix():\n cwd = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(cwd, \"nvfuser_common\")\n\n\nclass build_ext(setuptools.command.build_ext.build_ext):\n def __init__(self, *args, **kwargs):\n install_dir = kwargs.pop(\"install_dir\", \"\")\n self.install_dir = install_dir if install_dir else get_default_install_prefix()\n super().__init__(*args, **kwargs)\n\n def copy_library(self, ext, library_name):\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n libnvfuser_path = os.path.join(\n os.path.join(self.install_dir, \"lib\"), f\"{library_name}{fileext}\"","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.get_default_install_prefix","uri":"program://Fuser/function/python.utils.get_default_install_prefix#L112-L114","kind":"function","name":"get_default_install_prefix","path":"python/utils.py","language":"python","start_line":112,"end_line":114,"context_start_line":92,"context_end_line":134,"code":" config.build_dir = os.getenv(\"NVFUSER_BUILD_DIR\")\n if \"NVFUSER_BUILD_INSTALL_DIR\" in os.environ:\n config.install_dir = os.getenv(\"NVFUSER_BUILD_INSTALL_DIR\")\n if \"NVFUSER_BUILD_INSTALL_REQUIRES\" in os.environ:\n config.install_requires = os.getenv(\"NVFUSER_BUILD_INSTALL_REQUIRES\").split(\",\")\n if \"NVFUSER_BUILD_EXTRAS_REQUIRE\" in os.environ:\n config.extras_require = eval(os.getenv(\"NVFUSER_BUILD_EXTRAS_REQUIRE\"))\n if \"NVFUSER_BUILD_CPP_STANDARD\" in os.environ:\n config.cpp_standard = int(os.getenv(\"NVFUSER_BUILD_CPP_STANDARD\"))\n if \"NVFUSER_BUILD_VERSION_TAG\" in os.environ:\n config.overwrite_version = True\n config.version_tag = os.getenv(\"NVFUSER_BUILD_VERSION_TAG\")\n if \"NVFUSER_CUTLASS_MAX_JOBS\" in os.environ:\n config.cutlass_max_jobs = int(os.getenv(\"NVFUSER_CUTLASS_MAX_JOBS\"))\n if \"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\" in os.environ:\n config.nvmmh_include_dir = os.getenv(\"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\")\n if \"NVFUSER_BUILD_ENABLE_PCH\" in os.environ:\n config.enable_pch = get_env_flag_bool(\"NVFUSER_BUILD_ENABLE_PCH\")\n\n\ndef get_default_install_prefix():\n cwd = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(cwd, \"nvfuser_common\")\n\n\nclass build_ext(setuptools.command.build_ext.build_ext):\n def __init__(self, *args, **kwargs):\n install_dir = kwargs.pop(\"install_dir\", \"\")\n self.install_dir = install_dir if install_dir else get_default_install_prefix()\n super().__init__(*args, **kwargs)\n\n def copy_library(self, ext, library_name):\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n libnvfuser_path = os.path.join(\n os.path.join(self.install_dir, \"lib\"), f\"{library_name}{fileext}\"\n )\n assert os.path.exists(libnvfuser_path)\n install_dst = os.path.join(self.build_lib, filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.build_ext","uri":"program://Fuser/class/python.utils.build_ext#L117-L152","kind":"class","name":"build_ext","path":"python/utils.py","language":"python","start_line":117,"end_line":152,"context_start_line":97,"context_end_line":172,"code":" if \"NVFUSER_BUILD_EXTRAS_REQUIRE\" in os.environ:\n config.extras_require = eval(os.getenv(\"NVFUSER_BUILD_EXTRAS_REQUIRE\"))\n if \"NVFUSER_BUILD_CPP_STANDARD\" in os.environ:\n config.cpp_standard = int(os.getenv(\"NVFUSER_BUILD_CPP_STANDARD\"))\n if \"NVFUSER_BUILD_VERSION_TAG\" in os.environ:\n config.overwrite_version = True\n config.version_tag = os.getenv(\"NVFUSER_BUILD_VERSION_TAG\")\n if \"NVFUSER_CUTLASS_MAX_JOBS\" in os.environ:\n config.cutlass_max_jobs = int(os.getenv(\"NVFUSER_CUTLASS_MAX_JOBS\"))\n if \"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\" in os.environ:\n config.nvmmh_include_dir = os.getenv(\"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\")\n if \"NVFUSER_BUILD_ENABLE_PCH\" in os.environ:\n config.enable_pch = get_env_flag_bool(\"NVFUSER_BUILD_ENABLE_PCH\")\n\n\ndef get_default_install_prefix():\n cwd = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(cwd, \"nvfuser_common\")\n\n\nclass build_ext(setuptools.command.build_ext.build_ext):\n def __init__(self, *args, **kwargs):\n install_dir = kwargs.pop(\"install_dir\", \"\")\n self.install_dir = install_dir if install_dir else get_default_install_prefix()\n super().__init__(*args, **kwargs)\n\n def copy_library(self, ext, library_name):\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n libnvfuser_path = os.path.join(\n os.path.join(self.install_dir, \"lib\"), f\"{library_name}{fileext}\"\n )\n assert os.path.exists(libnvfuser_path)\n install_dst = os.path.join(self.build_lib, filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))\n self.copy_file(libnvfuser_path, install_dst)\n\n def build_extension(self, ext):\n if ext.name == \"nvfuser_direct._C_DIRECT\":\n self.copy_library(ext, \"libnvfuser_direct\")\n self.copy_shared_library(\"libnvfuser_codegen.so\")\n else:\n super().build_extension(ext)\n\n def copy_shared_library(self, lib_name):\n # Copy shared library to lib/ subdirectory for package data\n src_path = os.path.join(self.install_dir, \"lib\", lib_name)\n if os.path.exists(src_path):\n dst_dir = os.path.join(self.build_lib, \"nvfuser_common\", \"lib\")\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n dst_path = os.path.join(dst_dir, lib_name)\n self.copy_file(src_path, dst_path)\n\n\nclass concat_third_party_license:\n def __init__(self, directory=\"third_party\"):\n self.license_file = \"LICENSE\"\n self.directory = directory\n\n def __enter__(self):\n # read original license file\n with open(self.license_file, \"r\") as f:\n self.nvfuser_license_txt = f.read()\n\n licenses = {\"LICENSE\", \"LICENSE.txt\", \"LICENSE.rst\", \"COPYING.BSD\"}\n\n # aggregated license, we key on project name\n aggregated_license = {}\n for root, dirs, files in os.walk(self.directory):\n license = list(licenses & set(files))\n if license:\n project_name = root.split(\"/\")[-1]","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.concat_third_party_license","uri":"program://Fuser/class/python.utils.concat_third_party_license#L155-L186","kind":"class","name":"concat_third_party_license","path":"python/utils.py","language":"python","start_line":155,"end_line":186,"context_start_line":135,"context_end_line":206,"code":" self.copy_file(libnvfuser_path, install_dst)\n\n def build_extension(self, ext):\n if ext.name == \"nvfuser_direct._C_DIRECT\":\n self.copy_library(ext, \"libnvfuser_direct\")\n self.copy_shared_library(\"libnvfuser_codegen.so\")\n else:\n super().build_extension(ext)\n\n def copy_shared_library(self, lib_name):\n # Copy shared library to lib/ subdirectory for package data\n src_path = os.path.join(self.install_dir, \"lib\", lib_name)\n if os.path.exists(src_path):\n dst_dir = os.path.join(self.build_lib, \"nvfuser_common\", \"lib\")\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n dst_path = os.path.join(dst_dir, lib_name)\n self.copy_file(src_path, dst_path)\n\n\nclass concat_third_party_license:\n def __init__(self, directory=\"third_party\"):\n self.license_file = \"LICENSE\"\n self.directory = directory\n\n def __enter__(self):\n # read original license file\n with open(self.license_file, \"r\") as f:\n self.nvfuser_license_txt = f.read()\n\n licenses = {\"LICENSE\", \"LICENSE.txt\", \"LICENSE.rst\", \"COPYING.BSD\"}\n\n # aggregated license, we key on project name\n aggregated_license = {}\n for root, dirs, files in os.walk(self.directory):\n license = list(licenses & set(files))\n if license:\n project_name = root.split(\"/\")[-1]\n # let's worry about multiple license when we see it.\n assert len(license) == 1\n license_entry = os.path.join(root, license[0])\n if project_name in aggregated_license:\n # Only add it if the license is different\n aggregated_license[project_name].append(license_entry)\n else:\n aggregated_license[project_name] = [license_entry]\n return aggregated_license\n\n def __exit__(self, exception_type, exception_value, traceback):\n # restore original license file\n with open(self.license_file, \"w\") as f:\n f.write(self.nvfuser_license_txt)\n\n\ntry:\n from wheel.bdist_wheel import bdist_wheel\nexcept ImportError:\n build_whl = None\nelse:\n\n class build_whl(bdist_wheel):\n def run(self):\n with concat_third_party_license() as tp_licenses:\n if len(tp_licenses) != 0:\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\n\")\n f.write(\n \"NVIDIA/fuser depends on libraries with license listed below:\"\n )\n\n for project_name, license_files in tp_licenses.items():\n # check all license files are identical","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.get_cmake_bin","uri":"program://Fuser/function/python.utils.get_cmake_bin#L234-L236","kind":"function","name":"get_cmake_bin","path":"python/utils.py","language":"python","start_line":234,"end_line":236,"context_start_line":214,"context_end_line":256,"code":" identical_flag = all(map(check_file, license_files[1:]))\n if not identical_flag:\n raise RuntimeError(\n \"inconsistent license found for project: \",\n project_name,\n \" check its license files under: \",\n license_files,\n )\n\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\nProject Name: \" + project_name)\n f.write(\"\\nLicense Files:\\n\")\n for file_name in license_files:\n f.write(\"\\t\" + file_name)\n f.write(\"\\n\" + license_ref)\n\n # generate whl before we restore LICENSE\n super().run()\n\n\ndef get_cmake_bin():\n # TODO: double check cmake version here and retrieve later version if necessary\n return \"cmake\"\n\n\ndef cmake(config, relative_path):\n from tools.memory import get_available_memory_gb\n\n # make build directories\n cwd = os.path.dirname(os.path.abspath(__file__))\n cmake_build_dir = (\n os.path.join(cwd, \"build\") if not config.build_dir else config.build_dir\n )\n if not os.path.exists(cmake_build_dir):\n os.makedirs(cmake_build_dir)\n\n install_prefix = (\n config.install_dir if config.install_dir else get_default_install_prefix()\n )\n\n from tools.gen_nvfuser_version import (\n get_pytorch_use_distributed,\n )","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.cmake","uri":"program://Fuser/function/python.utils.cmake#L239-L324","kind":"function","name":"cmake","path":"python/utils.py","language":"python","start_line":239,"end_line":324,"context_start_line":219,"context_end_line":344,"code":" \" check its license files under: \",\n license_files,\n )\n\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\nProject Name: \" + project_name)\n f.write(\"\\nLicense Files:\\n\")\n for file_name in license_files:\n f.write(\"\\t\" + file_name)\n f.write(\"\\n\" + license_ref)\n\n # generate whl before we restore LICENSE\n super().run()\n\n\ndef get_cmake_bin():\n # TODO: double check cmake version here and retrieve later version if necessary\n return \"cmake\"\n\n\ndef cmake(config, relative_path):\n from tools.memory import get_available_memory_gb\n\n # make build directories\n cwd = os.path.dirname(os.path.abspath(__file__))\n cmake_build_dir = (\n os.path.join(cwd, \"build\") if not config.build_dir else config.build_dir\n )\n if not os.path.exists(cmake_build_dir):\n os.makedirs(cmake_build_dir)\n\n install_prefix = (\n config.install_dir if config.install_dir else get_default_install_prefix()\n )\n\n from tools.gen_nvfuser_version import (\n get_pytorch_use_distributed,\n )\n\n pytorch_use_distributed = get_pytorch_use_distributed()\n\n def on_or_off(flag: bool) -> str:\n return \"ON\" if flag else \"OFF\"\n\n # generate cmake directory\n #\n # cmake options are sticky: when -DFOO=... isn't specified, cmake's option\n # FOO prefers the cached value over the default value. This behavior\n # confused me several times (e.g.\n # https://github.com/NVIDIA/Fuser/pull/4319) when I ran `pip install -e`,\n # so I chose to always pass these options even for default values. Doing so\n # explicitly overrides cached values and ensures consistent behavior across\n # clean and dirty builds.\n cmd_str = [\n get_cmake_bin(),\n f\"-DCMAKE_BUILD_TYPE={config.build_type}\",\n f\"-DCMAKE_INSTALL_PREFIX={install_prefix}\",\n f\"-DNVFUSER_CPP_STANDARD={config.cpp_standard}\",\n f\"-DUSE_DISTRIBUTED={pytorch_use_distributed}\",\n f\"-DNVFUSER_BUILD_WITH_ASAN={on_or_off(config.build_with_asan)}\",\n f\"-DNVFUSER_STANDALONE_BUILD_WITH_UCC={on_or_off(config.build_with_ucc)}\",\n f\"-DNVFUSER_EXPLICIT_ERROR_CHECK={on_or_off(config.explicit_error_check)}\",\n f\"-DBUILD_TEST={on_or_off(not config.no_test)}\",\n f\"-DBUILD_PYTHON={on_or_off(not config.no_python)}\",\n f\"-DNVFUSER_DISABLE_CUTLASS={on_or_off(config.no_cutlass)}\",\n f\"-DPython_EXECUTABLE={sys.executable}\",\n f\"-DBUILD_NVFUSER_BENCHMARK={on_or_off(not config.no_benchmark)}\",\n f\"-DNVFUSER_DISTRIBUTED={on_or_off(not config.build_without_distributed)}\",\n f\"-DNVFUSER_USE_PCH={on_or_off(config.enable_pch)}\",\n \"-B\",\n cmake_build_dir,\n ]\n if config.cutlass_max_jobs:\n cmd_str.append(f\"-DCUTLASS_MAX_JOBS={config.cutlass_max_jobs}\")\n if config.nvmmh_include_dir:\n cmd_str.append(f\"-DNVMMH_INCLUDE_DIR={config.nvmmh_include_dir}\")\n if not config.no_ninja:\n cmd_str.append(\"-G\")\n cmd_str.append(\"Ninja\")\n cmd_str.append(relative_path)\n\n print(f\"Configuring CMake with {' '.join(cmd_str)}\")\n subprocess.check_call(cmd_str)\n\n max_jobs = multiprocessing.cpu_count()\n mem_gb_per_task = 3 # Currently compilation of nvFuser souce code takes ~3GB of memory per task, we should adjust this value if it changes in the future.\n available_mem = get_available_memory_gb()\n if available_mem > 0:\n max_jobs_mem = int(available_mem / mem_gb_per_task)\n max_jobs = min(max_jobs, max_jobs_mem)\n\n if not config.cmake_only:\n # build binary\n max_jobs = os.getenv(\"MAX_JOBS\", str(max_jobs))\n print(f\"Using {max_jobs} jobs for compilation\")\n cmd_str = [\n get_cmake_bin(),\n \"--build\",\n cmake_build_dir,\n \"--target\",\n \"install\",\n \"--\",\n \"-j\",\n max_jobs,\n ]\n subprocess.check_call(cmd_str)\n\n\ndef create_clean(relative_path):\n class clean(setuptools.Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n import glob\n\n gitignore_path = os.path.join(relative_path, \".gitignore\")\n assert os.path.exists(gitignore_path)\n with open(gitignore_path, \"r\") as f:\n ignores = f.read()\n for entry in ignores.split(\"\\n\"):","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.create_clean","uri":"program://Fuser/function/python.utils.create_clean#L327-L354","kind":"function","name":"create_clean","path":"python/utils.py","language":"python","start_line":327,"end_line":354,"context_start_line":307,"context_end_line":374,"code":" max_jobs_mem = int(available_mem / mem_gb_per_task)\n max_jobs = min(max_jobs, max_jobs_mem)\n\n if not config.cmake_only:\n # build binary\n max_jobs = os.getenv(\"MAX_JOBS\", str(max_jobs))\n print(f\"Using {max_jobs} jobs for compilation\")\n cmd_str = [\n get_cmake_bin(),\n \"--build\",\n cmake_build_dir,\n \"--target\",\n \"install\",\n \"--\",\n \"-j\",\n max_jobs,\n ]\n subprocess.check_call(cmd_str)\n\n\ndef create_clean(relative_path):\n class clean(setuptools.Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n import glob\n\n gitignore_path = os.path.join(relative_path, \".gitignore\")\n assert os.path.exists(gitignore_path)\n with open(gitignore_path, \"r\") as f:\n ignores = f.read()\n for entry in ignores.split(\"\\n\"):\n # ignore comment in .gitignore\n if len(entry) >= 1 and entry[0] != \"#\":\n for filename in glob.glob(entry):\n print(\"removing: \", filename)\n try:\n os.remove(filename)\n except OSError:\n shutil.rmtree(filename, ignore_errors=True)\n\n return clean\n\n\ndef run(config, version_tag, relative_path):\n from setuptools import Extension, setup, find_packages\n\n # NOTE(crcrpar): Deliberately build basically two dynamic libraries here so that they can\n # be treated as \"nvfuser_package_data\".\n if config.build_setup:\n cmake(config, relative_path)\n if not config.cmake_only:\n # NOTE: package include files for cmake\n # TODO(crcrpar): Better avoid hardcoding `libnvfuser_codegen.so`\n # might can be treated by using `exclude_package_data`.\n nvfuser_common_package_data = [\n \"lib/libnvfuser_codegen.so\",\n \"lib/libnvf_cutlass.so\",\n \"include/nvfuser/*.h\",\n \"include/nvfuser/struct.inl\",\n \"include/nvfuser/C++20/type_traits\",\n \"include/nvfuser/device_lower/*.h\",","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.run","uri":"program://Fuser/function/python.utils.run#L337-L352","kind":"function","name":"run","path":"python/utils.py","language":"python","start_line":337,"end_line":352,"context_start_line":317,"context_end_line":372,"code":" cmake_build_dir,\n \"--target\",\n \"install\",\n \"--\",\n \"-j\",\n max_jobs,\n ]\n subprocess.check_call(cmd_str)\n\n\ndef create_clean(relative_path):\n class clean(setuptools.Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n import glob\n\n gitignore_path = os.path.join(relative_path, \".gitignore\")\n assert os.path.exists(gitignore_path)\n with open(gitignore_path, \"r\") as f:\n ignores = f.read()\n for entry in ignores.split(\"\\n\"):\n # ignore comment in .gitignore\n if len(entry) >= 1 and entry[0] != \"#\":\n for filename in glob.glob(entry):\n print(\"removing: \", filename)\n try:\n os.remove(filename)\n except OSError:\n shutil.rmtree(filename, ignore_errors=True)\n\n return clean\n\n\ndef run(config, version_tag, relative_path):\n from setuptools import Extension, setup, find_packages\n\n # NOTE(crcrpar): Deliberately build basically two dynamic libraries here so that they can\n # be treated as \"nvfuser_package_data\".\n if config.build_setup:\n cmake(config, relative_path)\n if not config.cmake_only:\n # NOTE: package include files for cmake\n # TODO(crcrpar): Better avoid hardcoding `libnvfuser_codegen.so`\n # might can be treated by using `exclude_package_data`.\n nvfuser_common_package_data = [\n \"lib/libnvfuser_codegen.so\",\n \"lib/libnvf_cutlass.so\",\n \"include/nvfuser/*.h\",\n \"include/nvfuser/struct.inl\",","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.__init__","uri":"program://Fuser/function/python.utils.__init__#L156-L158","kind":"function","name":"__init__","path":"python/utils.py","language":"python","start_line":156,"end_line":158,"context_start_line":136,"context_end_line":178,"code":"\n def build_extension(self, ext):\n if ext.name == \"nvfuser_direct._C_DIRECT\":\n self.copy_library(ext, \"libnvfuser_direct\")\n self.copy_shared_library(\"libnvfuser_codegen.so\")\n else:\n super().build_extension(ext)\n\n def copy_shared_library(self, lib_name):\n # Copy shared library to lib/ subdirectory for package data\n src_path = os.path.join(self.install_dir, \"lib\", lib_name)\n if os.path.exists(src_path):\n dst_dir = os.path.join(self.build_lib, \"nvfuser_common\", \"lib\")\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n dst_path = os.path.join(dst_dir, lib_name)\n self.copy_file(src_path, dst_path)\n\n\nclass concat_third_party_license:\n def __init__(self, directory=\"third_party\"):\n self.license_file = \"LICENSE\"\n self.directory = directory\n\n def __enter__(self):\n # read original license file\n with open(self.license_file, \"r\") as f:\n self.nvfuser_license_txt = f.read()\n\n licenses = {\"LICENSE\", \"LICENSE.txt\", \"LICENSE.rst\", \"COPYING.BSD\"}\n\n # aggregated license, we key on project name\n aggregated_license = {}\n for root, dirs, files in os.walk(self.directory):\n license = list(licenses & set(files))\n if license:\n project_name = root.split(\"/\")[-1]\n # let's worry about multiple license when we see it.\n assert len(license) == 1\n license_entry = os.path.join(root, license[0])\n if project_name in aggregated_license:\n # Only add it if the license is different\n aggregated_license[project_name].append(license_entry)","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.copy_library","uri":"program://Fuser/function/python.utils.copy_library#L123-L135","kind":"function","name":"copy_library","path":"python/utils.py","language":"python","start_line":123,"end_line":135,"context_start_line":103,"context_end_line":155,"code":" config.version_tag = os.getenv(\"NVFUSER_BUILD_VERSION_TAG\")\n if \"NVFUSER_CUTLASS_MAX_JOBS\" in os.environ:\n config.cutlass_max_jobs = int(os.getenv(\"NVFUSER_CUTLASS_MAX_JOBS\"))\n if \"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\" in os.environ:\n config.nvmmh_include_dir = os.getenv(\"NVFUSER_BUILD_NVMMH_INCLUDE_DIR\")\n if \"NVFUSER_BUILD_ENABLE_PCH\" in os.environ:\n config.enable_pch = get_env_flag_bool(\"NVFUSER_BUILD_ENABLE_PCH\")\n\n\ndef get_default_install_prefix():\n cwd = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(cwd, \"nvfuser_common\")\n\n\nclass build_ext(setuptools.command.build_ext.build_ext):\n def __init__(self, *args, **kwargs):\n install_dir = kwargs.pop(\"install_dir\", \"\")\n self.install_dir = install_dir if install_dir else get_default_install_prefix()\n super().__init__(*args, **kwargs)\n\n def copy_library(self, ext, library_name):\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n libnvfuser_path = os.path.join(\n os.path.join(self.install_dir, \"lib\"), f\"{library_name}{fileext}\"\n )\n assert os.path.exists(libnvfuser_path)\n install_dst = os.path.join(self.build_lib, filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))\n self.copy_file(libnvfuser_path, install_dst)\n\n def build_extension(self, ext):\n if ext.name == \"nvfuser_direct._C_DIRECT\":\n self.copy_library(ext, \"libnvfuser_direct\")\n self.copy_shared_library(\"libnvfuser_codegen.so\")\n else:\n super().build_extension(ext)\n\n def copy_shared_library(self, lib_name):\n # Copy shared library to lib/ subdirectory for package data\n src_path = os.path.join(self.install_dir, \"lib\", lib_name)\n if os.path.exists(src_path):\n dst_dir = os.path.join(self.build_lib, \"nvfuser_common\", \"lib\")\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n dst_path = os.path.join(dst_dir, lib_name)\n self.copy_file(src_path, dst_path)\n\n\nclass concat_third_party_license:","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.build_extension","uri":"program://Fuser/function/python.utils.build_extension#L137-L142","kind":"function","name":"build_extension","path":"python/utils.py","language":"python","start_line":137,"end_line":142,"context_start_line":117,"context_end_line":162,"code":"class build_ext(setuptools.command.build_ext.build_ext):\n def __init__(self, *args, **kwargs):\n install_dir = kwargs.pop(\"install_dir\", \"\")\n self.install_dir = install_dir if install_dir else get_default_install_prefix()\n super().__init__(*args, **kwargs)\n\n def copy_library(self, ext, library_name):\n # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n libnvfuser_path = os.path.join(\n os.path.join(self.install_dir, \"lib\"), f\"{library_name}{fileext}\"\n )\n assert os.path.exists(libnvfuser_path)\n install_dst = os.path.join(self.build_lib, filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))\n self.copy_file(libnvfuser_path, install_dst)\n\n def build_extension(self, ext):\n if ext.name == \"nvfuser_direct._C_DIRECT\":\n self.copy_library(ext, \"libnvfuser_direct\")\n self.copy_shared_library(\"libnvfuser_codegen.so\")\n else:\n super().build_extension(ext)\n\n def copy_shared_library(self, lib_name):\n # Copy shared library to lib/ subdirectory for package data\n src_path = os.path.join(self.install_dir, \"lib\", lib_name)\n if os.path.exists(src_path):\n dst_dir = os.path.join(self.build_lib, \"nvfuser_common\", \"lib\")\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n dst_path = os.path.join(dst_dir, lib_name)\n self.copy_file(src_path, dst_path)\n\n\nclass concat_third_party_license:\n def __init__(self, directory=\"third_party\"):\n self.license_file = \"LICENSE\"\n self.directory = directory\n\n def __enter__(self):\n # read original license file\n with open(self.license_file, \"r\") as f:","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.copy_shared_library","uri":"program://Fuser/function/python.utils.copy_shared_library#L144-L152","kind":"function","name":"copy_shared_library","path":"python/utils.py","language":"python","start_line":144,"end_line":152,"context_start_line":124,"context_end_line":172,"code":" # Copy files on necessity.\n filename = self.get_ext_filename(self.get_ext_fullname(ext.name))\n fileext = os.path.splitext(filename)[1]\n\n libnvfuser_path = os.path.join(\n os.path.join(self.install_dir, \"lib\"), f\"{library_name}{fileext}\"\n )\n assert os.path.exists(libnvfuser_path)\n install_dst = os.path.join(self.build_lib, filename)\n if not os.path.exists(os.path.dirname(install_dst)):\n os.makedirs(os.path.dirname(install_dst))\n self.copy_file(libnvfuser_path, install_dst)\n\n def build_extension(self, ext):\n if ext.name == \"nvfuser_direct._C_DIRECT\":\n self.copy_library(ext, \"libnvfuser_direct\")\n self.copy_shared_library(\"libnvfuser_codegen.so\")\n else:\n super().build_extension(ext)\n\n def copy_shared_library(self, lib_name):\n # Copy shared library to lib/ subdirectory for package data\n src_path = os.path.join(self.install_dir, \"lib\", lib_name)\n if os.path.exists(src_path):\n dst_dir = os.path.join(self.build_lib, \"nvfuser_common\", \"lib\")\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n dst_path = os.path.join(dst_dir, lib_name)\n self.copy_file(src_path, dst_path)\n\n\nclass concat_third_party_license:\n def __init__(self, directory=\"third_party\"):\n self.license_file = \"LICENSE\"\n self.directory = directory\n\n def __enter__(self):\n # read original license file\n with open(self.license_file, \"r\") as f:\n self.nvfuser_license_txt = f.read()\n\n licenses = {\"LICENSE\", \"LICENSE.txt\", \"LICENSE.rst\", \"COPYING.BSD\"}\n\n # aggregated license, we key on project name\n aggregated_license = {}\n for root, dirs, files in os.walk(self.directory):\n license = list(licenses & set(files))\n if license:\n project_name = root.split(\"/\")[-1]","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.__enter__","uri":"program://Fuser/function/python.utils.__enter__#L160-L181","kind":"function","name":"__enter__","path":"python/utils.py","language":"python","start_line":160,"end_line":181,"context_start_line":140,"context_end_line":201,"code":" self.copy_shared_library(\"libnvfuser_codegen.so\")\n else:\n super().build_extension(ext)\n\n def copy_shared_library(self, lib_name):\n # Copy shared library to lib/ subdirectory for package data\n src_path = os.path.join(self.install_dir, \"lib\", lib_name)\n if os.path.exists(src_path):\n dst_dir = os.path.join(self.build_lib, \"nvfuser_common\", \"lib\")\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n dst_path = os.path.join(dst_dir, lib_name)\n self.copy_file(src_path, dst_path)\n\n\nclass concat_third_party_license:\n def __init__(self, directory=\"third_party\"):\n self.license_file = \"LICENSE\"\n self.directory = directory\n\n def __enter__(self):\n # read original license file\n with open(self.license_file, \"r\") as f:\n self.nvfuser_license_txt = f.read()\n\n licenses = {\"LICENSE\", \"LICENSE.txt\", \"LICENSE.rst\", \"COPYING.BSD\"}\n\n # aggregated license, we key on project name\n aggregated_license = {}\n for root, dirs, files in os.walk(self.directory):\n license = list(licenses & set(files))\n if license:\n project_name = root.split(\"/\")[-1]\n # let's worry about multiple license when we see it.\n assert len(license) == 1\n license_entry = os.path.join(root, license[0])\n if project_name in aggregated_license:\n # Only add it if the license is different\n aggregated_license[project_name].append(license_entry)\n else:\n aggregated_license[project_name] = [license_entry]\n return aggregated_license\n\n def __exit__(self, exception_type, exception_value, traceback):\n # restore original license file\n with open(self.license_file, \"w\") as f:\n f.write(self.nvfuser_license_txt)\n\n\ntry:\n from wheel.bdist_wheel import bdist_wheel\nexcept ImportError:\n build_whl = None\nelse:\n\n class build_whl(bdist_wheel):\n def run(self):\n with concat_third_party_license() as tp_licenses:\n if len(tp_licenses) != 0:\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\n\")\n f.write(","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.__exit__","uri":"program://Fuser/function/python.utils.__exit__#L183-L186","kind":"function","name":"__exit__","path":"python/utils.py","language":"python","start_line":183,"end_line":186,"context_start_line":163,"context_end_line":206,"code":" self.nvfuser_license_txt = f.read()\n\n licenses = {\"LICENSE\", \"LICENSE.txt\", \"LICENSE.rst\", \"COPYING.BSD\"}\n\n # aggregated license, we key on project name\n aggregated_license = {}\n for root, dirs, files in os.walk(self.directory):\n license = list(licenses & set(files))\n if license:\n project_name = root.split(\"/\")[-1]\n # let's worry about multiple license when we see it.\n assert len(license) == 1\n license_entry = os.path.join(root, license[0])\n if project_name in aggregated_license:\n # Only add it if the license is different\n aggregated_license[project_name].append(license_entry)\n else:\n aggregated_license[project_name] = [license_entry]\n return aggregated_license\n\n def __exit__(self, exception_type, exception_value, traceback):\n # restore original license file\n with open(self.license_file, \"w\") as f:\n f.write(self.nvfuser_license_txt)\n\n\ntry:\n from wheel.bdist_wheel import bdist_wheel\nexcept ImportError:\n build_whl = None\nelse:\n\n class build_whl(bdist_wheel):\n def run(self):\n with concat_third_party_license() as tp_licenses:\n if len(tp_licenses) != 0:\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\n\")\n f.write(\n \"NVIDIA/fuser depends on libraries with license listed below:\"\n )\n\n for project_name, license_files in tp_licenses.items():\n # check all license files are identical","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.build_whl","uri":"program://Fuser/class/python.utils.build_whl#L195-L231","kind":"class","name":"build_whl","path":"python/utils.py","language":"python","start_line":195,"end_line":231,"context_start_line":175,"context_end_line":251,"code":" license_entry = os.path.join(root, license[0])\n if project_name in aggregated_license:\n # Only add it if the license is different\n aggregated_license[project_name].append(license_entry)\n else:\n aggregated_license[project_name] = [license_entry]\n return aggregated_license\n\n def __exit__(self, exception_type, exception_value, traceback):\n # restore original license file\n with open(self.license_file, \"w\") as f:\n f.write(self.nvfuser_license_txt)\n\n\ntry:\n from wheel.bdist_wheel import bdist_wheel\nexcept ImportError:\n build_whl = None\nelse:\n\n class build_whl(bdist_wheel):\n def run(self):\n with concat_third_party_license() as tp_licenses:\n if len(tp_licenses) != 0:\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\n\")\n f.write(\n \"NVIDIA/fuser depends on libraries with license listed below:\"\n )\n\n for project_name, license_files in tp_licenses.items():\n # check all license files are identical\n with open(license_files[0], \"r\") as f:\n license_ref = f.read()\n\n def check_file(file_name):\n with open(file_name, \"r\") as f:\n return f.read() == license_ref\n\n identical_flag = all(map(check_file, license_files[1:]))\n if not identical_flag:\n raise RuntimeError(\n \"inconsistent license found for project: \",\n project_name,\n \" check its license files under: \",\n license_files,\n )\n\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\nProject Name: \" + project_name)\n f.write(\"\\nLicense Files:\\n\")\n for file_name in license_files:\n f.write(\"\\t\" + file_name)\n f.write(\"\\n\" + license_ref)\n\n # generate whl before we restore LICENSE\n super().run()\n\n\ndef get_cmake_bin():\n # TODO: double check cmake version here and retrieve later version if necessary\n return \"cmake\"\n\n\ndef cmake(config, relative_path):\n from tools.memory import get_available_memory_gb\n\n # make build directories\n cwd = os.path.dirname(os.path.abspath(__file__))\n cmake_build_dir = (\n os.path.join(cwd, \"build\") if not config.build_dir else config.build_dir\n )\n if not os.path.exists(cmake_build_dir):\n os.makedirs(cmake_build_dir)\n\n install_prefix = (\n config.install_dir if config.install_dir else get_default_install_prefix()","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.on_or_off","uri":"program://Fuser/function/python.utils.on_or_off#L260-L261","kind":"function","name":"on_or_off","path":"python/utils.py","language":"python","start_line":260,"end_line":261,"context_start_line":240,"context_end_line":281,"code":" from tools.memory import get_available_memory_gb\n\n # make build directories\n cwd = os.path.dirname(os.path.abspath(__file__))\n cmake_build_dir = (\n os.path.join(cwd, \"build\") if not config.build_dir else config.build_dir\n )\n if not os.path.exists(cmake_build_dir):\n os.makedirs(cmake_build_dir)\n\n install_prefix = (\n config.install_dir if config.install_dir else get_default_install_prefix()\n )\n\n from tools.gen_nvfuser_version import (\n get_pytorch_use_distributed,\n )\n\n pytorch_use_distributed = get_pytorch_use_distributed()\n\n def on_or_off(flag: bool) -> str:\n return \"ON\" if flag else \"OFF\"\n\n # generate cmake directory\n #\n # cmake options are sticky: when -DFOO=... isn't specified, cmake's option\n # FOO prefers the cached value over the default value. This behavior\n # confused me several times (e.g.\n # https://github.com/NVIDIA/Fuser/pull/4319) when I ran `pip install -e`,\n # so I chose to always pass these options even for default values. Doing so\n # explicitly overrides cached values and ensures consistent behavior across\n # clean and dirty builds.\n cmd_str = [\n get_cmake_bin(),\n f\"-DCMAKE_BUILD_TYPE={config.build_type}\",\n f\"-DCMAKE_INSTALL_PREFIX={install_prefix}\",\n f\"-DNVFUSER_CPP_STANDARD={config.cpp_standard}\",\n f\"-DUSE_DISTRIBUTED={pytorch_use_distributed}\",\n f\"-DNVFUSER_BUILD_WITH_ASAN={on_or_off(config.build_with_asan)}\",\n f\"-DNVFUSER_STANDALONE_BUILD_WITH_UCC={on_or_off(config.build_with_ucc)}\",\n f\"-DNVFUSER_EXPLICIT_ERROR_CHECK={on_or_off(config.explicit_error_check)}\",\n f\"-DBUILD_TEST={on_or_off(not config.no_test)}\",","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.clean","uri":"program://Fuser/class/python.utils.clean#L328-L352","kind":"class","name":"clean","path":"python/utils.py","language":"python","start_line":328,"end_line":352,"context_start_line":308,"context_end_line":372,"code":" max_jobs = min(max_jobs, max_jobs_mem)\n\n if not config.cmake_only:\n # build binary\n max_jobs = os.getenv(\"MAX_JOBS\", str(max_jobs))\n print(f\"Using {max_jobs} jobs for compilation\")\n cmd_str = [\n get_cmake_bin(),\n \"--build\",\n cmake_build_dir,\n \"--target\",\n \"install\",\n \"--\",\n \"-j\",\n max_jobs,\n ]\n subprocess.check_call(cmd_str)\n\n\ndef create_clean(relative_path):\n class clean(setuptools.Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n import glob\n\n gitignore_path = os.path.join(relative_path, \".gitignore\")\n assert os.path.exists(gitignore_path)\n with open(gitignore_path, \"r\") as f:\n ignores = f.read()\n for entry in ignores.split(\"\\n\"):\n # ignore comment in .gitignore\n if len(entry) >= 1 and entry[0] != \"#\":\n for filename in glob.glob(entry):\n print(\"removing: \", filename)\n try:\n os.remove(filename)\n except OSError:\n shutil.rmtree(filename, ignore_errors=True)\n\n return clean\n\n\ndef run(config, version_tag, relative_path):\n from setuptools import Extension, setup, find_packages\n\n # NOTE(crcrpar): Deliberately build basically two dynamic libraries here so that they can\n # be treated as \"nvfuser_package_data\".\n if config.build_setup:\n cmake(config, relative_path)\n if not config.cmake_only:\n # NOTE: package include files for cmake\n # TODO(crcrpar): Better avoid hardcoding `libnvfuser_codegen.so`\n # might can be treated by using `exclude_package_data`.\n nvfuser_common_package_data = [\n \"lib/libnvfuser_codegen.so\",\n \"lib/libnvf_cutlass.so\",\n \"include/nvfuser/*.h\",\n \"include/nvfuser/struct.inl\",","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.initialize_options","uri":"program://Fuser/function/python.utils.initialize_options#L331-L332","kind":"function","name":"initialize_options","path":"python/utils.py","language":"python","start_line":331,"end_line":332,"context_start_line":311,"context_end_line":352,"code":" # build binary\n max_jobs = os.getenv(\"MAX_JOBS\", str(max_jobs))\n print(f\"Using {max_jobs} jobs for compilation\")\n cmd_str = [\n get_cmake_bin(),\n \"--build\",\n cmake_build_dir,\n \"--target\",\n \"install\",\n \"--\",\n \"-j\",\n max_jobs,\n ]\n subprocess.check_call(cmd_str)\n\n\ndef create_clean(relative_path):\n class clean(setuptools.Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n import glob\n\n gitignore_path = os.path.join(relative_path, \".gitignore\")\n assert os.path.exists(gitignore_path)\n with open(gitignore_path, \"r\") as f:\n ignores = f.read()\n for entry in ignores.split(\"\\n\"):\n # ignore comment in .gitignore\n if len(entry) >= 1 and entry[0] != \"#\":\n for filename in glob.glob(entry):\n print(\"removing: \", filename)\n try:\n os.remove(filename)\n except OSError:\n shutil.rmtree(filename, ignore_errors=True)","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.finalize_options","uri":"program://Fuser/function/python.utils.finalize_options#L334-L335","kind":"function","name":"finalize_options","path":"python/utils.py","language":"python","start_line":334,"end_line":335,"context_start_line":314,"context_end_line":355,"code":" cmd_str = [\n get_cmake_bin(),\n \"--build\",\n cmake_build_dir,\n \"--target\",\n \"install\",\n \"--\",\n \"-j\",\n max_jobs,\n ]\n subprocess.check_call(cmd_str)\n\n\ndef create_clean(relative_path):\n class clean(setuptools.Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n import glob\n\n gitignore_path = os.path.join(relative_path, \".gitignore\")\n assert os.path.exists(gitignore_path)\n with open(gitignore_path, \"r\") as f:\n ignores = f.read()\n for entry in ignores.split(\"\\n\"):\n # ignore comment in .gitignore\n if len(entry) >= 1 and entry[0] != \"#\":\n for filename in glob.glob(entry):\n print(\"removing: \", filename)\n try:\n os.remove(filename)\n except OSError:\n shutil.rmtree(filename, ignore_errors=True)\n\n return clean\n","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.utils.check_file","uri":"program://Fuser/function/python.utils.check_file#L210-L212","kind":"function","name":"check_file","path":"python/utils.py","language":"python","start_line":210,"end_line":212,"context_start_line":190,"context_end_line":232,"code":" from wheel.bdist_wheel import bdist_wheel\nexcept ImportError:\n build_whl = None\nelse:\n\n class build_whl(bdist_wheel):\n def run(self):\n with concat_third_party_license() as tp_licenses:\n if len(tp_licenses) != 0:\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\n\")\n f.write(\n \"NVIDIA/fuser depends on libraries with license listed below:\"\n )\n\n for project_name, license_files in tp_licenses.items():\n # check all license files are identical\n with open(license_files[0], \"r\") as f:\n license_ref = f.read()\n\n def check_file(file_name):\n with open(file_name, \"r\") as f:\n return f.read() == license_ref\n\n identical_flag = all(map(check_file, license_files[1:]))\n if not identical_flag:\n raise RuntimeError(\n \"inconsistent license found for project: \",\n project_name,\n \" check its license files under: \",\n license_files,\n )\n\n with open(\"LICENSE\", \"a\") as f:\n f.write(\"\\n\\nProject Name: \" + project_name)\n f.write(\"\\nLicense Files:\\n\")\n for file_name in license_files:\n f.write(\"\\t\" + file_name)\n f.write(\"\\n\" + license_ref)\n\n # generate whl before we restore LICENSE\n super().run()\n","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.pytorch_utils","uri":"program://Fuser/module/python.nvfuser_direct.pytorch_utils#L1-L189","kind":"module","name":"python.nvfuser_direct.pytorch_utils","path":"python/nvfuser_direct/pytorch_utils.py","language":"python","start_line":1,"end_line":189,"context_start_line":1,"context_end_line":189,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\n\nfrom ._C_DIRECT import DataType\n\nimport ctypes\nfrom typing import Type, Union, Tuple\nimport functools\n\nNumberTypeType = Union[Type[bool], Type[int], Type[float], Type[complex]]\n\n_torch_dtype_to_nvfuser_dtype_map = {\n torch.cdouble: DataType.ComplexDouble,\n torch.cfloat: DataType.ComplexFloat,\n torch.double: DataType.Double,\n torch.float: DataType.Float,\n torch.half: DataType.Half,\n torch.bfloat16: DataType.BFloat16,\n torch.float8_e4m3fn: DataType.Float8_e4m3fn,\n torch.float8_e5m2: DataType.Float8_e5m2,\n torch.float8_e8m0fnu: DataType.Float8_e8m0fnu,\n torch.long: DataType.Int,\n torch.int: DataType.Int32,\n torch.bool: DataType.Bool,\n # Python scalars\n complex: DataType.ComplexDouble,\n float: DataType.Double,\n int: DataType.Int,\n bool: DataType.Bool,\n}\n\nif hasattr(torch, \"float4_e2m1fn_x2\"):\n _torch_dtype_to_nvfuser_dtype_map[\n torch.float4_e2m1fn_x2\n ] = DataType.Float4_e2m1fn_x2\n\n\ndef python_scalar_to_nvfuser_dtype(a: Union[int, float, complex, bool]):\n return _torch_dtype_to_nvfuser_dtype_map[type(a)]\n\n\ndef torch_dtype_to_nvfuser_dtype(dtype: Union[torch.dtype, NumberTypeType]):\n \"\"\"\n Translates from torch.dtype to nvFuser's DataType enum\n \"\"\"\n return _torch_dtype_to_nvfuser_dtype_map[dtype]\n\n\ndef retry_on_oom_or_skip_test(func):\n \"\"\"Decorator: upon torch.OutOfMemoryError clear the cache and retry test\"\"\"\n\n @functools.wraps(func)\n def retried_func(*args, **kwargs):\n try:\n output = func(*args, **kwargs)\n except torch.OutOfMemoryError:\n pass\n else:\n return output\n\n # We have hit an OOM error, so clear the cache and retry\n gc.collect()\n torch.cuda.empty_cache()\n\n try:\n output = func(*args, **kwargs)\n except torch.OutOfMemoryError as e:\n # If we hit an OOM this time, then skip the test\n import pytest\n\n pytest.skip(f\"Test failed due to OutOfMemoryError: {e}\")\n return\n\n return output\n\n return retried_func\n\n\ndef get_device_properties() -> Tuple[int, float]:\n \"\"\"\n Computes device properties using ctypes and cuda.\n Note: Consider using CUDA-Python when CUDA support >= 12.0.\n \"\"\"\n libnames = (\"libcuda.so\", \"libcuda.dylib\", \"nvcuda.dll\", \"cuda.dll\")\n for libname in libnames:\n try:\n cuda = ctypes.CDLL(libname)\n except OSError:\n continue\n else:\n break\n else:\n raise OSError(\"could not load any of: \" + \" \".join(libnames))\n\n # Device attribute enums (taken from cuda.h)\n # https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES_1ge12b8a782bebe21b1ac0091bf9f4e2a3\n\n CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1\n CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = 8\n CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = 12\n CU_DEVICE_ATTRIBUTE_CLOCK_RATE = 13\n CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE = 36\n CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = 37\n CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE = 38\n CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR = 39\n\n device_properties = {}\n device = torch.cuda.current_device()\n cuda_properties = torch.cuda.get_device_properties(device)\n\n device_properties[\"gpu_name\"] = cuda_properties.name\n device_properties[\"gpu_compute_capability_major\"] = cuda_properties.major\n device_properties[\"gpu_compute_capability_minor\"] = cuda_properties.minor\n device_properties[\"gpu_gmem_bytes\"] = cuda_properties.total_memory\n device_properties[\"gpu_sm_count\"] = cuda_properties.multi_processor_count\n\n max_threads_per_block = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(max_threads_per_block),\n CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK,\n device,\n )\n device_properties[\"gpu_max_threads_per_block\"] = max_threads_per_block.value\n\n smem_per_block = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(smem_per_block),\n CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK,\n device,\n )\n device_properties[\"gpu_smem_bytes_per_block\"] = smem_per_block.value\n\n max_reg_per_block = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(max_reg_per_block),\n CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK,\n device,\n )\n device_properties[\"gpu_regs_per_block\"] = max_reg_per_block.value\n\n max_clock_khz = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(max_clock_khz),\n CU_DEVICE_ATTRIBUTE_CLOCK_RATE,\n device,\n )\n device_properties[\"gpu_clock_rate_khz\"] = max_clock_khz.value\n\n l2_cache_size = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(l2_cache_size), CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, device\n )\n device_properties[\"gpu_l2_bytes\"] = l2_cache_size.value\n\n memory_clock_rate = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(memory_clock_rate), CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, device\n )\n device_properties[\"gpu_mem_clock_khz\"] = memory_clock_rate.value\n\n memory_bus_width = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(memory_bus_width),\n CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH,\n device,\n )\n device_properties[\"gpu_mem_bus_width\"] = memory_bus_width.value\n\n max_threads_per_sm = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(max_threads_per_sm),\n CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,\n device,\n )\n device_properties[\"gpu_max_threads_per_sm\"] = max_threads_per_sm.value\n\n # Compute peak bandwidth in GBps\n peak_bandwidth = (2 * memory_bus_width.value * memory_clock_rate.value) / (1e6 * 8)\n device_properties[\"gpu_peak_bandwidth_gbps\"] = peak_bandwidth\n\n return device_properties\n\n\nDEVICE_PROPERTIES = None\nif torch.cuda.is_available():\n # Loading libraries will raise errors on non-CUDA machines.\n DEVICE_PROPERTIES = get_device_properties()","source_hash":"8e20a062cb51a307028201b57302577fe3a6dd739145003dc3b3e352197e65e3","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.pytorch_utils.python_scalar_to_nvfuser_dtype","uri":"program://Fuser/function/python.nvfuser_direct.pytorch_utils.python_scalar_to_nvfuser_dtype#L40-L41","kind":"function","name":"python_scalar_to_nvfuser_dtype","path":"python/nvfuser_direct/pytorch_utils.py","language":"python","start_line":40,"end_line":41,"context_start_line":20,"context_end_line":61,"code":" torch.bfloat16: DataType.BFloat16,\n torch.float8_e4m3fn: DataType.Float8_e4m3fn,\n torch.float8_e5m2: DataType.Float8_e5m2,\n torch.float8_e8m0fnu: DataType.Float8_e8m0fnu,\n torch.long: DataType.Int,\n torch.int: DataType.Int32,\n torch.bool: DataType.Bool,\n # Python scalars\n complex: DataType.ComplexDouble,\n float: DataType.Double,\n int: DataType.Int,\n bool: DataType.Bool,\n}\n\nif hasattr(torch, \"float4_e2m1fn_x2\"):\n _torch_dtype_to_nvfuser_dtype_map[\n torch.float4_e2m1fn_x2\n ] = DataType.Float4_e2m1fn_x2\n\n\ndef python_scalar_to_nvfuser_dtype(a: Union[int, float, complex, bool]):\n return _torch_dtype_to_nvfuser_dtype_map[type(a)]\n\n\ndef torch_dtype_to_nvfuser_dtype(dtype: Union[torch.dtype, NumberTypeType]):\n \"\"\"\n Translates from torch.dtype to nvFuser's DataType enum\n \"\"\"\n return _torch_dtype_to_nvfuser_dtype_map[dtype]\n\n\ndef retry_on_oom_or_skip_test(func):\n \"\"\"Decorator: upon torch.OutOfMemoryError clear the cache and retry test\"\"\"\n\n @functools.wraps(func)\n def retried_func(*args, **kwargs):\n try:\n output = func(*args, **kwargs)\n except torch.OutOfMemoryError:\n pass\n else:\n return output","source_hash":"8e20a062cb51a307028201b57302577fe3a6dd739145003dc3b3e352197e65e3","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.pytorch_utils.torch_dtype_to_nvfuser_dtype","uri":"program://Fuser/function/python.nvfuser_direct.pytorch_utils.torch_dtype_to_nvfuser_dtype#L44-L48","kind":"function","name":"torch_dtype_to_nvfuser_dtype","path":"python/nvfuser_direct/pytorch_utils.py","language":"python","start_line":44,"end_line":48,"context_start_line":24,"context_end_line":68,"code":" torch.long: DataType.Int,\n torch.int: DataType.Int32,\n torch.bool: DataType.Bool,\n # Python scalars\n complex: DataType.ComplexDouble,\n float: DataType.Double,\n int: DataType.Int,\n bool: DataType.Bool,\n}\n\nif hasattr(torch, \"float4_e2m1fn_x2\"):\n _torch_dtype_to_nvfuser_dtype_map[\n torch.float4_e2m1fn_x2\n ] = DataType.Float4_e2m1fn_x2\n\n\ndef python_scalar_to_nvfuser_dtype(a: Union[int, float, complex, bool]):\n return _torch_dtype_to_nvfuser_dtype_map[type(a)]\n\n\ndef torch_dtype_to_nvfuser_dtype(dtype: Union[torch.dtype, NumberTypeType]):\n \"\"\"\n Translates from torch.dtype to nvFuser's DataType enum\n \"\"\"\n return _torch_dtype_to_nvfuser_dtype_map[dtype]\n\n\ndef retry_on_oom_or_skip_test(func):\n \"\"\"Decorator: upon torch.OutOfMemoryError clear the cache and retry test\"\"\"\n\n @functools.wraps(func)\n def retried_func(*args, **kwargs):\n try:\n output = func(*args, **kwargs)\n except torch.OutOfMemoryError:\n pass\n else:\n return output\n\n # We have hit an OOM error, so clear the cache and retry\n gc.collect()\n torch.cuda.empty_cache()\n\n try:\n output = func(*args, **kwargs)","source_hash":"8e20a062cb51a307028201b57302577fe3a6dd739145003dc3b3e352197e65e3","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.pytorch_utils.retry_on_oom_or_skip_test","uri":"program://Fuser/function/python.nvfuser_direct.pytorch_utils.retry_on_oom_or_skip_test#L51-L78","kind":"function","name":"retry_on_oom_or_skip_test","path":"python/nvfuser_direct/pytorch_utils.py","language":"python","start_line":51,"end_line":78,"context_start_line":31,"context_end_line":98,"code":" bool: DataType.Bool,\n}\n\nif hasattr(torch, \"float4_e2m1fn_x2\"):\n _torch_dtype_to_nvfuser_dtype_map[\n torch.float4_e2m1fn_x2\n ] = DataType.Float4_e2m1fn_x2\n\n\ndef python_scalar_to_nvfuser_dtype(a: Union[int, float, complex, bool]):\n return _torch_dtype_to_nvfuser_dtype_map[type(a)]\n\n\ndef torch_dtype_to_nvfuser_dtype(dtype: Union[torch.dtype, NumberTypeType]):\n \"\"\"\n Translates from torch.dtype to nvFuser's DataType enum\n \"\"\"\n return _torch_dtype_to_nvfuser_dtype_map[dtype]\n\n\ndef retry_on_oom_or_skip_test(func):\n \"\"\"Decorator: upon torch.OutOfMemoryError clear the cache and retry test\"\"\"\n\n @functools.wraps(func)\n def retried_func(*args, **kwargs):\n try:\n output = func(*args, **kwargs)\n except torch.OutOfMemoryError:\n pass\n else:\n return output\n\n # We have hit an OOM error, so clear the cache and retry\n gc.collect()\n torch.cuda.empty_cache()\n\n try:\n output = func(*args, **kwargs)\n except torch.OutOfMemoryError as e:\n # If we hit an OOM this time, then skip the test\n import pytest\n\n pytest.skip(f\"Test failed due to OutOfMemoryError: {e}\")\n return\n\n return output\n\n return retried_func\n\n\ndef get_device_properties() -> Tuple[int, float]:\n \"\"\"\n Computes device properties using ctypes and cuda.\n Note: Consider using CUDA-Python when CUDA support >= 12.0.\n \"\"\"\n libnames = (\"libcuda.so\", \"libcuda.dylib\", \"nvcuda.dll\", \"cuda.dll\")\n for libname in libnames:\n try:\n cuda = ctypes.CDLL(libname)\n except OSError:\n continue\n else:\n break\n else:\n raise OSError(\"could not load any of: \" + \" \".join(libnames))\n\n # Device attribute enums (taken from cuda.h)\n # https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES_1ge12b8a782bebe21b1ac0091bf9f4e2a3","source_hash":"8e20a062cb51a307028201b57302577fe3a6dd739145003dc3b3e352197e65e3","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.pytorch_utils.get_device_properties","uri":"program://Fuser/function/python.nvfuser_direct.pytorch_utils.get_device_properties#L81-L183","kind":"function","name":"get_device_properties","path":"python/nvfuser_direct/pytorch_utils.py","language":"python","start_line":81,"end_line":183,"context_start_line":61,"context_end_line":189,"code":" return output\n\n # We have hit an OOM error, so clear the cache and retry\n gc.collect()\n torch.cuda.empty_cache()\n\n try:\n output = func(*args, **kwargs)\n except torch.OutOfMemoryError as e:\n # If we hit an OOM this time, then skip the test\n import pytest\n\n pytest.skip(f\"Test failed due to OutOfMemoryError: {e}\")\n return\n\n return output\n\n return retried_func\n\n\ndef get_device_properties() -> Tuple[int, float]:\n \"\"\"\n Computes device properties using ctypes and cuda.\n Note: Consider using CUDA-Python when CUDA support >= 12.0.\n \"\"\"\n libnames = (\"libcuda.so\", \"libcuda.dylib\", \"nvcuda.dll\", \"cuda.dll\")\n for libname in libnames:\n try:\n cuda = ctypes.CDLL(libname)\n except OSError:\n continue\n else:\n break\n else:\n raise OSError(\"could not load any of: \" + \" \".join(libnames))\n\n # Device attribute enums (taken from cuda.h)\n # https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES_1ge12b8a782bebe21b1ac0091bf9f4e2a3\n\n CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1\n CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = 8\n CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = 12\n CU_DEVICE_ATTRIBUTE_CLOCK_RATE = 13\n CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE = 36\n CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = 37\n CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE = 38\n CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR = 39\n\n device_properties = {}\n device = torch.cuda.current_device()\n cuda_properties = torch.cuda.get_device_properties(device)\n\n device_properties[\"gpu_name\"] = cuda_properties.name\n device_properties[\"gpu_compute_capability_major\"] = cuda_properties.major\n device_properties[\"gpu_compute_capability_minor\"] = cuda_properties.minor\n device_properties[\"gpu_gmem_bytes\"] = cuda_properties.total_memory\n device_properties[\"gpu_sm_count\"] = cuda_properties.multi_processor_count\n\n max_threads_per_block = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(max_threads_per_block),\n CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK,\n device,\n )\n device_properties[\"gpu_max_threads_per_block\"] = max_threads_per_block.value\n\n smem_per_block = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(smem_per_block),\n CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK,\n device,\n )\n device_properties[\"gpu_smem_bytes_per_block\"] = smem_per_block.value\n\n max_reg_per_block = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(max_reg_per_block),\n CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK,\n device,\n )\n device_properties[\"gpu_regs_per_block\"] = max_reg_per_block.value\n\n max_clock_khz = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(max_clock_khz),\n CU_DEVICE_ATTRIBUTE_CLOCK_RATE,\n device,\n )\n device_properties[\"gpu_clock_rate_khz\"] = max_clock_khz.value\n\n l2_cache_size = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(l2_cache_size), CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, device\n )\n device_properties[\"gpu_l2_bytes\"] = l2_cache_size.value\n\n memory_clock_rate = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(memory_clock_rate), CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, device\n )\n device_properties[\"gpu_mem_clock_khz\"] = memory_clock_rate.value\n\n memory_bus_width = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(memory_bus_width),\n CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH,\n device,\n )\n device_properties[\"gpu_mem_bus_width\"] = memory_bus_width.value\n\n max_threads_per_sm = ctypes.c_int()\n cuda.cuDeviceGetAttribute(\n ctypes.byref(max_threads_per_sm),\n CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,\n device,\n )\n device_properties[\"gpu_max_threads_per_sm\"] = max_threads_per_sm.value\n\n # Compute peak bandwidth in GBps\n peak_bandwidth = (2 * memory_bus_width.value * memory_clock_rate.value) / (1e6 * 8)\n device_properties[\"gpu_peak_bandwidth_gbps\"] = peak_bandwidth\n\n return device_properties\n\n\nDEVICE_PROPERTIES = None\nif torch.cuda.is_available():\n # Loading libraries will raise errors on non-CUDA machines.\n DEVICE_PROPERTIES = get_device_properties()","source_hash":"8e20a062cb51a307028201b57302577fe3a6dd739145003dc3b3e352197e65e3","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.pytorch_utils.retried_func","uri":"program://Fuser/function/python.nvfuser_direct.pytorch_utils.retried_func#L55-L76","kind":"function","name":"retried_func","path":"python/nvfuser_direct/pytorch_utils.py","language":"python","start_line":55,"end_line":76,"context_start_line":35,"context_end_line":96,"code":" _torch_dtype_to_nvfuser_dtype_map[\n torch.float4_e2m1fn_x2\n ] = DataType.Float4_e2m1fn_x2\n\n\ndef python_scalar_to_nvfuser_dtype(a: Union[int, float, complex, bool]):\n return _torch_dtype_to_nvfuser_dtype_map[type(a)]\n\n\ndef torch_dtype_to_nvfuser_dtype(dtype: Union[torch.dtype, NumberTypeType]):\n \"\"\"\n Translates from torch.dtype to nvFuser's DataType enum\n \"\"\"\n return _torch_dtype_to_nvfuser_dtype_map[dtype]\n\n\ndef retry_on_oom_or_skip_test(func):\n \"\"\"Decorator: upon torch.OutOfMemoryError clear the cache and retry test\"\"\"\n\n @functools.wraps(func)\n def retried_func(*args, **kwargs):\n try:\n output = func(*args, **kwargs)\n except torch.OutOfMemoryError:\n pass\n else:\n return output\n\n # We have hit an OOM error, so clear the cache and retry\n gc.collect()\n torch.cuda.empty_cache()\n\n try:\n output = func(*args, **kwargs)\n except torch.OutOfMemoryError as e:\n # If we hit an OOM this time, then skip the test\n import pytest\n\n pytest.skip(f\"Test failed due to OutOfMemoryError: {e}\")\n return\n\n return output\n\n return retried_func\n\n\ndef get_device_properties() -> Tuple[int, float]:\n \"\"\"\n Computes device properties using ctypes and cuda.\n Note: Consider using CUDA-Python when CUDA support >= 12.0.\n \"\"\"\n libnames = (\"libcuda.so\", \"libcuda.dylib\", \"nvcuda.dll\", \"cuda.dll\")\n for libname in libnames:\n try:\n cuda = ctypes.CDLL(libname)\n except OSError:\n continue\n else:\n break\n else:\n raise OSError(\"could not load any of: \" + \" \".join(libnames))\n","source_hash":"8e20a062cb51a307028201b57302577fe3a6dd739145003dc3b3e352197e65e3","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.nvfuser_direct_version","uri":"program://Fuser/module/python.nvfuser_direct.nvfuser_direct_version#L1-L69","kind":"module","name":"python.nvfuser_direct.nvfuser_direct_version","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":1,"end_line":69,"context_start_line":1,"context_end_line":69,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom typing import Any\nfrom .version import _version_str\n\n__all__ = [\"NvfuserVersion\", \"Version\"]\n\n\nclass _LazyImport:\n \"\"\"Wraps around classes lazy imported from packaging.version\n Output of the function v in following snippets are identical:\n from packaging.version import Version\n def v():\n return Version('1.2.3')\n and\n Version = _LazyImport('Version')\n def v():\n return Version('1.2.3')\n The difference here is that in later example imports\n do not happen until v is called\n \"\"\"\n\n def __init__(self, cls_name: str) -> None:\n self._cls_name = cls_name\n\n def get_cls(self):\n try:\n import packaging.version # type: ignore[import]\n except ImportError:\n # If packaging isn't installed, try and use the vendored copy\n # in pkg_resources\n from pkg_resources import packaging # type: ignore[attr-defined, no-redef]\n return getattr(packaging.version, self._cls_name)\n\n def __call__(self, *args, **kwargs):\n return self.get_cls()(*args, **kwargs)\n\n def __instancecheck__(self, obj):\n return isinstance(obj, self.get_cls())\n\n\nVersion = _LazyImport(\"Version\")\n\n\nclass NvfuserVersion(str):\n @classmethod\n def _convert_to_version(cls, ver: Any) -> Version:\n if isinstance(ver, str):\n return Version(ver.split(\"+\")[0])\n elif isinstance(ver, Version.get_cls()):\n return ver\n else:\n raise ValueError(\"can't convert {} to Version\".format(ver))\n\n def _cmp_version(self, other: Any, method: str) -> Version:\n return getattr(NvfuserVersion._convert_to_version(self), method)(\n NvfuserVersion._convert_to_version(other)\n )\n\n\nfor cmp_method in [\"__gt__\", \"__lt__\", \"__eq__\", \"__ge__\", \"__le__\"]:\n setattr(\n NvfuserVersion,\n cmp_method,\n lambda x, y, method=cmp_method: x._cmp_version(y, method),\n )\n\n__version__ = NvfuserVersion(_version_str)","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.nvfuser_direct_version._LazyImport","uri":"program://Fuser/class/python.nvfuser_direct.nvfuser_direct_version._LazyImport#L10-L40","kind":"class","name":"_LazyImport","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":10,"end_line":40,"context_start_line":1,"context_end_line":60,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom typing import Any\nfrom .version import _version_str\n\n__all__ = [\"NvfuserVersion\", \"Version\"]\n\n\nclass _LazyImport:\n \"\"\"Wraps around classes lazy imported from packaging.version\n Output of the function v in following snippets are identical:\n from packaging.version import Version\n def v():\n return Version('1.2.3')\n and\n Version = _LazyImport('Version')\n def v():\n return Version('1.2.3')\n The difference here is that in later example imports\n do not happen until v is called\n \"\"\"\n\n def __init__(self, cls_name: str) -> None:\n self._cls_name = cls_name\n\n def get_cls(self):\n try:\n import packaging.version # type: ignore[import]\n except ImportError:\n # If packaging isn't installed, try and use the vendored copy\n # in pkg_resources\n from pkg_resources import packaging # type: ignore[attr-defined, no-redef]\n return getattr(packaging.version, self._cls_name)\n\n def __call__(self, *args, **kwargs):\n return self.get_cls()(*args, **kwargs)\n\n def __instancecheck__(self, obj):\n return isinstance(obj, self.get_cls())\n\n\nVersion = _LazyImport(\"Version\")\n\n\nclass NvfuserVersion(str):\n @classmethod\n def _convert_to_version(cls, ver: Any) -> Version:\n if isinstance(ver, str):\n return Version(ver.split(\"+\")[0])\n elif isinstance(ver, Version.get_cls()):\n return ver\n else:\n raise ValueError(\"can't convert {} to Version\".format(ver))\n\n def _cmp_version(self, other: Any, method: str) -> Version:\n return getattr(NvfuserVersion._convert_to_version(self), method)(\n NvfuserVersion._convert_to_version(other)\n )\n","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.nvfuser_direct_version.NvfuserVersion","uri":"program://Fuser/class/python.nvfuser_direct.nvfuser_direct_version.NvfuserVersion#L46-L59","kind":"class","name":"NvfuserVersion","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":46,"end_line":59,"context_start_line":26,"context_end_line":69,"code":"\n def get_cls(self):\n try:\n import packaging.version # type: ignore[import]\n except ImportError:\n # If packaging isn't installed, try and use the vendored copy\n # in pkg_resources\n from pkg_resources import packaging # type: ignore[attr-defined, no-redef]\n return getattr(packaging.version, self._cls_name)\n\n def __call__(self, *args, **kwargs):\n return self.get_cls()(*args, **kwargs)\n\n def __instancecheck__(self, obj):\n return isinstance(obj, self.get_cls())\n\n\nVersion = _LazyImport(\"Version\")\n\n\nclass NvfuserVersion(str):\n @classmethod\n def _convert_to_version(cls, ver: Any) -> Version:\n if isinstance(ver, str):\n return Version(ver.split(\"+\")[0])\n elif isinstance(ver, Version.get_cls()):\n return ver\n else:\n raise ValueError(\"can't convert {} to Version\".format(ver))\n\n def _cmp_version(self, other: Any, method: str) -> Version:\n return getattr(NvfuserVersion._convert_to_version(self), method)(\n NvfuserVersion._convert_to_version(other)\n )\n\n\nfor cmp_method in [\"__gt__\", \"__lt__\", \"__eq__\", \"__ge__\", \"__le__\"]:\n setattr(\n NvfuserVersion,\n cmp_method,\n lambda x, y, method=cmp_method: x._cmp_version(y, method),\n )\n\n__version__ = NvfuserVersion(_version_str)","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.nvfuser_direct_version.__init__","uri":"program://Fuser/function/python.nvfuser_direct.nvfuser_direct_version.__init__#L24-L25","kind":"function","name":"__init__","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":24,"end_line":25,"context_start_line":4,"context_end_line":45,"code":"from typing import Any\nfrom .version import _version_str\n\n__all__ = [\"NvfuserVersion\", \"Version\"]\n\n\nclass _LazyImport:\n \"\"\"Wraps around classes lazy imported from packaging.version\n Output of the function v in following snippets are identical:\n from packaging.version import Version\n def v():\n return Version('1.2.3')\n and\n Version = _LazyImport('Version')\n def v():\n return Version('1.2.3')\n The difference here is that in later example imports\n do not happen until v is called\n \"\"\"\n\n def __init__(self, cls_name: str) -> None:\n self._cls_name = cls_name\n\n def get_cls(self):\n try:\n import packaging.version # type: ignore[import]\n except ImportError:\n # If packaging isn't installed, try and use the vendored copy\n # in pkg_resources\n from pkg_resources import packaging # type: ignore[attr-defined, no-redef]\n return getattr(packaging.version, self._cls_name)\n\n def __call__(self, *args, **kwargs):\n return self.get_cls()(*args, **kwargs)\n\n def __instancecheck__(self, obj):\n return isinstance(obj, self.get_cls())\n\n\nVersion = _LazyImport(\"Version\")\n\n","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.nvfuser_direct_version.get_cls","uri":"program://Fuser/function/python.nvfuser_direct.nvfuser_direct_version.get_cls#L27-L34","kind":"function","name":"get_cls","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":27,"end_line":34,"context_start_line":7,"context_end_line":54,"code":"__all__ = [\"NvfuserVersion\", \"Version\"]\n\n\nclass _LazyImport:\n \"\"\"Wraps around classes lazy imported from packaging.version\n Output of the function v in following snippets are identical:\n from packaging.version import Version\n def v():\n return Version('1.2.3')\n and\n Version = _LazyImport('Version')\n def v():\n return Version('1.2.3')\n The difference here is that in later example imports\n do not happen until v is called\n \"\"\"\n\n def __init__(self, cls_name: str) -> None:\n self._cls_name = cls_name\n\n def get_cls(self):\n try:\n import packaging.version # type: ignore[import]\n except ImportError:\n # If packaging isn't installed, try and use the vendored copy\n # in pkg_resources\n from pkg_resources import packaging # type: ignore[attr-defined, no-redef]\n return getattr(packaging.version, self._cls_name)\n\n def __call__(self, *args, **kwargs):\n return self.get_cls()(*args, **kwargs)\n\n def __instancecheck__(self, obj):\n return isinstance(obj, self.get_cls())\n\n\nVersion = _LazyImport(\"Version\")\n\n\nclass NvfuserVersion(str):\n @classmethod\n def _convert_to_version(cls, ver: Any) -> Version:\n if isinstance(ver, str):\n return Version(ver.split(\"+\")[0])\n elif isinstance(ver, Version.get_cls()):\n return ver\n else:\n raise ValueError(\"can't convert {} to Version\".format(ver))","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.nvfuser_direct_version.__call__","uri":"program://Fuser/function/python.nvfuser_direct.nvfuser_direct_version.__call__#L36-L37","kind":"function","name":"__call__","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":36,"end_line":37,"context_start_line":16,"context_end_line":57,"code":" and\n Version = _LazyImport('Version')\n def v():\n return Version('1.2.3')\n The difference here is that in later example imports\n do not happen until v is called\n \"\"\"\n\n def __init__(self, cls_name: str) -> None:\n self._cls_name = cls_name\n\n def get_cls(self):\n try:\n import packaging.version # type: ignore[import]\n except ImportError:\n # If packaging isn't installed, try and use the vendored copy\n # in pkg_resources\n from pkg_resources import packaging # type: ignore[attr-defined, no-redef]\n return getattr(packaging.version, self._cls_name)\n\n def __call__(self, *args, **kwargs):\n return self.get_cls()(*args, **kwargs)\n\n def __instancecheck__(self, obj):\n return isinstance(obj, self.get_cls())\n\n\nVersion = _LazyImport(\"Version\")\n\n\nclass NvfuserVersion(str):\n @classmethod\n def _convert_to_version(cls, ver: Any) -> Version:\n if isinstance(ver, str):\n return Version(ver.split(\"+\")[0])\n elif isinstance(ver, Version.get_cls()):\n return ver\n else:\n raise ValueError(\"can't convert {} to Version\".format(ver))\n\n def _cmp_version(self, other: Any, method: str) -> Version:\n return getattr(NvfuserVersion._convert_to_version(self), method)(","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.nvfuser_direct_version.__instancecheck__","uri":"program://Fuser/function/python.nvfuser_direct.nvfuser_direct_version.__instancecheck__#L39-L40","kind":"function","name":"__instancecheck__","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":39,"end_line":40,"context_start_line":19,"context_end_line":60,"code":" return Version('1.2.3')\n The difference here is that in later example imports\n do not happen until v is called\n \"\"\"\n\n def __init__(self, cls_name: str) -> None:\n self._cls_name = cls_name\n\n def get_cls(self):\n try:\n import packaging.version # type: ignore[import]\n except ImportError:\n # If packaging isn't installed, try and use the vendored copy\n # in pkg_resources\n from pkg_resources import packaging # type: ignore[attr-defined, no-redef]\n return getattr(packaging.version, self._cls_name)\n\n def __call__(self, *args, **kwargs):\n return self.get_cls()(*args, **kwargs)\n\n def __instancecheck__(self, obj):\n return isinstance(obj, self.get_cls())\n\n\nVersion = _LazyImport(\"Version\")\n\n\nclass NvfuserVersion(str):\n @classmethod\n def _convert_to_version(cls, ver: Any) -> Version:\n if isinstance(ver, str):\n return Version(ver.split(\"+\")[0])\n elif isinstance(ver, Version.get_cls()):\n return ver\n else:\n raise ValueError(\"can't convert {} to Version\".format(ver))\n\n def _cmp_version(self, other: Any, method: str) -> Version:\n return getattr(NvfuserVersion._convert_to_version(self), method)(\n NvfuserVersion._convert_to_version(other)\n )\n","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.nvfuser_direct_version._convert_to_version","uri":"program://Fuser/function/python.nvfuser_direct.nvfuser_direct_version._convert_to_version#L48-L54","kind":"function","name":"_convert_to_version","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":48,"end_line":54,"context_start_line":28,"context_end_line":69,"code":" try:\n import packaging.version # type: ignore[import]\n except ImportError:\n # If packaging isn't installed, try and use the vendored copy\n # in pkg_resources\n from pkg_resources import packaging # type: ignore[attr-defined, no-redef]\n return getattr(packaging.version, self._cls_name)\n\n def __call__(self, *args, **kwargs):\n return self.get_cls()(*args, **kwargs)\n\n def __instancecheck__(self, obj):\n return isinstance(obj, self.get_cls())\n\n\nVersion = _LazyImport(\"Version\")\n\n\nclass NvfuserVersion(str):\n @classmethod\n def _convert_to_version(cls, ver: Any) -> Version:\n if isinstance(ver, str):\n return Version(ver.split(\"+\")[0])\n elif isinstance(ver, Version.get_cls()):\n return ver\n else:\n raise ValueError(\"can't convert {} to Version\".format(ver))\n\n def _cmp_version(self, other: Any, method: str) -> Version:\n return getattr(NvfuserVersion._convert_to_version(self), method)(\n NvfuserVersion._convert_to_version(other)\n )\n\n\nfor cmp_method in [\"__gt__\", \"__lt__\", \"__eq__\", \"__ge__\", \"__le__\"]:\n setattr(\n NvfuserVersion,\n cmp_method,\n lambda x, y, method=cmp_method: x._cmp_version(y, method),\n )\n\n__version__ = NvfuserVersion(_version_str)","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.nvfuser_direct_version._cmp_version","uri":"program://Fuser/function/python.nvfuser_direct.nvfuser_direct_version._cmp_version#L56-L59","kind":"function","name":"_cmp_version","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":56,"end_line":59,"context_start_line":36,"context_end_line":69,"code":" def __call__(self, *args, **kwargs):\n return self.get_cls()(*args, **kwargs)\n\n def __instancecheck__(self, obj):\n return isinstance(obj, self.get_cls())\n\n\nVersion = _LazyImport(\"Version\")\n\n\nclass NvfuserVersion(str):\n @classmethod\n def _convert_to_version(cls, ver: Any) -> Version:\n if isinstance(ver, str):\n return Version(ver.split(\"+\")[0])\n elif isinstance(ver, Version.get_cls()):\n return ver\n else:\n raise ValueError(\"can't convert {} to Version\".format(ver))\n\n def _cmp_version(self, other: Any, method: str) -> Version:\n return getattr(NvfuserVersion._convert_to_version(self), method)(\n NvfuserVersion._convert_to_version(other)\n )\n\n\nfor cmp_method in [\"__gt__\", \"__lt__\", \"__eq__\", \"__ge__\", \"__le__\"]:\n setattr(\n NvfuserVersion,\n cmp_method,\n lambda x, y, method=cmp_method: x._cmp_version(y, method),\n )\n\n__version__ = NvfuserVersion(_version_str)","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils","uri":"program://Fuser/module/python.nvfuser_direct.benchmark_utils#L1-L161","kind":"module","name":"python.nvfuser_direct.benchmark_utils","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":1,"end_line":161,"context_start_line":1,"context_end_line":161,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\nfrom cupti import cupti\nimport cxxfilt\nimport pytest\nfrom ._C_DIRECT import get_fusion_profile\n\n\n# Base class for all timers used by pytest-benchmark.\nclass Timer:\n def __init__(self):\n self.current_time = 0.0\n\n def _increment_global_time(self, elapsed_time: float) -> None:\n self.current_time += elapsed_time\n\n def __call__(self):\n raise NotImplementedError(\"Subclass must implement this method\")\n\n def cleanup(self):\n pass\n\n\ndef demangle_kernel_name(mangled_name):\n try:\n return cxxfilt.demangle(mangled_name)\n except Exception:\n return mangled_name # Return original if demangling fails\n\n\ndef cupti_call_safe(func, *args):\n \"\"\"Wrapper for CUPTI calls. Failing CUPTI calls will exit the program.\"\"\"\n try:\n return func(*args)\n except Exception as e:\n print(f\"CUPTI call {func.__name__} failed: {e}\")\n pytest.exit(1)\n\n\nclass CuptiProfiler:\n # List of activities to be recorded by CUPTI.\n activity_kinds: list[cupti.ActivityKind] = [\n cupti.ActivityKind.CONCURRENT_KERNEL,\n ]\n\n # Private class variable to store the subscriber handle.\n __subscriber_handle = None\n\n def _error_if_not_valid(self) -> None:\n if not self.is_valid:\n raise RuntimeError(\n \"CuptiProfiler is not valid. \" \"This instance has been torn down.\"\n )\n\n def _func_buffer_requested(self) -> tuple[int, int]:\n # 8MB buffer size as recommended by CUPTI samples.\n # max_num_records=0 indicates the buffer is filled with as many records as possible.\n buffer_size = 8 * 1024 * 1024\n max_num_records = 0\n return buffer_size, max_num_records\n\n def _func_buffer_completed(self, activities: list[cupti.ActivityAPI]) -> None:\n for activity in activities:\n # Activity.end and Activity.start are in nanoseconds.\n duration = (activity.end - activity.start) / 1e9\n self.profiler_output.append((demangle_kernel_name(activity.name), duration))\n\n def __init__(self):\n if CuptiProfiler.__subscriber_handle is not None:\n raise RuntimeError(\n \"Only one instance of CuptiProfiler can be created. \"\n \"CUPTI only supports one subscriber at a time.\"\n )\n\n self.profiler_output: list[tuple[str, float]] = []\n\n # Subscribe to CUPTI and register activity callbacks.\n CuptiProfiler.__subscriber_handle = cupti_call_safe(cupti.subscribe, None, None)\n cupti_call_safe(\n cupti.activity_register_callbacks,\n self._func_buffer_requested,\n self._func_buffer_completed,\n )\n self.is_valid = True\n\n def start(self) -> None:\n self._error_if_not_valid()\n cupti_call_safe(cupti.activity_flush_all, 1)\n self.profiler_output = []\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_enable, activity_kind)\n\n def stop(self) -> list[tuple[str, float]]:\n self._error_if_not_valid()\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_disable, activity_kind)\n cupti_call_safe(cupti.activity_flush_all, 0)\n return self.profiler_output\n\n def teardown_cupti(self) -> None:\n self._error_if_not_valid()\n if CuptiProfiler.__subscriber_handle is None:\n return\n cupti_call_safe(cupti.unsubscribe, CuptiProfiler.__subscriber_handle)\n cupti_call_safe(cupti.finalize)\n CuptiProfiler.__subscriber_handle = None\n # Invalidate the profiler so it cannot be used again.\n self.is_valid = False\n\n\nclass CuptiTimer(Timer):\n def __init__(self):\n super().__init__()\n self.cupti_profiler = CuptiProfiler()\n self.is_running = False\n\n def __call__(self):\n torch.cuda.synchronize()\n\n if not self.is_running:\n self.cupti_profiler.start()\n self.is_running = True\n return self.current_time\n\n profiler_output = self.cupti_profiler.stop()\n self.is_running = False\n\n # Check if any activities were recorded\n if len(profiler_output) == 0:\n self.cleanup()\n raise RuntimeError(\"No activities were recorded.\")\n\n self._increment_global_time(sum(duration for _, duration in profiler_output))\n return self.current_time\n\n def cleanup(self):\n self.is_running = False\n self.cupti_profiler.teardown_cupti()\n\n\nclass FusionProfileTimer(Timer):\n def __init__(self):\n super().__init__()\n self.fd = None\n # Specifies if the timer in host measurement is called at the start/finish of execution.\n # Timings are measured at the end of execution.\n self.execution_start = True\n\n def set_fd(self, fd):\n self.fd = fd\n\n def __call__(self):\n if not self.execution_start:\n profile = get_fusion_profile()\n elapsed_host_time = profile.host_time_ms / 1e3\n self._increment_global_time(elapsed_host_time)\n self.execution_start = not self.execution_start\n return self.current_time","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.Timer","uri":"program://Fuser/class/python.nvfuser_direct.benchmark_utils.Timer#L13-L24","kind":"class","name":"Timer","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":13,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\nfrom cupti import cupti\nimport cxxfilt\nimport pytest\nfrom ._C_DIRECT import get_fusion_profile\n\n\n# Base class for all timers used by pytest-benchmark.\nclass Timer:\n def __init__(self):\n self.current_time = 0.0\n\n def _increment_global_time(self, elapsed_time: float) -> None:\n self.current_time += elapsed_time\n\n def __call__(self):\n raise NotImplementedError(\"Subclass must implement this method\")\n\n def cleanup(self):\n pass\n\n\ndef demangle_kernel_name(mangled_name):\n try:\n return cxxfilt.demangle(mangled_name)\n except Exception:\n return mangled_name # Return original if demangling fails\n\n\ndef cupti_call_safe(func, *args):\n \"\"\"Wrapper for CUPTI calls. Failing CUPTI calls will exit the program.\"\"\"\n try:\n return func(*args)\n except Exception as e:\n print(f\"CUPTI call {func.__name__} failed: {e}\")\n pytest.exit(1)\n\n\nclass CuptiProfiler:\n # List of activities to be recorded by CUPTI.","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.demangle_kernel_name","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils.demangle_kernel_name#L27-L31","kind":"function","name":"demangle_kernel_name","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":27,"end_line":31,"context_start_line":7,"context_end_line":51,"code":"import cxxfilt\nimport pytest\nfrom ._C_DIRECT import get_fusion_profile\n\n\n# Base class for all timers used by pytest-benchmark.\nclass Timer:\n def __init__(self):\n self.current_time = 0.0\n\n def _increment_global_time(self, elapsed_time: float) -> None:\n self.current_time += elapsed_time\n\n def __call__(self):\n raise NotImplementedError(\"Subclass must implement this method\")\n\n def cleanup(self):\n pass\n\n\ndef demangle_kernel_name(mangled_name):\n try:\n return cxxfilt.demangle(mangled_name)\n except Exception:\n return mangled_name # Return original if demangling fails\n\n\ndef cupti_call_safe(func, *args):\n \"\"\"Wrapper for CUPTI calls. Failing CUPTI calls will exit the program.\"\"\"\n try:\n return func(*args)\n except Exception as e:\n print(f\"CUPTI call {func.__name__} failed: {e}\")\n pytest.exit(1)\n\n\nclass CuptiProfiler:\n # List of activities to be recorded by CUPTI.\n activity_kinds: list[cupti.ActivityKind] = [\n cupti.ActivityKind.CONCURRENT_KERNEL,\n ]\n\n # Private class variable to store the subscriber handle.\n __subscriber_handle = None\n","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.cupti_call_safe","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils.cupti_call_safe#L34-L40","kind":"function","name":"cupti_call_safe","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":34,"end_line":40,"context_start_line":14,"context_end_line":60,"code":" def __init__(self):\n self.current_time = 0.0\n\n def _increment_global_time(self, elapsed_time: float) -> None:\n self.current_time += elapsed_time\n\n def __call__(self):\n raise NotImplementedError(\"Subclass must implement this method\")\n\n def cleanup(self):\n pass\n\n\ndef demangle_kernel_name(mangled_name):\n try:\n return cxxfilt.demangle(mangled_name)\n except Exception:\n return mangled_name # Return original if demangling fails\n\n\ndef cupti_call_safe(func, *args):\n \"\"\"Wrapper for CUPTI calls. Failing CUPTI calls will exit the program.\"\"\"\n try:\n return func(*args)\n except Exception as e:\n print(f\"CUPTI call {func.__name__} failed: {e}\")\n pytest.exit(1)\n\n\nclass CuptiProfiler:\n # List of activities to be recorded by CUPTI.\n activity_kinds: list[cupti.ActivityKind] = [\n cupti.ActivityKind.CONCURRENT_KERNEL,\n ]\n\n # Private class variable to store the subscriber handle.\n __subscriber_handle = None\n\n def _error_if_not_valid(self) -> None:\n if not self.is_valid:\n raise RuntimeError(\n \"CuptiProfiler is not valid. \" \"This instance has been torn down.\"\n )\n\n def _func_buffer_requested(self) -> tuple[int, int]:\n # 8MB buffer size as recommended by CUPTI samples.\n # max_num_records=0 indicates the buffer is filled with as many records as possible.","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.CuptiProfiler","uri":"program://Fuser/class/python.nvfuser_direct.benchmark_utils.CuptiProfiler#L43-L111","kind":"class","name":"CuptiProfiler","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":43,"end_line":111,"context_start_line":23,"context_end_line":131,"code":" def cleanup(self):\n pass\n\n\ndef demangle_kernel_name(mangled_name):\n try:\n return cxxfilt.demangle(mangled_name)\n except Exception:\n return mangled_name # Return original if demangling fails\n\n\ndef cupti_call_safe(func, *args):\n \"\"\"Wrapper for CUPTI calls. Failing CUPTI calls will exit the program.\"\"\"\n try:\n return func(*args)\n except Exception as e:\n print(f\"CUPTI call {func.__name__} failed: {e}\")\n pytest.exit(1)\n\n\nclass CuptiProfiler:\n # List of activities to be recorded by CUPTI.\n activity_kinds: list[cupti.ActivityKind] = [\n cupti.ActivityKind.CONCURRENT_KERNEL,\n ]\n\n # Private class variable to store the subscriber handle.\n __subscriber_handle = None\n\n def _error_if_not_valid(self) -> None:\n if not self.is_valid:\n raise RuntimeError(\n \"CuptiProfiler is not valid. \" \"This instance has been torn down.\"\n )\n\n def _func_buffer_requested(self) -> tuple[int, int]:\n # 8MB buffer size as recommended by CUPTI samples.\n # max_num_records=0 indicates the buffer is filled with as many records as possible.\n buffer_size = 8 * 1024 * 1024\n max_num_records = 0\n return buffer_size, max_num_records\n\n def _func_buffer_completed(self, activities: list[cupti.ActivityAPI]) -> None:\n for activity in activities:\n # Activity.end and Activity.start are in nanoseconds.\n duration = (activity.end - activity.start) / 1e9\n self.profiler_output.append((demangle_kernel_name(activity.name), duration))\n\n def __init__(self):\n if CuptiProfiler.__subscriber_handle is not None:\n raise RuntimeError(\n \"Only one instance of CuptiProfiler can be created. \"\n \"CUPTI only supports one subscriber at a time.\"\n )\n\n self.profiler_output: list[tuple[str, float]] = []\n\n # Subscribe to CUPTI and register activity callbacks.\n CuptiProfiler.__subscriber_handle = cupti_call_safe(cupti.subscribe, None, None)\n cupti_call_safe(\n cupti.activity_register_callbacks,\n self._func_buffer_requested,\n self._func_buffer_completed,\n )\n self.is_valid = True\n\n def start(self) -> None:\n self._error_if_not_valid()\n cupti_call_safe(cupti.activity_flush_all, 1)\n self.profiler_output = []\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_enable, activity_kind)\n\n def stop(self) -> list[tuple[str, float]]:\n self._error_if_not_valid()\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_disable, activity_kind)\n cupti_call_safe(cupti.activity_flush_all, 0)\n return self.profiler_output\n\n def teardown_cupti(self) -> None:\n self._error_if_not_valid()\n if CuptiProfiler.__subscriber_handle is None:\n return\n cupti_call_safe(cupti.unsubscribe, CuptiProfiler.__subscriber_handle)\n cupti_call_safe(cupti.finalize)\n CuptiProfiler.__subscriber_handle = None\n # Invalidate the profiler so it cannot be used again.\n self.is_valid = False\n\n\nclass CuptiTimer(Timer):\n def __init__(self):\n super().__init__()\n self.cupti_profiler = CuptiProfiler()\n self.is_running = False\n\n def __call__(self):\n torch.cuda.synchronize()\n\n if not self.is_running:\n self.cupti_profiler.start()\n self.is_running = True\n return self.current_time\n\n profiler_output = self.cupti_profiler.stop()\n self.is_running = False\n\n # Check if any activities were recorded","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.CuptiTimer","uri":"program://Fuser/class/python.nvfuser_direct.benchmark_utils.CuptiTimer#L114-L141","kind":"class","name":"CuptiTimer","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":114,"end_line":141,"context_start_line":94,"context_end_line":161,"code":" cupti_call_safe(cupti.activity_enable, activity_kind)\n\n def stop(self) -> list[tuple[str, float]]:\n self._error_if_not_valid()\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_disable, activity_kind)\n cupti_call_safe(cupti.activity_flush_all, 0)\n return self.profiler_output\n\n def teardown_cupti(self) -> None:\n self._error_if_not_valid()\n if CuptiProfiler.__subscriber_handle is None:\n return\n cupti_call_safe(cupti.unsubscribe, CuptiProfiler.__subscriber_handle)\n cupti_call_safe(cupti.finalize)\n CuptiProfiler.__subscriber_handle = None\n # Invalidate the profiler so it cannot be used again.\n self.is_valid = False\n\n\nclass CuptiTimer(Timer):\n def __init__(self):\n super().__init__()\n self.cupti_profiler = CuptiProfiler()\n self.is_running = False\n\n def __call__(self):\n torch.cuda.synchronize()\n\n if not self.is_running:\n self.cupti_profiler.start()\n self.is_running = True\n return self.current_time\n\n profiler_output = self.cupti_profiler.stop()\n self.is_running = False\n\n # Check if any activities were recorded\n if len(profiler_output) == 0:\n self.cleanup()\n raise RuntimeError(\"No activities were recorded.\")\n\n self._increment_global_time(sum(duration for _, duration in profiler_output))\n return self.current_time\n\n def cleanup(self):\n self.is_running = False\n self.cupti_profiler.teardown_cupti()\n\n\nclass FusionProfileTimer(Timer):\n def __init__(self):\n super().__init__()\n self.fd = None\n # Specifies if the timer in host measurement is called at the start/finish of execution.\n # Timings are measured at the end of execution.\n self.execution_start = True\n\n def set_fd(self, fd):\n self.fd = fd\n\n def __call__(self):\n if not self.execution_start:\n profile = get_fusion_profile()\n elapsed_host_time = profile.host_time_ms / 1e3\n self._increment_global_time(elapsed_host_time)\n self.execution_start = not self.execution_start\n return self.current_time","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.FusionProfileTimer","uri":"program://Fuser/class/python.nvfuser_direct.benchmark_utils.FusionProfileTimer#L144-L161","kind":"class","name":"FusionProfileTimer","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":144,"end_line":161,"context_start_line":124,"context_end_line":161,"code":" self.cupti_profiler.start()\n self.is_running = True\n return self.current_time\n\n profiler_output = self.cupti_profiler.stop()\n self.is_running = False\n\n # Check if any activities were recorded\n if len(profiler_output) == 0:\n self.cleanup()\n raise RuntimeError(\"No activities were recorded.\")\n\n self._increment_global_time(sum(duration for _, duration in profiler_output))\n return self.current_time\n\n def cleanup(self):\n self.is_running = False\n self.cupti_profiler.teardown_cupti()\n\n\nclass FusionProfileTimer(Timer):\n def __init__(self):\n super().__init__()\n self.fd = None\n # Specifies if the timer in host measurement is called at the start/finish of execution.\n # Timings are measured at the end of execution.\n self.execution_start = True\n\n def set_fd(self, fd):\n self.fd = fd\n\n def __call__(self):\n if not self.execution_start:\n profile = get_fusion_profile()\n elapsed_host_time = profile.host_time_ms / 1e3\n self._increment_global_time(elapsed_host_time)\n self.execution_start = not self.execution_start\n return self.current_time","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.__init__","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils.__init__#L145-L150","kind":"function","name":"__init__","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":145,"end_line":150,"context_start_line":125,"context_end_line":161,"code":" self.is_running = True\n return self.current_time\n\n profiler_output = self.cupti_profiler.stop()\n self.is_running = False\n\n # Check if any activities were recorded\n if len(profiler_output) == 0:\n self.cleanup()\n raise RuntimeError(\"No activities were recorded.\")\n\n self._increment_global_time(sum(duration for _, duration in profiler_output))\n return self.current_time\n\n def cleanup(self):\n self.is_running = False\n self.cupti_profiler.teardown_cupti()\n\n\nclass FusionProfileTimer(Timer):\n def __init__(self):\n super().__init__()\n self.fd = None\n # Specifies if the timer in host measurement is called at the start/finish of execution.\n # Timings are measured at the end of execution.\n self.execution_start = True\n\n def set_fd(self, fd):\n self.fd = fd\n\n def __call__(self):\n if not self.execution_start:\n profile = get_fusion_profile()\n elapsed_host_time = profile.host_time_ms / 1e3\n self._increment_global_time(elapsed_host_time)\n self.execution_start = not self.execution_start\n return self.current_time","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils._increment_global_time","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils._increment_global_time#L17-L18","kind":"function","name":"_increment_global_time","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":17,"end_line":18,"context_start_line":1,"context_end_line":38,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\nfrom cupti import cupti\nimport cxxfilt\nimport pytest\nfrom ._C_DIRECT import get_fusion_profile\n\n\n# Base class for all timers used by pytest-benchmark.\nclass Timer:\n def __init__(self):\n self.current_time = 0.0\n\n def _increment_global_time(self, elapsed_time: float) -> None:\n self.current_time += elapsed_time\n\n def __call__(self):\n raise NotImplementedError(\"Subclass must implement this method\")\n\n def cleanup(self):\n pass\n\n\ndef demangle_kernel_name(mangled_name):\n try:\n return cxxfilt.demangle(mangled_name)\n except Exception:\n return mangled_name # Return original if demangling fails\n\n\ndef cupti_call_safe(func, *args):\n \"\"\"Wrapper for CUPTI calls. Failing CUPTI calls will exit the program.\"\"\"\n try:\n return func(*args)\n except Exception as e:","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.__call__","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils.__call__#L155-L161","kind":"function","name":"__call__","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":155,"end_line":161,"context_start_line":135,"context_end_line":161,"code":"\n self._increment_global_time(sum(duration for _, duration in profiler_output))\n return self.current_time\n\n def cleanup(self):\n self.is_running = False\n self.cupti_profiler.teardown_cupti()\n\n\nclass FusionProfileTimer(Timer):\n def __init__(self):\n super().__init__()\n self.fd = None\n # Specifies if the timer in host measurement is called at the start/finish of execution.\n # Timings are measured at the end of execution.\n self.execution_start = True\n\n def set_fd(self, fd):\n self.fd = fd\n\n def __call__(self):\n if not self.execution_start:\n profile = get_fusion_profile()\n elapsed_host_time = profile.host_time_ms / 1e3\n self._increment_global_time(elapsed_host_time)\n self.execution_start = not self.execution_start\n return self.current_time","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.cleanup","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils.cleanup#L139-L141","kind":"function","name":"cleanup","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":139,"end_line":141,"context_start_line":119,"context_end_line":161,"code":"\n def __call__(self):\n torch.cuda.synchronize()\n\n if not self.is_running:\n self.cupti_profiler.start()\n self.is_running = True\n return self.current_time\n\n profiler_output = self.cupti_profiler.stop()\n self.is_running = False\n\n # Check if any activities were recorded\n if len(profiler_output) == 0:\n self.cleanup()\n raise RuntimeError(\"No activities were recorded.\")\n\n self._increment_global_time(sum(duration for _, duration in profiler_output))\n return self.current_time\n\n def cleanup(self):\n self.is_running = False\n self.cupti_profiler.teardown_cupti()\n\n\nclass FusionProfileTimer(Timer):\n def __init__(self):\n super().__init__()\n self.fd = None\n # Specifies if the timer in host measurement is called at the start/finish of execution.\n # Timings are measured at the end of execution.\n self.execution_start = True\n\n def set_fd(self, fd):\n self.fd = fd\n\n def __call__(self):\n if not self.execution_start:\n profile = get_fusion_profile()\n elapsed_host_time = profile.host_time_ms / 1e3\n self._increment_global_time(elapsed_host_time)\n self.execution_start = not self.execution_start\n return self.current_time","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils._error_if_not_valid","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils._error_if_not_valid#L52-L56","kind":"function","name":"_error_if_not_valid","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":52,"end_line":56,"context_start_line":32,"context_end_line":76,"code":"\n\ndef cupti_call_safe(func, *args):\n \"\"\"Wrapper for CUPTI calls. Failing CUPTI calls will exit the program.\"\"\"\n try:\n return func(*args)\n except Exception as e:\n print(f\"CUPTI call {func.__name__} failed: {e}\")\n pytest.exit(1)\n\n\nclass CuptiProfiler:\n # List of activities to be recorded by CUPTI.\n activity_kinds: list[cupti.ActivityKind] = [\n cupti.ActivityKind.CONCURRENT_KERNEL,\n ]\n\n # Private class variable to store the subscriber handle.\n __subscriber_handle = None\n\n def _error_if_not_valid(self) -> None:\n if not self.is_valid:\n raise RuntimeError(\n \"CuptiProfiler is not valid. \" \"This instance has been torn down.\"\n )\n\n def _func_buffer_requested(self) -> tuple[int, int]:\n # 8MB buffer size as recommended by CUPTI samples.\n # max_num_records=0 indicates the buffer is filled with as many records as possible.\n buffer_size = 8 * 1024 * 1024\n max_num_records = 0\n return buffer_size, max_num_records\n\n def _func_buffer_completed(self, activities: list[cupti.ActivityAPI]) -> None:\n for activity in activities:\n # Activity.end and Activity.start are in nanoseconds.\n duration = (activity.end - activity.start) / 1e9\n self.profiler_output.append((demangle_kernel_name(activity.name), duration))\n\n def __init__(self):\n if CuptiProfiler.__subscriber_handle is not None:\n raise RuntimeError(\n \"Only one instance of CuptiProfiler can be created. \"\n \"CUPTI only supports one subscriber at a time.\"\n )","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils._func_buffer_requested","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils._func_buffer_requested#L58-L63","kind":"function","name":"_func_buffer_requested","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":58,"end_line":63,"context_start_line":38,"context_end_line":83,"code":" except Exception as e:\n print(f\"CUPTI call {func.__name__} failed: {e}\")\n pytest.exit(1)\n\n\nclass CuptiProfiler:\n # List of activities to be recorded by CUPTI.\n activity_kinds: list[cupti.ActivityKind] = [\n cupti.ActivityKind.CONCURRENT_KERNEL,\n ]\n\n # Private class variable to store the subscriber handle.\n __subscriber_handle = None\n\n def _error_if_not_valid(self) -> None:\n if not self.is_valid:\n raise RuntimeError(\n \"CuptiProfiler is not valid. \" \"This instance has been torn down.\"\n )\n\n def _func_buffer_requested(self) -> tuple[int, int]:\n # 8MB buffer size as recommended by CUPTI samples.\n # max_num_records=0 indicates the buffer is filled with as many records as possible.\n buffer_size = 8 * 1024 * 1024\n max_num_records = 0\n return buffer_size, max_num_records\n\n def _func_buffer_completed(self, activities: list[cupti.ActivityAPI]) -> None:\n for activity in activities:\n # Activity.end and Activity.start are in nanoseconds.\n duration = (activity.end - activity.start) / 1e9\n self.profiler_output.append((demangle_kernel_name(activity.name), duration))\n\n def __init__(self):\n if CuptiProfiler.__subscriber_handle is not None:\n raise RuntimeError(\n \"Only one instance of CuptiProfiler can be created. \"\n \"CUPTI only supports one subscriber at a time.\"\n )\n\n self.profiler_output: list[tuple[str, float]] = []\n\n # Subscribe to CUPTI and register activity callbacks.\n CuptiProfiler.__subscriber_handle = cupti_call_safe(cupti.subscribe, None, None)\n cupti_call_safe(\n cupti.activity_register_callbacks,","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils._func_buffer_completed","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils._func_buffer_completed#L65-L69","kind":"function","name":"_func_buffer_completed","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":65,"end_line":69,"context_start_line":45,"context_end_line":89,"code":" activity_kinds: list[cupti.ActivityKind] = [\n cupti.ActivityKind.CONCURRENT_KERNEL,\n ]\n\n # Private class variable to store the subscriber handle.\n __subscriber_handle = None\n\n def _error_if_not_valid(self) -> None:\n if not self.is_valid:\n raise RuntimeError(\n \"CuptiProfiler is not valid. \" \"This instance has been torn down.\"\n )\n\n def _func_buffer_requested(self) -> tuple[int, int]:\n # 8MB buffer size as recommended by CUPTI samples.\n # max_num_records=0 indicates the buffer is filled with as many records as possible.\n buffer_size = 8 * 1024 * 1024\n max_num_records = 0\n return buffer_size, max_num_records\n\n def _func_buffer_completed(self, activities: list[cupti.ActivityAPI]) -> None:\n for activity in activities:\n # Activity.end and Activity.start are in nanoseconds.\n duration = (activity.end - activity.start) / 1e9\n self.profiler_output.append((demangle_kernel_name(activity.name), duration))\n\n def __init__(self):\n if CuptiProfiler.__subscriber_handle is not None:\n raise RuntimeError(\n \"Only one instance of CuptiProfiler can be created. \"\n \"CUPTI only supports one subscriber at a time.\"\n )\n\n self.profiler_output: list[tuple[str, float]] = []\n\n # Subscribe to CUPTI and register activity callbacks.\n CuptiProfiler.__subscriber_handle = cupti_call_safe(cupti.subscribe, None, None)\n cupti_call_safe(\n cupti.activity_register_callbacks,\n self._func_buffer_requested,\n self._func_buffer_completed,\n )\n self.is_valid = True\n\n def start(self) -> None:","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.start","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils.start#L89-L94","kind":"function","name":"start","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":89,"end_line":94,"context_start_line":69,"context_end_line":114,"code":" self.profiler_output.append((demangle_kernel_name(activity.name), duration))\n\n def __init__(self):\n if CuptiProfiler.__subscriber_handle is not None:\n raise RuntimeError(\n \"Only one instance of CuptiProfiler can be created. \"\n \"CUPTI only supports one subscriber at a time.\"\n )\n\n self.profiler_output: list[tuple[str, float]] = []\n\n # Subscribe to CUPTI and register activity callbacks.\n CuptiProfiler.__subscriber_handle = cupti_call_safe(cupti.subscribe, None, None)\n cupti_call_safe(\n cupti.activity_register_callbacks,\n self._func_buffer_requested,\n self._func_buffer_completed,\n )\n self.is_valid = True\n\n def start(self) -> None:\n self._error_if_not_valid()\n cupti_call_safe(cupti.activity_flush_all, 1)\n self.profiler_output = []\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_enable, activity_kind)\n\n def stop(self) -> list[tuple[str, float]]:\n self._error_if_not_valid()\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_disable, activity_kind)\n cupti_call_safe(cupti.activity_flush_all, 0)\n return self.profiler_output\n\n def teardown_cupti(self) -> None:\n self._error_if_not_valid()\n if CuptiProfiler.__subscriber_handle is None:\n return\n cupti_call_safe(cupti.unsubscribe, CuptiProfiler.__subscriber_handle)\n cupti_call_safe(cupti.finalize)\n CuptiProfiler.__subscriber_handle = None\n # Invalidate the profiler so it cannot be used again.\n self.is_valid = False\n\n\nclass CuptiTimer(Timer):","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.stop","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils.stop#L96-L101","kind":"function","name":"stop","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":96,"end_line":101,"context_start_line":76,"context_end_line":121,"code":" )\n\n self.profiler_output: list[tuple[str, float]] = []\n\n # Subscribe to CUPTI and register activity callbacks.\n CuptiProfiler.__subscriber_handle = cupti_call_safe(cupti.subscribe, None, None)\n cupti_call_safe(\n cupti.activity_register_callbacks,\n self._func_buffer_requested,\n self._func_buffer_completed,\n )\n self.is_valid = True\n\n def start(self) -> None:\n self._error_if_not_valid()\n cupti_call_safe(cupti.activity_flush_all, 1)\n self.profiler_output = []\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_enable, activity_kind)\n\n def stop(self) -> list[tuple[str, float]]:\n self._error_if_not_valid()\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_disable, activity_kind)\n cupti_call_safe(cupti.activity_flush_all, 0)\n return self.profiler_output\n\n def teardown_cupti(self) -> None:\n self._error_if_not_valid()\n if CuptiProfiler.__subscriber_handle is None:\n return\n cupti_call_safe(cupti.unsubscribe, CuptiProfiler.__subscriber_handle)\n cupti_call_safe(cupti.finalize)\n CuptiProfiler.__subscriber_handle = None\n # Invalidate the profiler so it cannot be used again.\n self.is_valid = False\n\n\nclass CuptiTimer(Timer):\n def __init__(self):\n super().__init__()\n self.cupti_profiler = CuptiProfiler()\n self.is_running = False\n\n def __call__(self):\n torch.cuda.synchronize()","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.teardown_cupti","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils.teardown_cupti#L103-L111","kind":"function","name":"teardown_cupti","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":103,"end_line":111,"context_start_line":83,"context_end_line":131,"code":" cupti.activity_register_callbacks,\n self._func_buffer_requested,\n self._func_buffer_completed,\n )\n self.is_valid = True\n\n def start(self) -> None:\n self._error_if_not_valid()\n cupti_call_safe(cupti.activity_flush_all, 1)\n self.profiler_output = []\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_enable, activity_kind)\n\n def stop(self) -> list[tuple[str, float]]:\n self._error_if_not_valid()\n for activity_kind in CuptiProfiler.activity_kinds:\n cupti_call_safe(cupti.activity_disable, activity_kind)\n cupti_call_safe(cupti.activity_flush_all, 0)\n return self.profiler_output\n\n def teardown_cupti(self) -> None:\n self._error_if_not_valid()\n if CuptiProfiler.__subscriber_handle is None:\n return\n cupti_call_safe(cupti.unsubscribe, CuptiProfiler.__subscriber_handle)\n cupti_call_safe(cupti.finalize)\n CuptiProfiler.__subscriber_handle = None\n # Invalidate the profiler so it cannot be used again.\n self.is_valid = False\n\n\nclass CuptiTimer(Timer):\n def __init__(self):\n super().__init__()\n self.cupti_profiler = CuptiProfiler()\n self.is_running = False\n\n def __call__(self):\n torch.cuda.synchronize()\n\n if not self.is_running:\n self.cupti_profiler.start()\n self.is_running = True\n return self.current_time\n\n profiler_output = self.cupti_profiler.stop()\n self.is_running = False\n\n # Check if any activities were recorded","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_direct.benchmark_utils.set_fd","uri":"program://Fuser/function/python.nvfuser_direct.benchmark_utils.set_fd#L152-L153","kind":"function","name":"set_fd","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":152,"end_line":153,"context_start_line":132,"context_end_line":161,"code":" if len(profiler_output) == 0:\n self.cleanup()\n raise RuntimeError(\"No activities were recorded.\")\n\n self._increment_global_time(sum(duration for _, duration in profiler_output))\n return self.current_time\n\n def cleanup(self):\n self.is_running = False\n self.cupti_profiler.teardown_cupti()\n\n\nclass FusionProfileTimer(Timer):\n def __init__(self):\n super().__init__()\n self.fd = None\n # Specifies if the timer in host measurement is called at the start/finish of execution.\n # Timings are measured at the end of execution.\n self.execution_start = True\n\n def set_fd(self, fd):\n self.fd = fd\n\n def __call__(self):\n if not self.execution_start:\n profile = get_fusion_profile()\n elapsed_host_time = profile.host_time_ms / 1e3\n self._increment_global_time(elapsed_host_time)\n self.execution_start = not self.execution_start\n return self.current_time","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.memory","uri":"program://Fuser/module/python.tools.memory#L1-L28","kind":"module","name":"python.tools.memory","path":"python/tools/memory.py","language":"python","start_line":1,"end_line":28,"context_start_line":1,"context_end_line":28,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\ndef get_available_memory_gb():\n \"\"\"Returns the available memory in GB.\"\"\"\n try:\n import psutil\n\n return psutil.virtual_memory().available / 1024 / 1024 / 1024\n except: # noqa: E722\n pass\n\n try:\n with open(\"/proc/meminfo\", \"r\") as f:\n while True:\n line = f.readline()\n if line.startswith(\"MemAvailable:\"):\n mem = line.split()[1]\n assert line.split()[2] == \"kB\"\n return int(mem) / 1024 / 1024\n if not line:\n break\n except: # noqa: E722\n pass\n\n return 0","source_hash":"29abf2a174c9e2b85c35c42603262a8157251a100571e5525577f4fff6e00105","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.memory.get_available_memory_gb","uri":"program://Fuser/function/python.tools.memory.get_available_memory_gb#L6-L28","kind":"function","name":"get_available_memory_gb","path":"python/tools/memory.py","language":"python","start_line":6,"end_line":28,"context_start_line":1,"context_end_line":28,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\ndef get_available_memory_gb():\n \"\"\"Returns the available memory in GB.\"\"\"\n try:\n import psutil\n\n return psutil.virtual_memory().available / 1024 / 1024 / 1024\n except: # noqa: E722\n pass\n\n try:\n with open(\"/proc/meminfo\", \"r\") as f:\n while True:\n line = f.readline()\n if line.startswith(\"MemAvailable:\"):\n mem = line.split()[1]\n assert line.split()[2] == \"kB\"\n return int(mem) / 1024 / 1024\n if not line:\n break\n except: # noqa: E722\n pass\n\n return 0","source_hash":"29abf2a174c9e2b85c35c42603262a8157251a100571e5525577f4fff6e00105","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies","uri":"program://Fuser/module/python.tools.check_dependencies#L1-L183","kind":"module","name":"python.tools.check_dependencies","path":"python/tools/check_dependencies.py","language":"python","start_line":1,"end_line":183,"context_start_line":1,"context_end_line":183,"code":"#!/usr/bin/env python3\n# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nnvFuser Dependency Report Generator\n\nReads dependency data from JSON (generated by CMake) and prints\na comprehensive, user-friendly report with colored output and\nactionable installation instructions for missing dependencies.\n\nIMPORTANT: CMake is the source of truth for all dependency requirements.\nThis script only formats output and provides help text.\n\"\"\"\n\nimport json\nimport sys\nfrom pathlib import Path\nfrom typing import Dict\n\nfrom prereqs import detect_platform, format_platform_info\nfrom prereqs.colors import colorize, Colors\nfrom prereqs.requirements import (\n PythonRequirement,\n TorchRequirement,\n LLVMRequirement,\n CUDAToolkitRequirement,\n Pybind11Requirement,\n CompilerRequirement,\n NinjaRequirement,\n NVMMHRequirement,\n GitSubmodulesRequirement,\n)\n\n\nclass DependencyReporter:\n \"\"\"\n Generates formatted dependency reports from JSON data with help text.\n\n CMake provides all dependency data via JSON. This class formats the output\n and generates platform-specific installation instructions for failures.\n \"\"\"\n\n def __init__(self, deps_path: Path):\n # Load CMake variables\n cmake_vars = self._load_cmake_vars(deps_path)\n\n self.colors = Colors()\n self.platform_info = detect_platform()\n\n # Create requirement objects - each class defines its own name and variable names\n self.requirements = []\n self.requirements.append(NinjaRequirement(cmake_vars))\n self.requirements.append(GitSubmodulesRequirement(cmake_vars))\n self.requirements.append(CompilerRequirement(cmake_vars))\n self.requirements.append(PythonRequirement(cmake_vars))\n self.requirements.append(CUDAToolkitRequirement(cmake_vars))\n self.requirements.append(TorchRequirement(cmake_vars))\n self.requirements.append(Pybind11Requirement(cmake_vars))\n self.requirements.append(LLVMRequirement(cmake_vars))\n self.requirements.append(NVMMHRequirement(cmake_vars))\n\n def _load_cmake_vars(self, deps_path: Path) -> Dict:\n \"\"\"Load CMake variables from JSON file\"\"\"\n try:\n with open(deps_path, \"r\") as f:\n data = json.load(f)\n return data.get(\"cmake_vars\", {})\n except FileNotFoundError:\n print(f\"Error: {deps_path} not found\", file=sys.stderr)\n sys.exit(1)\n except Exception as e:\n print(f\"Error loading dependencies: {e}\", file=sys.stderr)\n sys.exit(1)\n\n def generate_report(self):\n \"\"\"Main entry point - prints formatted report\"\"\"\n print() # Blank line before report\n print(\"=\" * 80)\n self._print_header()\n print(\"=\" * 80)\n print() # Blank line after header\n self._print_dependencies()\n print() # Blank line after dependencies\n print(\"* Optional requirement\")\n print(\"=\" * 80)\n\n # Collect failures and issues to show help for\n # Include required failures (is_failure=True) and optional issues (not SUCCESS)\n failures = []\n for req in self.requirements:\n if hasattr(req, \"is_failure\") and req.is_failure():\n # Required dependency that failed\n failures.append(req)\n elif (\n hasattr(req, \"status\")\n and hasattr(req, \"optional\")\n and req.optional\n and req.status != \"SUCCESS\"\n ):\n # Optional dependency with issues (NOT_FOUND or INCOMPATIBLE)\n failures.append(req)\n\n if failures:\n self._print_help_section(failures)\n # Only print failure summary if there are actual (non-optional) failures\n required_failures = [\n req\n for req in self.requirements\n if hasattr(req, \"is_failure\") and req.is_failure()\n ]\n if required_failures:\n self._print_failure_summary()\n\n print() # Blank line at end\n\n def _print_header(self):\n \"\"\"Print report header with platform information\"\"\"\n platform_str = format_platform_info(self.platform_info)\n print(\n colorize(\n self.colors.BOLD_GREEN, \"[nvFuser] Validating build prerequisites...\"\n )\n )\n print(colorize(self.colors.CYAN, \"Platform: \") + platform_str)\n\n def _print_failure_summary(self):\n \"\"\"Print failure summary message\"\"\"\n print()\n print(colorize(self.colors.BOLD_RED, \"Build prerequisite validation FAILED\"))\n print(\"See installation instructions above\")\n\n def _print_dependencies(self):\n \"\"\"Print status for each dependency using OOP requirement classes\"\"\"\n for req in self.requirements:\n if hasattr(req, \"format_status_line\"):\n # OOP: use requirement's format method\n print(req.format_status_line(self.colors))\n else:\n # Fallback: use legacy dict-based formatting (shouldn't happen)\n print(f\"[nvFuser] ? {getattr(req, 'name', 'Unknown')}\")\n\n def _print_help_section(self, failures):\n \"\"\"Print help section header and help for each failed dependency\"\"\"\n print()\n print(\"=\" * 70)\n print(\"Installation Instructions\")\n print(\"=\" * 70)\n print()\n\n for req in failures:\n self._print_help_for_requirement(req)\n\n def _print_help_for_requirement(self, req):\n \"\"\"Call requirement's help generation method\"\"\"\n if hasattr(req, \"generate_help\"):\n req.generate_help(self.platform_info)\n else:\n # Fallback for requirements without help\n print(f\"{req.name} installation help not available\")\n print()\n\n\ndef main():\n if len(sys.argv) != 2:\n print(\"Usage: check_dependencies.py \", file=sys.stderr)\n sys.exit(1)\n\n json_path = Path(sys.argv[1])\n if not json_path.exists():\n print(f\"Error: {json_path} not found\", file=sys.stderr)\n sys.exit(1)\n\n # Generate report\n reporter = DependencyReporter(json_path)\n reporter.generate_report()\n\n # Report generated successfully\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies.DependencyReporter","uri":"program://Fuser/class/python.tools.check_dependencies.DependencyReporter#L36-L161","kind":"class","name":"DependencyReporter","path":"python/tools/check_dependencies.py","language":"python","start_line":36,"end_line":161,"context_start_line":16,"context_end_line":181,"code":"import json\nimport sys\nfrom pathlib import Path\nfrom typing import Dict\n\nfrom prereqs import detect_platform, format_platform_info\nfrom prereqs.colors import colorize, Colors\nfrom prereqs.requirements import (\n PythonRequirement,\n TorchRequirement,\n LLVMRequirement,\n CUDAToolkitRequirement,\n Pybind11Requirement,\n CompilerRequirement,\n NinjaRequirement,\n NVMMHRequirement,\n GitSubmodulesRequirement,\n)\n\n\nclass DependencyReporter:\n \"\"\"\n Generates formatted dependency reports from JSON data with help text.\n\n CMake provides all dependency data via JSON. This class formats the output\n and generates platform-specific installation instructions for failures.\n \"\"\"\n\n def __init__(self, deps_path: Path):\n # Load CMake variables\n cmake_vars = self._load_cmake_vars(deps_path)\n\n self.colors = Colors()\n self.platform_info = detect_platform()\n\n # Create requirement objects - each class defines its own name and variable names\n self.requirements = []\n self.requirements.append(NinjaRequirement(cmake_vars))\n self.requirements.append(GitSubmodulesRequirement(cmake_vars))\n self.requirements.append(CompilerRequirement(cmake_vars))\n self.requirements.append(PythonRequirement(cmake_vars))\n self.requirements.append(CUDAToolkitRequirement(cmake_vars))\n self.requirements.append(TorchRequirement(cmake_vars))\n self.requirements.append(Pybind11Requirement(cmake_vars))\n self.requirements.append(LLVMRequirement(cmake_vars))\n self.requirements.append(NVMMHRequirement(cmake_vars))\n\n def _load_cmake_vars(self, deps_path: Path) -> Dict:\n \"\"\"Load CMake variables from JSON file\"\"\"\n try:\n with open(deps_path, \"r\") as f:\n data = json.load(f)\n return data.get(\"cmake_vars\", {})\n except FileNotFoundError:\n print(f\"Error: {deps_path} not found\", file=sys.stderr)\n sys.exit(1)\n except Exception as e:\n print(f\"Error loading dependencies: {e}\", file=sys.stderr)\n sys.exit(1)\n\n def generate_report(self):\n \"\"\"Main entry point - prints formatted report\"\"\"\n print() # Blank line before report\n print(\"=\" * 80)\n self._print_header()\n print(\"=\" * 80)\n print() # Blank line after header\n self._print_dependencies()\n print() # Blank line after dependencies\n print(\"* Optional requirement\")\n print(\"=\" * 80)\n\n # Collect failures and issues to show help for\n # Include required failures (is_failure=True) and optional issues (not SUCCESS)\n failures = []\n for req in self.requirements:\n if hasattr(req, \"is_failure\") and req.is_failure():\n # Required dependency that failed\n failures.append(req)\n elif (\n hasattr(req, \"status\")\n and hasattr(req, \"optional\")\n and req.optional\n and req.status != \"SUCCESS\"\n ):\n # Optional dependency with issues (NOT_FOUND or INCOMPATIBLE)\n failures.append(req)\n\n if failures:\n self._print_help_section(failures)\n # Only print failure summary if there are actual (non-optional) failures\n required_failures = [\n req\n for req in self.requirements\n if hasattr(req, \"is_failure\") and req.is_failure()\n ]\n if required_failures:\n self._print_failure_summary()\n\n print() # Blank line at end\n\n def _print_header(self):\n \"\"\"Print report header with platform information\"\"\"\n platform_str = format_platform_info(self.platform_info)\n print(\n colorize(\n self.colors.BOLD_GREEN, \"[nvFuser] Validating build prerequisites...\"\n )\n )\n print(colorize(self.colors.CYAN, \"Platform: \") + platform_str)\n\n def _print_failure_summary(self):\n \"\"\"Print failure summary message\"\"\"\n print()\n print(colorize(self.colors.BOLD_RED, \"Build prerequisite validation FAILED\"))\n print(\"See installation instructions above\")\n\n def _print_dependencies(self):\n \"\"\"Print status for each dependency using OOP requirement classes\"\"\"\n for req in self.requirements:\n if hasattr(req, \"format_status_line\"):\n # OOP: use requirement's format method\n print(req.format_status_line(self.colors))\n else:\n # Fallback: use legacy dict-based formatting (shouldn't happen)\n print(f\"[nvFuser] ? {getattr(req, 'name', 'Unknown')}\")\n\n def _print_help_section(self, failures):\n \"\"\"Print help section header and help for each failed dependency\"\"\"\n print()\n print(\"=\" * 70)\n print(\"Installation Instructions\")\n print(\"=\" * 70)\n print()\n\n for req in failures:\n self._print_help_for_requirement(req)\n\n def _print_help_for_requirement(self, req):\n \"\"\"Call requirement's help generation method\"\"\"\n if hasattr(req, \"generate_help\"):\n req.generate_help(self.platform_info)\n else:\n # Fallback for requirements without help\n print(f\"{req.name} installation help not available\")\n print()\n\n\ndef main():\n if len(sys.argv) != 2:\n print(\"Usage: check_dependencies.py \", file=sys.stderr)\n sys.exit(1)\n\n json_path = Path(sys.argv[1])\n if not json_path.exists():\n print(f\"Error: {json_path} not found\", file=sys.stderr)\n sys.exit(1)\n\n # Generate report\n reporter = DependencyReporter(json_path)\n reporter.generate_report()\n\n # Report generated successfully\n sys.exit(0)\n\n","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies.main","uri":"program://Fuser/function/python.tools.check_dependencies.main#L164-L179","kind":"function","name":"main","path":"python/tools/check_dependencies.py","language":"python","start_line":164,"end_line":179,"context_start_line":144,"context_end_line":183,"code":" \"\"\"Print help section header and help for each failed dependency\"\"\"\n print()\n print(\"=\" * 70)\n print(\"Installation Instructions\")\n print(\"=\" * 70)\n print()\n\n for req in failures:\n self._print_help_for_requirement(req)\n\n def _print_help_for_requirement(self, req):\n \"\"\"Call requirement's help generation method\"\"\"\n if hasattr(req, \"generate_help\"):\n req.generate_help(self.platform_info)\n else:\n # Fallback for requirements without help\n print(f\"{req.name} installation help not available\")\n print()\n\n\ndef main():\n if len(sys.argv) != 2:\n print(\"Usage: check_dependencies.py \", file=sys.stderr)\n sys.exit(1)\n\n json_path = Path(sys.argv[1])\n if not json_path.exists():\n print(f\"Error: {json_path} not found\", file=sys.stderr)\n sys.exit(1)\n\n # Generate report\n reporter = DependencyReporter(json_path)\n reporter.generate_report()\n\n # Report generated successfully\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main()","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies.__init__","uri":"program://Fuser/function/python.tools.check_dependencies.__init__#L44-L61","kind":"function","name":"__init__","path":"python/tools/check_dependencies.py","language":"python","start_line":44,"end_line":61,"context_start_line":24,"context_end_line":81,"code":" PythonRequirement,\n TorchRequirement,\n LLVMRequirement,\n CUDAToolkitRequirement,\n Pybind11Requirement,\n CompilerRequirement,\n NinjaRequirement,\n NVMMHRequirement,\n GitSubmodulesRequirement,\n)\n\n\nclass DependencyReporter:\n \"\"\"\n Generates formatted dependency reports from JSON data with help text.\n\n CMake provides all dependency data via JSON. This class formats the output\n and generates platform-specific installation instructions for failures.\n \"\"\"\n\n def __init__(self, deps_path: Path):\n # Load CMake variables\n cmake_vars = self._load_cmake_vars(deps_path)\n\n self.colors = Colors()\n self.platform_info = detect_platform()\n\n # Create requirement objects - each class defines its own name and variable names\n self.requirements = []\n self.requirements.append(NinjaRequirement(cmake_vars))\n self.requirements.append(GitSubmodulesRequirement(cmake_vars))\n self.requirements.append(CompilerRequirement(cmake_vars))\n self.requirements.append(PythonRequirement(cmake_vars))\n self.requirements.append(CUDAToolkitRequirement(cmake_vars))\n self.requirements.append(TorchRequirement(cmake_vars))\n self.requirements.append(Pybind11Requirement(cmake_vars))\n self.requirements.append(LLVMRequirement(cmake_vars))\n self.requirements.append(NVMMHRequirement(cmake_vars))\n\n def _load_cmake_vars(self, deps_path: Path) -> Dict:\n \"\"\"Load CMake variables from JSON file\"\"\"\n try:\n with open(deps_path, \"r\") as f:\n data = json.load(f)\n return data.get(\"cmake_vars\", {})\n except FileNotFoundError:\n print(f\"Error: {deps_path} not found\", file=sys.stderr)\n sys.exit(1)\n except Exception as e:\n print(f\"Error loading dependencies: {e}\", file=sys.stderr)\n sys.exit(1)\n\n def generate_report(self):\n \"\"\"Main entry point - prints formatted report\"\"\"\n print() # Blank line before report\n print(\"=\" * 80)\n self._print_header()\n print(\"=\" * 80)","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies._load_cmake_vars","uri":"program://Fuser/function/python.tools.check_dependencies._load_cmake_vars#L63-L74","kind":"function","name":"_load_cmake_vars","path":"python/tools/check_dependencies.py","language":"python","start_line":63,"end_line":74,"context_start_line":43,"context_end_line":94,"code":"\n def __init__(self, deps_path: Path):\n # Load CMake variables\n cmake_vars = self._load_cmake_vars(deps_path)\n\n self.colors = Colors()\n self.platform_info = detect_platform()\n\n # Create requirement objects - each class defines its own name and variable names\n self.requirements = []\n self.requirements.append(NinjaRequirement(cmake_vars))\n self.requirements.append(GitSubmodulesRequirement(cmake_vars))\n self.requirements.append(CompilerRequirement(cmake_vars))\n self.requirements.append(PythonRequirement(cmake_vars))\n self.requirements.append(CUDAToolkitRequirement(cmake_vars))\n self.requirements.append(TorchRequirement(cmake_vars))\n self.requirements.append(Pybind11Requirement(cmake_vars))\n self.requirements.append(LLVMRequirement(cmake_vars))\n self.requirements.append(NVMMHRequirement(cmake_vars))\n\n def _load_cmake_vars(self, deps_path: Path) -> Dict:\n \"\"\"Load CMake variables from JSON file\"\"\"\n try:\n with open(deps_path, \"r\") as f:\n data = json.load(f)\n return data.get(\"cmake_vars\", {})\n except FileNotFoundError:\n print(f\"Error: {deps_path} not found\", file=sys.stderr)\n sys.exit(1)\n except Exception as e:\n print(f\"Error loading dependencies: {e}\", file=sys.stderr)\n sys.exit(1)\n\n def generate_report(self):\n \"\"\"Main entry point - prints formatted report\"\"\"\n print() # Blank line before report\n print(\"=\" * 80)\n self._print_header()\n print(\"=\" * 80)\n print() # Blank line after header\n self._print_dependencies()\n print() # Blank line after dependencies\n print(\"* Optional requirement\")\n print(\"=\" * 80)\n\n # Collect failures and issues to show help for\n # Include required failures (is_failure=True) and optional issues (not SUCCESS)\n failures = []\n for req in self.requirements:\n if hasattr(req, \"is_failure\") and req.is_failure():\n # Required dependency that failed\n failures.append(req)","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies.generate_report","uri":"program://Fuser/function/python.tools.check_dependencies.generate_report#L76-L115","kind":"function","name":"generate_report","path":"python/tools/check_dependencies.py","language":"python","start_line":76,"end_line":115,"context_start_line":56,"context_end_line":135,"code":" self.requirements.append(PythonRequirement(cmake_vars))\n self.requirements.append(CUDAToolkitRequirement(cmake_vars))\n self.requirements.append(TorchRequirement(cmake_vars))\n self.requirements.append(Pybind11Requirement(cmake_vars))\n self.requirements.append(LLVMRequirement(cmake_vars))\n self.requirements.append(NVMMHRequirement(cmake_vars))\n\n def _load_cmake_vars(self, deps_path: Path) -> Dict:\n \"\"\"Load CMake variables from JSON file\"\"\"\n try:\n with open(deps_path, \"r\") as f:\n data = json.load(f)\n return data.get(\"cmake_vars\", {})\n except FileNotFoundError:\n print(f\"Error: {deps_path} not found\", file=sys.stderr)\n sys.exit(1)\n except Exception as e:\n print(f\"Error loading dependencies: {e}\", file=sys.stderr)\n sys.exit(1)\n\n def generate_report(self):\n \"\"\"Main entry point - prints formatted report\"\"\"\n print() # Blank line before report\n print(\"=\" * 80)\n self._print_header()\n print(\"=\" * 80)\n print() # Blank line after header\n self._print_dependencies()\n print() # Blank line after dependencies\n print(\"* Optional requirement\")\n print(\"=\" * 80)\n\n # Collect failures and issues to show help for\n # Include required failures (is_failure=True) and optional issues (not SUCCESS)\n failures = []\n for req in self.requirements:\n if hasattr(req, \"is_failure\") and req.is_failure():\n # Required dependency that failed\n failures.append(req)\n elif (\n hasattr(req, \"status\")\n and hasattr(req, \"optional\")\n and req.optional\n and req.status != \"SUCCESS\"\n ):\n # Optional dependency with issues (NOT_FOUND or INCOMPATIBLE)\n failures.append(req)\n\n if failures:\n self._print_help_section(failures)\n # Only print failure summary if there are actual (non-optional) failures\n required_failures = [\n req\n for req in self.requirements\n if hasattr(req, \"is_failure\") and req.is_failure()\n ]\n if required_failures:\n self._print_failure_summary()\n\n print() # Blank line at end\n\n def _print_header(self):\n \"\"\"Print report header with platform information\"\"\"\n platform_str = format_platform_info(self.platform_info)\n print(\n colorize(\n self.colors.BOLD_GREEN, \"[nvFuser] Validating build prerequisites...\"\n )\n )\n print(colorize(self.colors.CYAN, \"Platform: \") + platform_str)\n\n def _print_failure_summary(self):\n \"\"\"Print failure summary message\"\"\"\n print()\n print(colorize(self.colors.BOLD_RED, \"Build prerequisite validation FAILED\"))\n print(\"See installation instructions above\")\n\n def _print_dependencies(self):\n \"\"\"Print status for each dependency using OOP requirement classes\"\"\"\n for req in self.requirements:","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies._print_header","uri":"program://Fuser/function/python.tools.check_dependencies._print_header#L117-L125","kind":"function","name":"_print_header","path":"python/tools/check_dependencies.py","language":"python","start_line":117,"end_line":125,"context_start_line":97,"context_end_line":145,"code":" and hasattr(req, \"optional\")\n and req.optional\n and req.status != \"SUCCESS\"\n ):\n # Optional dependency with issues (NOT_FOUND or INCOMPATIBLE)\n failures.append(req)\n\n if failures:\n self._print_help_section(failures)\n # Only print failure summary if there are actual (non-optional) failures\n required_failures = [\n req\n for req in self.requirements\n if hasattr(req, \"is_failure\") and req.is_failure()\n ]\n if required_failures:\n self._print_failure_summary()\n\n print() # Blank line at end\n\n def _print_header(self):\n \"\"\"Print report header with platform information\"\"\"\n platform_str = format_platform_info(self.platform_info)\n print(\n colorize(\n self.colors.BOLD_GREEN, \"[nvFuser] Validating build prerequisites...\"\n )\n )\n print(colorize(self.colors.CYAN, \"Platform: \") + platform_str)\n\n def _print_failure_summary(self):\n \"\"\"Print failure summary message\"\"\"\n print()\n print(colorize(self.colors.BOLD_RED, \"Build prerequisite validation FAILED\"))\n print(\"See installation instructions above\")\n\n def _print_dependencies(self):\n \"\"\"Print status for each dependency using OOP requirement classes\"\"\"\n for req in self.requirements:\n if hasattr(req, \"format_status_line\"):\n # OOP: use requirement's format method\n print(req.format_status_line(self.colors))\n else:\n # Fallback: use legacy dict-based formatting (shouldn't happen)\n print(f\"[nvFuser] ? {getattr(req, 'name', 'Unknown')}\")\n\n def _print_help_section(self, failures):\n \"\"\"Print help section header and help for each failed dependency\"\"\"\n print()","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies._print_failure_summary","uri":"program://Fuser/function/python.tools.check_dependencies._print_failure_summary#L127-L131","kind":"function","name":"_print_failure_summary","path":"python/tools/check_dependencies.py","language":"python","start_line":127,"end_line":131,"context_start_line":107,"context_end_line":151,"code":" required_failures = [\n req\n for req in self.requirements\n if hasattr(req, \"is_failure\") and req.is_failure()\n ]\n if required_failures:\n self._print_failure_summary()\n\n print() # Blank line at end\n\n def _print_header(self):\n \"\"\"Print report header with platform information\"\"\"\n platform_str = format_platform_info(self.platform_info)\n print(\n colorize(\n self.colors.BOLD_GREEN, \"[nvFuser] Validating build prerequisites...\"\n )\n )\n print(colorize(self.colors.CYAN, \"Platform: \") + platform_str)\n\n def _print_failure_summary(self):\n \"\"\"Print failure summary message\"\"\"\n print()\n print(colorize(self.colors.BOLD_RED, \"Build prerequisite validation FAILED\"))\n print(\"See installation instructions above\")\n\n def _print_dependencies(self):\n \"\"\"Print status for each dependency using OOP requirement classes\"\"\"\n for req in self.requirements:\n if hasattr(req, \"format_status_line\"):\n # OOP: use requirement's format method\n print(req.format_status_line(self.colors))\n else:\n # Fallback: use legacy dict-based formatting (shouldn't happen)\n print(f\"[nvFuser] ? {getattr(req, 'name', 'Unknown')}\")\n\n def _print_help_section(self, failures):\n \"\"\"Print help section header and help for each failed dependency\"\"\"\n print()\n print(\"=\" * 70)\n print(\"Installation Instructions\")\n print(\"=\" * 70)\n print()\n\n for req in failures:","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies._print_dependencies","uri":"program://Fuser/function/python.tools.check_dependencies._print_dependencies#L133-L141","kind":"function","name":"_print_dependencies","path":"python/tools/check_dependencies.py","language":"python","start_line":133,"end_line":141,"context_start_line":113,"context_end_line":161,"code":" self._print_failure_summary()\n\n print() # Blank line at end\n\n def _print_header(self):\n \"\"\"Print report header with platform information\"\"\"\n platform_str = format_platform_info(self.platform_info)\n print(\n colorize(\n self.colors.BOLD_GREEN, \"[nvFuser] Validating build prerequisites...\"\n )\n )\n print(colorize(self.colors.CYAN, \"Platform: \") + platform_str)\n\n def _print_failure_summary(self):\n \"\"\"Print failure summary message\"\"\"\n print()\n print(colorize(self.colors.BOLD_RED, \"Build prerequisite validation FAILED\"))\n print(\"See installation instructions above\")\n\n def _print_dependencies(self):\n \"\"\"Print status for each dependency using OOP requirement classes\"\"\"\n for req in self.requirements:\n if hasattr(req, \"format_status_line\"):\n # OOP: use requirement's format method\n print(req.format_status_line(self.colors))\n else:\n # Fallback: use legacy dict-based formatting (shouldn't happen)\n print(f\"[nvFuser] ? {getattr(req, 'name', 'Unknown')}\")\n\n def _print_help_section(self, failures):\n \"\"\"Print help section header and help for each failed dependency\"\"\"\n print()\n print(\"=\" * 70)\n print(\"Installation Instructions\")\n print(\"=\" * 70)\n print()\n\n for req in failures:\n self._print_help_for_requirement(req)\n\n def _print_help_for_requirement(self, req):\n \"\"\"Call requirement's help generation method\"\"\"\n if hasattr(req, \"generate_help\"):\n req.generate_help(self.platform_info)\n else:\n # Fallback for requirements without help\n print(f\"{req.name} installation help not available\")\n print()","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies._print_help_section","uri":"program://Fuser/function/python.tools.check_dependencies._print_help_section#L143-L152","kind":"function","name":"_print_help_section","path":"python/tools/check_dependencies.py","language":"python","start_line":143,"end_line":152,"context_start_line":123,"context_end_line":172,"code":" )\n )\n print(colorize(self.colors.CYAN, \"Platform: \") + platform_str)\n\n def _print_failure_summary(self):\n \"\"\"Print failure summary message\"\"\"\n print()\n print(colorize(self.colors.BOLD_RED, \"Build prerequisite validation FAILED\"))\n print(\"See installation instructions above\")\n\n def _print_dependencies(self):\n \"\"\"Print status for each dependency using OOP requirement classes\"\"\"\n for req in self.requirements:\n if hasattr(req, \"format_status_line\"):\n # OOP: use requirement's format method\n print(req.format_status_line(self.colors))\n else:\n # Fallback: use legacy dict-based formatting (shouldn't happen)\n print(f\"[nvFuser] ? {getattr(req, 'name', 'Unknown')}\")\n\n def _print_help_section(self, failures):\n \"\"\"Print help section header and help for each failed dependency\"\"\"\n print()\n print(\"=\" * 70)\n print(\"Installation Instructions\")\n print(\"=\" * 70)\n print()\n\n for req in failures:\n self._print_help_for_requirement(req)\n\n def _print_help_for_requirement(self, req):\n \"\"\"Call requirement's help generation method\"\"\"\n if hasattr(req, \"generate_help\"):\n req.generate_help(self.platform_info)\n else:\n # Fallback for requirements without help\n print(f\"{req.name} installation help not available\")\n print()\n\n\ndef main():\n if len(sys.argv) != 2:\n print(\"Usage: check_dependencies.py \", file=sys.stderr)\n sys.exit(1)\n\n json_path = Path(sys.argv[1])\n if not json_path.exists():\n print(f\"Error: {json_path} not found\", file=sys.stderr)\n sys.exit(1)","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.check_dependencies._print_help_for_requirement","uri":"program://Fuser/function/python.tools.check_dependencies._print_help_for_requirement#L154-L161","kind":"function","name":"_print_help_for_requirement","path":"python/tools/check_dependencies.py","language":"python","start_line":154,"end_line":161,"context_start_line":134,"context_end_line":181,"code":" \"\"\"Print status for each dependency using OOP requirement classes\"\"\"\n for req in self.requirements:\n if hasattr(req, \"format_status_line\"):\n # OOP: use requirement's format method\n print(req.format_status_line(self.colors))\n else:\n # Fallback: use legacy dict-based formatting (shouldn't happen)\n print(f\"[nvFuser] ? {getattr(req, 'name', 'Unknown')}\")\n\n def _print_help_section(self, failures):\n \"\"\"Print help section header and help for each failed dependency\"\"\"\n print()\n print(\"=\" * 70)\n print(\"Installation Instructions\")\n print(\"=\" * 70)\n print()\n\n for req in failures:\n self._print_help_for_requirement(req)\n\n def _print_help_for_requirement(self, req):\n \"\"\"Call requirement's help generation method\"\"\"\n if hasattr(req, \"generate_help\"):\n req.generate_help(self.platform_info)\n else:\n # Fallback for requirements without help\n print(f\"{req.name} installation help not available\")\n print()\n\n\ndef main():\n if len(sys.argv) != 2:\n print(\"Usage: check_dependencies.py \", file=sys.stderr)\n sys.exit(1)\n\n json_path = Path(sys.argv[1])\n if not json_path.exists():\n print(f\"Error: {json_path} not found\", file=sys.stderr)\n sys.exit(1)\n\n # Generate report\n reporter = DependencyReporter(json_path)\n reporter.generate_report()\n\n # Report generated successfully\n sys.exit(0)\n\n","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.gen_nvfuser_version","uri":"program://Fuser/module/python.tools.gen_nvfuser_version#L1-L78","kind":"module","name":"python.tools.gen_nvfuser_version","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":1,"end_line":78,"context_start_line":1,"context_end_line":78,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nUNKNOWN = \"Unknown\"\nnvfuser_root = Path(__file__).parent.parent\n\n\n# note that this root currently is still part of pytorch.\ndef get_sha() -> str:\n try:\n return (\n subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=nvfuser_root)\n .decode(\"ascii\")\n .strip()\n )\n except Exception:\n import os\n\n # assume the $NVFUSER_VERSION is in sha form\n if nvfuser_version := os.environ.get(\"NVFUSER_VERSION\"):\n assert (\n len(nvfuser_version) < 11\n ), \"The NVFUSER_VERSION should be in sha form\"\n return nvfuser_version\n return UNKNOWN\n\n\ndef get_version() -> str:\n sha = get_sha()\n version = (\n open((nvfuser_root / \"version.txt\"), \"r\").read().strip() + \"+git\" + sha[:7]\n )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\ndef get_pytorch_use_distributed():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch; print(torch._C._has_distributed())\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\nif __name__ == \"__main__\":\n assert len(sys.argv) == 2\n assert sys.argv[1] == \"nvfuser\" or sys.argv[1] == \"nvfuser_direct\"\n python_module = sys.argv[1]\n version_file = nvfuser_root / python_module / \"version.py\"\n with open(version_file, \"w\") as f:\n f.write(\"_version_str = '{}'\\n\".format(get_version()))","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.gen_nvfuser_version.get_sha","uri":"program://Fuser/function/python.tools.gen_nvfuser_version.get_sha#L13-L29","kind":"function","name":"get_sha","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":13,"end_line":29,"context_start_line":1,"context_end_line":49,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nUNKNOWN = \"Unknown\"\nnvfuser_root = Path(__file__).parent.parent\n\n\n# note that this root currently is still part of pytorch.\ndef get_sha() -> str:\n try:\n return (\n subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=nvfuser_root)\n .decode(\"ascii\")\n .strip()\n )\n except Exception:\n import os\n\n # assume the $NVFUSER_VERSION is in sha form\n if nvfuser_version := os.environ.get(\"NVFUSER_VERSION\"):\n assert (\n len(nvfuser_version) < 11\n ), \"The NVFUSER_VERSION should be in sha form\"\n return nvfuser_version\n return UNKNOWN\n\n\ndef get_version() -> str:\n sha = get_sha()\n version = (\n open((nvfuser_root / \"version.txt\"), \"r\").read().strip() + \"+git\" + sha[:7]\n )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.gen_nvfuser_version.get_version","uri":"program://Fuser/function/python.tools.gen_nvfuser_version.get_version#L32-L37","kind":"function","name":"get_version","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":32,"end_line":37,"context_start_line":12,"context_end_line":57,"code":"# note that this root currently is still part of pytorch.\ndef get_sha() -> str:\n try:\n return (\n subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=nvfuser_root)\n .decode(\"ascii\")\n .strip()\n )\n except Exception:\n import os\n\n # assume the $NVFUSER_VERSION is in sha form\n if nvfuser_version := os.environ.get(\"NVFUSER_VERSION\"):\n assert (\n len(nvfuser_version) < 11\n ), \"The NVFUSER_VERSION should be in sha form\"\n return nvfuser_version\n return UNKNOWN\n\n\ndef get_version() -> str:\n sha = get_sha()\n version = (\n open((nvfuser_root / \"version.txt\"), \"r\").read().strip() + \"+git\" + sha[:7]\n )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\ndef get_pytorch_use_distributed():\n from subprocess import Popen, PIPE","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.gen_nvfuser_version.get_pytorch_cmake_prefix","uri":"program://Fuser/function/python.tools.gen_nvfuser_version.get_pytorch_cmake_prefix#L40-L53","kind":"function","name":"get_pytorch_cmake_prefix","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":40,"end_line":53,"context_start_line":20,"context_end_line":73,"code":" except Exception:\n import os\n\n # assume the $NVFUSER_VERSION is in sha form\n if nvfuser_version := os.environ.get(\"NVFUSER_VERSION\"):\n assert (\n len(nvfuser_version) < 11\n ), \"The NVFUSER_VERSION should be in sha form\"\n return nvfuser_version\n return UNKNOWN\n\n\ndef get_version() -> str:\n sha = get_sha()\n version = (\n open((nvfuser_root / \"version.txt\"), \"r\").read().strip() + \"+git\" + sha[:7]\n )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\ndef get_pytorch_use_distributed():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch; print(torch._C._has_distributed())\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\nif __name__ == \"__main__\":\n assert len(sys.argv) == 2","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.gen_nvfuser_version.get_pytorch_use_distributed","uri":"program://Fuser/function/python.tools.gen_nvfuser_version.get_pytorch_use_distributed#L56-L69","kind":"function","name":"get_pytorch_use_distributed","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":56,"end_line":69,"context_start_line":36,"context_end_line":78,"code":" )\n return version\n\n\ndef get_pytorch_cmake_prefix():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch.utils; print(torch.utils.cmake_prefix_path)\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\ndef get_pytorch_use_distributed():\n from subprocess import Popen, PIPE\n\n # need to do this in a separate process so we are not going to delete nvfuser library while it's loaded by torch\n process_torch_prefix = Popen(\n [\n sys.executable,\n \"-c\",\n \"import torch; print(torch._C._has_distributed())\",\n ],\n stdout=PIPE,\n )\n stdout_msg, error_msg = process_torch_prefix.communicate()\n return stdout_msg.decode(\"utf-8\").rstrip(\"\\n\")\n\n\nif __name__ == \"__main__\":\n assert len(sys.argv) == 2\n assert sys.argv[1] == \"nvfuser\" or sys.argv[1] == \"nvfuser_direct\"\n python_module = sys.argv[1]\n version_file = nvfuser_root / python_module / \"version.py\"\n with open(version_file, \"w\") as f:\n f.write(\"_version_str = '{}'\\n\".format(get_version()))","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.colors","uri":"program://Fuser/module/python.tools.prereqs.colors#L1-L51","kind":"module","name":"python.tools.prereqs.colors","path":"python/tools/prereqs/colors.py","language":"python","start_line":1,"end_line":51,"context_start_line":1,"context_end_line":51,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nColor utilities for terminal output.\n\"\"\"\n\nimport os\n\n\nclass Colors:\n \"\"\"ANSI color codes for terminal output\"\"\"\n\n _codes = {\n \"RESET\": \"\\033[m\",\n \"BOLD\": \"\\033[1m\",\n # Regular colors\n \"GREEN\": \"\\033[32m\",\n \"YELLOW\": \"\\033[33m\",\n \"CYAN\": \"\\033[36m\",\n \"WHITE\": \"\\033[37m\",\n # Bold colors\n \"BOLD_RED\": \"\\033[1;31m\",\n \"BOLD_GREEN\": \"\\033[1;32m\",\n \"BOLD_WHITE\": \"\\033[1;37m\",\n }\n\n def __init__(self):\n use_colors = os.environ.get(\"NVFUSER_BUILD_DISABLE_COLOR\") is None\n\n for name, code in self._codes.items():\n setattr(self, name, code if use_colors else \"\")\n\n\ndef colorize(color: str, text: str) -> str:\n \"\"\"Helper to wrap text with color and reset codes.\n\n Args:\n color: The color code (e.g., colors.GREEN, colors.BOLD_RED)\n text: The text to colorize\n\n Returns:\n Text wrapped with color codes: text\n\n Example:\n >>> colors = Colors()\n >>> print(colorize(colors.GREEN, \"Success\") + \" - operation completed\")\n # Prints \"Success\" in green, followed by plain text\n \"\"\"\n RESET = \"\\033[m\"\n return f\"{color}{text}{RESET}\"","source_hash":"286e88472c79fd888dc46e4424aff33d19a3c7e604ab9b747ed08ccdbded6ffc","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.colors.Colors","uri":"program://Fuser/class/python.tools.prereqs.colors.Colors#L11-L32","kind":"class","name":"Colors","path":"python/tools/prereqs/colors.py","language":"python","start_line":11,"end_line":32,"context_start_line":1,"context_end_line":51,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nColor utilities for terminal output.\n\"\"\"\n\nimport os\n\n\nclass Colors:\n \"\"\"ANSI color codes for terminal output\"\"\"\n\n _codes = {\n \"RESET\": \"\\033[m\",\n \"BOLD\": \"\\033[1m\",\n # Regular colors\n \"GREEN\": \"\\033[32m\",\n \"YELLOW\": \"\\033[33m\",\n \"CYAN\": \"\\033[36m\",\n \"WHITE\": \"\\033[37m\",\n # Bold colors\n \"BOLD_RED\": \"\\033[1;31m\",\n \"BOLD_GREEN\": \"\\033[1;32m\",\n \"BOLD_WHITE\": \"\\033[1;37m\",\n }\n\n def __init__(self):\n use_colors = os.environ.get(\"NVFUSER_BUILD_DISABLE_COLOR\") is None\n\n for name, code in self._codes.items():\n setattr(self, name, code if use_colors else \"\")\n\n\ndef colorize(color: str, text: str) -> str:\n \"\"\"Helper to wrap text with color and reset codes.\n\n Args:\n color: The color code (e.g., colors.GREEN, colors.BOLD_RED)\n text: The text to colorize\n\n Returns:\n Text wrapped with color codes: text\n\n Example:\n >>> colors = Colors()\n >>> print(colorize(colors.GREEN, \"Success\") + \" - operation completed\")\n # Prints \"Success\" in green, followed by plain text\n \"\"\"\n RESET = \"\\033[m\"\n return f\"{color}{text}{RESET}\"","source_hash":"286e88472c79fd888dc46e4424aff33d19a3c7e604ab9b747ed08ccdbded6ffc","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.colors.colorize","uri":"program://Fuser/function/python.tools.prereqs.colors.colorize#L35-L51","kind":"function","name":"colorize","path":"python/tools/prereqs/colors.py","language":"python","start_line":35,"end_line":51,"context_start_line":15,"context_end_line":51,"code":" \"RESET\": \"\\033[m\",\n \"BOLD\": \"\\033[1m\",\n # Regular colors\n \"GREEN\": \"\\033[32m\",\n \"YELLOW\": \"\\033[33m\",\n \"CYAN\": \"\\033[36m\",\n \"WHITE\": \"\\033[37m\",\n # Bold colors\n \"BOLD_RED\": \"\\033[1;31m\",\n \"BOLD_GREEN\": \"\\033[1;32m\",\n \"BOLD_WHITE\": \"\\033[1;37m\",\n }\n\n def __init__(self):\n use_colors = os.environ.get(\"NVFUSER_BUILD_DISABLE_COLOR\") is None\n\n for name, code in self._codes.items():\n setattr(self, name, code if use_colors else \"\")\n\n\ndef colorize(color: str, text: str) -> str:\n \"\"\"Helper to wrap text with color and reset codes.\n\n Args:\n color: The color code (e.g., colors.GREEN, colors.BOLD_RED)\n text: The text to colorize\n\n Returns:\n Text wrapped with color codes: text\n\n Example:\n >>> colors = Colors()\n >>> print(colorize(colors.GREEN, \"Success\") + \" - operation completed\")\n # Prints \"Success\" in green, followed by plain text\n \"\"\"\n RESET = \"\\033[m\"\n return f\"{color}{text}{RESET}\"","source_hash":"286e88472c79fd888dc46e4424aff33d19a3c7e604ab9b747ed08ccdbded6ffc","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.colors.__init__","uri":"program://Fuser/function/python.tools.prereqs.colors.__init__#L28-L32","kind":"function","name":"__init__","path":"python/tools/prereqs/colors.py","language":"python","start_line":28,"end_line":32,"context_start_line":8,"context_end_line":51,"code":"import os\n\n\nclass Colors:\n \"\"\"ANSI color codes for terminal output\"\"\"\n\n _codes = {\n \"RESET\": \"\\033[m\",\n \"BOLD\": \"\\033[1m\",\n # Regular colors\n \"GREEN\": \"\\033[32m\",\n \"YELLOW\": \"\\033[33m\",\n \"CYAN\": \"\\033[36m\",\n \"WHITE\": \"\\033[37m\",\n # Bold colors\n \"BOLD_RED\": \"\\033[1;31m\",\n \"BOLD_GREEN\": \"\\033[1;32m\",\n \"BOLD_WHITE\": \"\\033[1;37m\",\n }\n\n def __init__(self):\n use_colors = os.environ.get(\"NVFUSER_BUILD_DISABLE_COLOR\") is None\n\n for name, code in self._codes.items():\n setattr(self, name, code if use_colors else \"\")\n\n\ndef colorize(color: str, text: str) -> str:\n \"\"\"Helper to wrap text with color and reset codes.\n\n Args:\n color: The color code (e.g., colors.GREEN, colors.BOLD_RED)\n text: The text to colorize\n\n Returns:\n Text wrapped with color codes: text\n\n Example:\n >>> colors = Colors()\n >>> print(colorize(colors.GREEN, \"Success\") + \" - operation completed\")\n # Prints \"Success\" in green, followed by plain text\n \"\"\"\n RESET = \"\\033[m\"\n return f\"{color}{text}{RESET}\"","source_hash":"286e88472c79fd888dc46e4424aff33d19a3c7e604ab9b747ed08ccdbded6ffc","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.exceptions","uri":"program://Fuser/module/python.tools.prereqs.exceptions#L1-L23","kind":"module","name":"python.tools.prereqs.exceptions","path":"python/tools/prereqs/exceptions.py","language":"python","start_line":1,"end_line":23,"context_start_line":1,"context_end_line":23,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nCustom exceptions for nvFuser prerequisite validation.\n\nThese exceptions provide structured error handling for build prerequisite\nchecks, enabling clear and actionable error messages.\n\"\"\"\n\n\nclass PrerequisiteMissingError(Exception):\n \"\"\"\n Raised when a prerequisite for building nvFuser is missing or has an incorrect version.\n\n This exception should include:\n - What prerequisite is missing or incorrect\n - Why it's required\n - Exact commands to install or fix it\n - Platform-specific guidance when applicable\n \"\"\"\n\n pass","source_hash":"49836a66031691ac0e5c084856917aac6929932a4f6f497db05609e3b23bd474","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.exceptions.PrerequisiteMissingError","uri":"program://Fuser/class/python.tools.prereqs.exceptions.PrerequisiteMissingError#L12-L23","kind":"class","name":"PrerequisiteMissingError","path":"python/tools/prereqs/exceptions.py","language":"python","start_line":12,"end_line":23,"context_start_line":1,"context_end_line":23,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nCustom exceptions for nvFuser prerequisite validation.\n\nThese exceptions provide structured error handling for build prerequisite\nchecks, enabling clear and actionable error messages.\n\"\"\"\n\n\nclass PrerequisiteMissingError(Exception):\n \"\"\"\n Raised when a prerequisite for building nvFuser is missing or has an incorrect version.\n\n This exception should include:\n - What prerequisite is missing or incorrect\n - Why it's required\n - Exact commands to install or fix it\n - Platform-specific guidance when applicable\n \"\"\"\n\n pass","source_hash":"49836a66031691ac0e5c084856917aac6929932a4f6f497db05609e3b23bd474","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.platform","uri":"program://Fuser/module/python.tools.prereqs.platform#L1-L129","kind":"module","name":"python.tools.prereqs.platform","path":"python/tools/prereqs/platform.py","language":"python","start_line":1,"end_line":129,"context_start_line":1,"context_end_line":129,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nPlatform detection utilities for nvFuser build system.\n\nDetects OS, architecture, and Linux distribution to provide platform-specific\nerror messages and installation guidance.\n\"\"\"\n\nimport platform\nfrom typing import Dict, Optional\n\n\ndef detect_platform() -> Dict[str, Optional[str]]:\n \"\"\"\n Detect the current platform and return structured information.\n\n Returns:\n dict: Platform information with keys:\n - 'os': Operating system (Linux, Darwin, Windows, etc.)\n - 'arch': Architecture (x86_64, aarch64, arm64, etc.)\n - 'distro': Linux distribution ID (ubuntu, debian, rhel, etc.) or None\n - 'distro_version': Distribution version (22.04, 20.04, etc.) or None\n - 'distro_name': Human-readable distribution name or None\n - 'ubuntu_based': Boolean indicating if this is Ubuntu-based distro\n\n Example:\n >>> info = detect_platform()\n >>> print(info['os'])\n 'Linux'\n >>> print(info['distro'])\n 'ubuntu'\n \"\"\"\n system = platform.system()\n machine = platform.machine()\n\n # Initialize distro information\n distro_info = {}\n distro_id = None\n distro_version = None\n distro_name = None\n ubuntu_based = False\n\n # Detect Linux distribution from /etc/os-release\n if system == \"Linux\":\n try:\n with open(\"/etc/os-release\") as f:\n for line in f:\n line = line.strip()\n if \"=\" in line:\n key, value = line.split(\"=\", 1)\n # Remove quotes from value\n distro_info[key] = value.strip('\"').strip(\"'\")\n\n distro_id = distro_info.get(\"ID\", \"unknown\")\n distro_version = distro_info.get(\"VERSION_ID\", \"unknown\")\n distro_name = distro_info.get(\"NAME\", \"unknown\")\n\n # Check if Ubuntu-based (useful for PPA availability)\n ubuntu_based = distro_id in (\n \"ubuntu\",\n \"debian\",\n \"linuxmint\",\n \"pop\",\n \"zorin\",\n )\n\n except FileNotFoundError:\n # /etc/os-release doesn't exist (not a standard Linux or very old system)\n distro_id = \"unknown\"\n distro_version = \"unknown\"\n distro_name = \"unknown\"\n except Exception as e:\n # Other errors reading/parsing the file\n distro_id = f\"error: {e}\"\n distro_version = \"unknown\"\n distro_name = \"unknown\"\n\n return {\n \"os\": system,\n \"arch\": machine,\n \"distro\": distro_id,\n \"distro_version\": distro_version,\n \"distro_name\": distro_name,\n \"ubuntu_based\": ubuntu_based,\n }\n\n\ndef format_platform_info(\n platform_info: Optional[Dict[str, Optional[str]]] = None\n) -> str:\n \"\"\"\n Format platform information as a human-readable string.\n\n Args:\n platform_info: Platform information dict from detect_platform().\n If None, will call detect_platform() automatically.\n\n Returns:\n str: Formatted platform string like \"Linux x86_64 (Ubuntu 22.04)\"\n\n Example:\n >>> print(format_platform_info())\n 'Linux x86_64 (Ubuntu 22.04)'\n \"\"\"\n if platform_info is None:\n platform_info = detect_platform()\n\n os_name = platform_info[\"os\"]\n arch = platform_info[\"arch\"]\n\n # Build distro info if available\n distro_parts = []\n if platform_info.get(\"distro\") and platform_info[\"distro\"] not in (\n \"unknown\",\n \"error\",\n ):\n distro_parts.append(platform_info[\"distro\"].capitalize())\n if (\n platform_info.get(\"distro_version\")\n and platform_info[\"distro_version\"] != \"unknown\"\n ):\n distro_parts.append(platform_info[\"distro_version\"])\n\n if distro_parts:\n return f\"{os_name} {arch} ({' '.join(distro_parts)})\"\n else:\n return f\"{os_name} {arch}\"","source_hash":"0cc4908454ea1420ec0a0158c8ccfd93b0d300c26cdbb26196856eb9184f7271","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.platform.detect_platform","uri":"program://Fuser/function/python.tools.prereqs.platform.detect_platform#L15-L87","kind":"function","name":"detect_platform","path":"python/tools/prereqs/platform.py","language":"python","start_line":15,"end_line":87,"context_start_line":1,"context_end_line":107,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nPlatform detection utilities for nvFuser build system.\n\nDetects OS, architecture, and Linux distribution to provide platform-specific\nerror messages and installation guidance.\n\"\"\"\n\nimport platform\nfrom typing import Dict, Optional\n\n\ndef detect_platform() -> Dict[str, Optional[str]]:\n \"\"\"\n Detect the current platform and return structured information.\n\n Returns:\n dict: Platform information with keys:\n - 'os': Operating system (Linux, Darwin, Windows, etc.)\n - 'arch': Architecture (x86_64, aarch64, arm64, etc.)\n - 'distro': Linux distribution ID (ubuntu, debian, rhel, etc.) or None\n - 'distro_version': Distribution version (22.04, 20.04, etc.) or None\n - 'distro_name': Human-readable distribution name or None\n - 'ubuntu_based': Boolean indicating if this is Ubuntu-based distro\n\n Example:\n >>> info = detect_platform()\n >>> print(info['os'])\n 'Linux'\n >>> print(info['distro'])\n 'ubuntu'\n \"\"\"\n system = platform.system()\n machine = platform.machine()\n\n # Initialize distro information\n distro_info = {}\n distro_id = None\n distro_version = None\n distro_name = None\n ubuntu_based = False\n\n # Detect Linux distribution from /etc/os-release\n if system == \"Linux\":\n try:\n with open(\"/etc/os-release\") as f:\n for line in f:\n line = line.strip()\n if \"=\" in line:\n key, value = line.split(\"=\", 1)\n # Remove quotes from value\n distro_info[key] = value.strip('\"').strip(\"'\")\n\n distro_id = distro_info.get(\"ID\", \"unknown\")\n distro_version = distro_info.get(\"VERSION_ID\", \"unknown\")\n distro_name = distro_info.get(\"NAME\", \"unknown\")\n\n # Check if Ubuntu-based (useful for PPA availability)\n ubuntu_based = distro_id in (\n \"ubuntu\",\n \"debian\",\n \"linuxmint\",\n \"pop\",\n \"zorin\",\n )\n\n except FileNotFoundError:\n # /etc/os-release doesn't exist (not a standard Linux or very old system)\n distro_id = \"unknown\"\n distro_version = \"unknown\"\n distro_name = \"unknown\"\n except Exception as e:\n # Other errors reading/parsing the file\n distro_id = f\"error: {e}\"\n distro_version = \"unknown\"\n distro_name = \"unknown\"\n\n return {\n \"os\": system,\n \"arch\": machine,\n \"distro\": distro_id,\n \"distro_version\": distro_version,\n \"distro_name\": distro_name,\n \"ubuntu_based\": ubuntu_based,\n }\n\n\ndef format_platform_info(\n platform_info: Optional[Dict[str, Optional[str]]] = None\n) -> str:\n \"\"\"\n Format platform information as a human-readable string.\n\n Args:\n platform_info: Platform information dict from detect_platform().\n If None, will call detect_platform() automatically.\n\n Returns:\n str: Formatted platform string like \"Linux x86_64 (Ubuntu 22.04)\"\n\n Example:\n >>> print(format_platform_info())\n 'Linux x86_64 (Ubuntu 22.04)'\n \"\"\"\n if platform_info is None:","source_hash":"0cc4908454ea1420ec0a0158c8ccfd93b0d300c26cdbb26196856eb9184f7271","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.platform.format_platform_info","uri":"program://Fuser/function/python.tools.prereqs.platform.format_platform_info#L90-L129","kind":"function","name":"format_platform_info","path":"python/tools/prereqs/platform.py","language":"python","start_line":90,"end_line":129,"context_start_line":70,"context_end_line":129,"code":" # /etc/os-release doesn't exist (not a standard Linux or very old system)\n distro_id = \"unknown\"\n distro_version = \"unknown\"\n distro_name = \"unknown\"\n except Exception as e:\n # Other errors reading/parsing the file\n distro_id = f\"error: {e}\"\n distro_version = \"unknown\"\n distro_name = \"unknown\"\n\n return {\n \"os\": system,\n \"arch\": machine,\n \"distro\": distro_id,\n \"distro_version\": distro_version,\n \"distro_name\": distro_name,\n \"ubuntu_based\": ubuntu_based,\n }\n\n\ndef format_platform_info(\n platform_info: Optional[Dict[str, Optional[str]]] = None\n) -> str:\n \"\"\"\n Format platform information as a human-readable string.\n\n Args:\n platform_info: Platform information dict from detect_platform().\n If None, will call detect_platform() automatically.\n\n Returns:\n str: Formatted platform string like \"Linux x86_64 (Ubuntu 22.04)\"\n\n Example:\n >>> print(format_platform_info())\n 'Linux x86_64 (Ubuntu 22.04)'\n \"\"\"\n if platform_info is None:\n platform_info = detect_platform()\n\n os_name = platform_info[\"os\"]\n arch = platform_info[\"arch\"]\n\n # Build distro info if available\n distro_parts = []\n if platform_info.get(\"distro\") and platform_info[\"distro\"] not in (\n \"unknown\",\n \"error\",\n ):\n distro_parts.append(platform_info[\"distro\"].capitalize())\n if (\n platform_info.get(\"distro_version\")\n and platform_info[\"distro_version\"] != \"unknown\"\n ):\n distro_parts.append(platform_info[\"distro_version\"])\n\n if distro_parts:\n return f\"{os_name} {arch} ({' '.join(distro_parts)})\"\n else:\n return f\"{os_name} {arch}\"","source_hash":"0cc4908454ea1420ec0a0158c8ccfd93b0d300c26cdbb26196856eb9184f7271","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils","uri":"program://Fuser/module/python.tools.prereqs.requirement_utils#L1-L257","kind":"module","name":"python.tools.prereqs.requirement_utils","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":1,"end_line":257,"context_start_line":1,"context_end_line":257,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nUtility functions for nvFuser dependency reporting.\n\nIMPORTANT: This module provides ONLY utility functions for formatting and URL generation.\nVersion requirements and dependency validation are handled by CMake.\n\nCMake defines requirements in: cmake/DependencyRequirements.cmake\nCMake exports status to: build/nvfuser_dependencies.json\nPython reads JSON and uses these utilities to format help text.\n\"\"\"\n\nimport platform\nimport re\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple\n\n\n# =============================================================================\n# VERSION CONVERSION UTILITIES\n# =============================================================================\n\n\ndef parse_version(version_str: str) -> Tuple[int, ...]:\n \"\"\"\n Parse version string to tuple.\n\n Args:\n version_str: Version string like \"3.8\", \"18.1.8\", \"13\", \"18.1.8git\"\n\n Returns:\n Tuple of integers: (3, 8), (18, 1, 8), (13,), (18, 1, 8)\n\n Examples:\n >>> parse_version(\"3.8\")\n (3, 8)\n >>> parse_version(\"18.1.8\")\n (18, 1, 8)\n >>> parse_version(\"18.1.8git\") # strips non-numeric suffix\n (18, 1, 8)\n\n Raises:\n ValueError: If version string cannot be parsed\n \"\"\"\n # Strip common suffixes like \"git\", \"rc1\", \"+cu128\", etc.\n clean = re.match(r\"^[\\d.]+\", version_str.strip())\n if not clean:\n raise ValueError(f\"Cannot parse version: {version_str}\")\n\n parts = clean.group().rstrip(\".\").split(\".\")\n return tuple(int(p) for p in parts if p)\n\n\ndef format_version(version: Tuple[int, ...]) -> str:\n \"\"\"\n Format version tuple to string.\n\n Args:\n version: Tuple of integers like (3, 8), (18, 1, 8), (13,)\n\n Returns:\n Version string: \"3.8\", \"18.1.8\", \"13\"\n\n Examples:\n >>> format_version((3, 8))\n '3.8'\n >>> format_version((18, 1, 8))\n '18.1.8'\n >>> format_version((13,))\n '13'\n \"\"\"\n return \".\".join(map(str, version))\n\n\n# =============================================================================\n# REQUIREMENT DATACLASS (Utility Only)\n# =============================================================================\n\n\n@dataclass\nclass Requirement:\n \"\"\"\n A version requirement utility class (NOT the source of truth).\n\n NOTE: This is for utility methods only. Actual version requirements come from\n CMake's DependencyRequirements.cmake and are exported via JSON.\n\n Attributes:\n name: Human-readable name (e.g., \"CMake\", \"LLVM\")\n min_version: Minimum required version tuple, or None for \"any version\"\n recommended: Recommended version tuple for download URLs (optional)\n \"\"\"\n\n name: str\n min_version: Optional[Tuple[int, ...]]\n recommended: Optional[Tuple[int, ...]] = None\n\n @property\n def min_str(self) -> str:\n \"\"\"Minimum version as string: '3.18' or 'any'\"\"\"\n if self.min_version is None:\n return \"any\"\n return format_version(self.min_version)\n\n @property\n def min_display(self) -> str:\n \"\"\"Minimum version for display: '3.18+' or 'any version'\"\"\"\n if self.min_version is None:\n return \"any version\"\n return f\"{self.min_str}+\"\n\n @property\n def recommended_str(self) -> str:\n \"\"\"Recommended version as string, falls back to min_str\"\"\"\n if self.recommended is None:\n return self.min_str\n return format_version(self.recommended)\n\n def check(self, detected: Tuple[int, ...]) -> bool:\n \"\"\"\n Check if detected version meets minimum requirement.\n\n Args:\n detected: Detected version tuple (e.g., from parse_version)\n\n Returns:\n True if detected >= min_version (or min_version is None)\n\n Note:\n Compares only as many parts as min_version specifies.\n So (3, 22, 1) >= (3, 18) compares (3, 22) >= (3, 18) -> True\n \"\"\"\n if self.min_version is None:\n return True\n # Compare only as many parts as min_version specifies\n return detected[: len(self.min_version)] >= self.min_version\n\n\n# =============================================================================\n# CUDA VERSIONS - For PyTorch wheel URLs\n# =============================================================================\n\n# PyTorch wheel CUDA versions currently available (newest first)\nCUDA_AVAILABLE = [(13, 1), (13, 0), (12, 8)]\n\n\n# =============================================================================\n# URL GENERATORS\n# =============================================================================\n\n\ndef cuda_wheel_suffix(cuda: Tuple[int, int]) -> str:\n \"\"\"\n Convert CUDA version tuple to PyTorch wheel suffix.\n\n Examples:\n >>> cuda_wheel_suffix((12, 8))\n 'cu128'\n >>> cuda_wheel_suffix((13, 1))\n 'cu131'\n \"\"\"\n return f\"cu{cuda[0]}{cuda[1]}\"\n\n\ndef pytorch_index_url(cuda: Tuple[int, int]) -> str:\n \"\"\"\n Generate PyTorch wheel index URL for a CUDA version.\n\n Examples:\n >>> pytorch_index_url((12, 8))\n 'https://download.pytorch.org/whl/cu128'\n >>> pytorch_index_url((13, 1))\n 'https://download.pytorch.org/whl/cu131'\n \"\"\"\n return f\"https://download.pytorch.org/whl/{cuda_wheel_suffix(cuda)}\"\n\n\ndef pytorch_install_instructions(cuda_major: Optional[int] = None) -> str:\n \"\"\"\n Generate PyTorch installation instructions.\n\n Args:\n cuda_major: If specified, only show instructions for this CUDA major version.\n Otherwise show all available versions.\n\n Returns:\n Multi-line string with pip install commands\n \"\"\"\n if cuda_major is not None:\n # Filter to matching CUDA major version\n matching = [cuda for cuda in CUDA_AVAILABLE if cuda[0] == cuda_major]\n versions_to_show = matching if matching else CUDA_AVAILABLE\n else:\n versions_to_show = CUDA_AVAILABLE\n\n lines = []\n for cuda in versions_to_show:\n lines.append(f\" # For CUDA {format_version(cuda)}:\")\n lines.append(f\" pip install torch --index-url {pytorch_index_url(cuda)}\")\n return \"\\n\".join(lines)\n\n\ndef llvm_download_url(version: Optional[Tuple[int, ...]] = None) -> str:\n \"\"\"\n Generate LLVM prebuilt binary download URL.\n\n Args:\n version: LLVM version tuple. If None, uses (18, 1, 8) as default.\n\n Returns:\n GitHub release URL for prebuilt binary matching current platform\n\n Raises:\n NotImplementedError: If platform is not supported\n\n Example:\n >>> llvm_download_url((18, 1, 8)) # doctest: +SKIP\n 'https://github.com/llvm/llvm-project/releases/download/llvmorg-18.1.8/clang+llvm-18.1.8-x86_64-linux-gnu-ubuntu-18.04.tar.xz'\n \"\"\"\n if version is None:\n version = (18, 1, 8)\n\n v = format_version(version)\n machine = platform.machine()\n\n if machine == \"x86_64\":\n return (\n f\"https://github.com/llvm/llvm-project/releases/download/\"\n f\"llvmorg-{v}/clang+llvm-{v}-x86_64-linux-gnu-ubuntu-18.04.tar.xz\"\n )\n elif machine == \"aarch64\":\n return (\n f\"https://github.com/llvm/llvm-project/releases/download/\"\n f\"llvmorg-{v}/clang+llvm-{v}-aarch64-linux-gnu.tar.xz\"\n )\n elif machine.startswith(\"arm64\"):\n # 64-bit ARM (macOS)\n return (\n f\"https://github.com/llvm/llvm-project/releases/download/\"\n f\"llvmorg-{v}/clang+llvm-{v}-arm64-apple-macos11.tar.xz\"\n )\n else:\n raise NotImplementedError(\n f\"LLVM prebuilt binaries not available for: {machine}\"\n )\n\n\ndef cuda_toolkit_download_url() -> str:\n \"\"\"\n Return NVIDIA CUDA Toolkit download page URL.\n\n Returns:\n URL to CUDA downloads page\n \"\"\"\n return \"https://developer.nvidia.com/cuda-downloads\"","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.parse_version","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.parse_version#L26-L53","kind":"function","name":"parse_version","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":26,"end_line":53,"context_start_line":6,"context_end_line":73,"code":"\nIMPORTANT: This module provides ONLY utility functions for formatting and URL generation.\nVersion requirements and dependency validation are handled by CMake.\n\nCMake defines requirements in: cmake/DependencyRequirements.cmake\nCMake exports status to: build/nvfuser_dependencies.json\nPython reads JSON and uses these utilities to format help text.\n\"\"\"\n\nimport platform\nimport re\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple\n\n\n# =============================================================================\n# VERSION CONVERSION UTILITIES\n# =============================================================================\n\n\ndef parse_version(version_str: str) -> Tuple[int, ...]:\n \"\"\"\n Parse version string to tuple.\n\n Args:\n version_str: Version string like \"3.8\", \"18.1.8\", \"13\", \"18.1.8git\"\n\n Returns:\n Tuple of integers: (3, 8), (18, 1, 8), (13,), (18, 1, 8)\n\n Examples:\n >>> parse_version(\"3.8\")\n (3, 8)\n >>> parse_version(\"18.1.8\")\n (18, 1, 8)\n >>> parse_version(\"18.1.8git\") # strips non-numeric suffix\n (18, 1, 8)\n\n Raises:\n ValueError: If version string cannot be parsed\n \"\"\"\n # Strip common suffixes like \"git\", \"rc1\", \"+cu128\", etc.\n clean = re.match(r\"^[\\d.]+\", version_str.strip())\n if not clean:\n raise ValueError(f\"Cannot parse version: {version_str}\")\n\n parts = clean.group().rstrip(\".\").split(\".\")\n return tuple(int(p) for p in parts if p)\n\n\ndef format_version(version: Tuple[int, ...]) -> str:\n \"\"\"\n Format version tuple to string.\n\n Args:\n version: Tuple of integers like (3, 8), (18, 1, 8), (13,)\n\n Returns:\n Version string: \"3.8\", \"18.1.8\", \"13\"\n\n Examples:\n >>> format_version((3, 8))\n '3.8'\n >>> format_version((18, 1, 8))\n '18.1.8'\n >>> format_version((13,))\n '13'\n \"\"\"","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.format_version","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.format_version#L56-L74","kind":"function","name":"format_version","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":56,"end_line":74,"context_start_line":36,"context_end_line":94,"code":" Examples:\n >>> parse_version(\"3.8\")\n (3, 8)\n >>> parse_version(\"18.1.8\")\n (18, 1, 8)\n >>> parse_version(\"18.1.8git\") # strips non-numeric suffix\n (18, 1, 8)\n\n Raises:\n ValueError: If version string cannot be parsed\n \"\"\"\n # Strip common suffixes like \"git\", \"rc1\", \"+cu128\", etc.\n clean = re.match(r\"^[\\d.]+\", version_str.strip())\n if not clean:\n raise ValueError(f\"Cannot parse version: {version_str}\")\n\n parts = clean.group().rstrip(\".\").split(\".\")\n return tuple(int(p) for p in parts if p)\n\n\ndef format_version(version: Tuple[int, ...]) -> str:\n \"\"\"\n Format version tuple to string.\n\n Args:\n version: Tuple of integers like (3, 8), (18, 1, 8), (13,)\n\n Returns:\n Version string: \"3.8\", \"18.1.8\", \"13\"\n\n Examples:\n >>> format_version((3, 8))\n '3.8'\n >>> format_version((18, 1, 8))\n '18.1.8'\n >>> format_version((13,))\n '13'\n \"\"\"\n return \".\".join(map(str, version))\n\n\n# =============================================================================\n# REQUIREMENT DATACLASS (Utility Only)\n# =============================================================================\n\n\n@dataclass\nclass Requirement:\n \"\"\"\n A version requirement utility class (NOT the source of truth).\n\n NOTE: This is for utility methods only. Actual version requirements come from\n CMake's DependencyRequirements.cmake and are exported via JSON.\n\n Attributes:\n name: Human-readable name (e.g., \"CMake\", \"LLVM\")\n min_version: Minimum required version tuple, or None for \"any version\"\n recommended: Recommended version tuple for download URLs (optional)\n \"\"\"","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.Requirement","uri":"program://Fuser/class/python.tools.prereqs.requirement_utils.Requirement#L83-L138","kind":"class","name":"Requirement","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":83,"end_line":138,"context_start_line":63,"context_end_line":158,"code":" Returns:\n Version string: \"3.8\", \"18.1.8\", \"13\"\n\n Examples:\n >>> format_version((3, 8))\n '3.8'\n >>> format_version((18, 1, 8))\n '18.1.8'\n >>> format_version((13,))\n '13'\n \"\"\"\n return \".\".join(map(str, version))\n\n\n# =============================================================================\n# REQUIREMENT DATACLASS (Utility Only)\n# =============================================================================\n\n\n@dataclass\nclass Requirement:\n \"\"\"\n A version requirement utility class (NOT the source of truth).\n\n NOTE: This is for utility methods only. Actual version requirements come from\n CMake's DependencyRequirements.cmake and are exported via JSON.\n\n Attributes:\n name: Human-readable name (e.g., \"CMake\", \"LLVM\")\n min_version: Minimum required version tuple, or None for \"any version\"\n recommended: Recommended version tuple for download URLs (optional)\n \"\"\"\n\n name: str\n min_version: Optional[Tuple[int, ...]]\n recommended: Optional[Tuple[int, ...]] = None\n\n @property\n def min_str(self) -> str:\n \"\"\"Minimum version as string: '3.18' or 'any'\"\"\"\n if self.min_version is None:\n return \"any\"\n return format_version(self.min_version)\n\n @property\n def min_display(self) -> str:\n \"\"\"Minimum version for display: '3.18+' or 'any version'\"\"\"\n if self.min_version is None:\n return \"any version\"\n return f\"{self.min_str}+\"\n\n @property\n def recommended_str(self) -> str:\n \"\"\"Recommended version as string, falls back to min_str\"\"\"\n if self.recommended is None:\n return self.min_str\n return format_version(self.recommended)\n\n def check(self, detected: Tuple[int, ...]) -> bool:\n \"\"\"\n Check if detected version meets minimum requirement.\n\n Args:\n detected: Detected version tuple (e.g., from parse_version)\n\n Returns:\n True if detected >= min_version (or min_version is None)\n\n Note:\n Compares only as many parts as min_version specifies.\n So (3, 22, 1) >= (3, 18) compares (3, 22) >= (3, 18) -> True\n \"\"\"\n if self.min_version is None:\n return True\n # Compare only as many parts as min_version specifies\n return detected[: len(self.min_version)] >= self.min_version\n\n\n# =============================================================================\n# CUDA VERSIONS - For PyTorch wheel URLs\n# =============================================================================\n\n# PyTorch wheel CUDA versions currently available (newest first)\nCUDA_AVAILABLE = [(13, 1), (13, 0), (12, 8)]\n\n\n# =============================================================================\n# URL GENERATORS\n# =============================================================================\n\n\ndef cuda_wheel_suffix(cuda: Tuple[int, int]) -> str:\n \"\"\"\n Convert CUDA version tuple to PyTorch wheel suffix.\n\n Examples:","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.cuda_wheel_suffix","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.cuda_wheel_suffix#L154-L164","kind":"function","name":"cuda_wheel_suffix","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":154,"end_line":164,"context_start_line":134,"context_end_line":184,"code":" \"\"\"\n if self.min_version is None:\n return True\n # Compare only as many parts as min_version specifies\n return detected[: len(self.min_version)] >= self.min_version\n\n\n# =============================================================================\n# CUDA VERSIONS - For PyTorch wheel URLs\n# =============================================================================\n\n# PyTorch wheel CUDA versions currently available (newest first)\nCUDA_AVAILABLE = [(13, 1), (13, 0), (12, 8)]\n\n\n# =============================================================================\n# URL GENERATORS\n# =============================================================================\n\n\ndef cuda_wheel_suffix(cuda: Tuple[int, int]) -> str:\n \"\"\"\n Convert CUDA version tuple to PyTorch wheel suffix.\n\n Examples:\n >>> cuda_wheel_suffix((12, 8))\n 'cu128'\n >>> cuda_wheel_suffix((13, 1))\n 'cu131'\n \"\"\"\n return f\"cu{cuda[0]}{cuda[1]}\"\n\n\ndef pytorch_index_url(cuda: Tuple[int, int]) -> str:\n \"\"\"\n Generate PyTorch wheel index URL for a CUDA version.\n\n Examples:\n >>> pytorch_index_url((12, 8))\n 'https://download.pytorch.org/whl/cu128'\n >>> pytorch_index_url((13, 1))\n 'https://download.pytorch.org/whl/cu131'\n \"\"\"\n return f\"https://download.pytorch.org/whl/{cuda_wheel_suffix(cuda)}\"\n\n\ndef pytorch_install_instructions(cuda_major: Optional[int] = None) -> str:\n \"\"\"\n Generate PyTorch installation instructions.\n\n Args:","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.pytorch_index_url","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.pytorch_index_url#L167-L177","kind":"function","name":"pytorch_index_url","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":167,"end_line":177,"context_start_line":147,"context_end_line":197,"code":"\n\n# =============================================================================\n# URL GENERATORS\n# =============================================================================\n\n\ndef cuda_wheel_suffix(cuda: Tuple[int, int]) -> str:\n \"\"\"\n Convert CUDA version tuple to PyTorch wheel suffix.\n\n Examples:\n >>> cuda_wheel_suffix((12, 8))\n 'cu128'\n >>> cuda_wheel_suffix((13, 1))\n 'cu131'\n \"\"\"\n return f\"cu{cuda[0]}{cuda[1]}\"\n\n\ndef pytorch_index_url(cuda: Tuple[int, int]) -> str:\n \"\"\"\n Generate PyTorch wheel index URL for a CUDA version.\n\n Examples:\n >>> pytorch_index_url((12, 8))\n 'https://download.pytorch.org/whl/cu128'\n >>> pytorch_index_url((13, 1))\n 'https://download.pytorch.org/whl/cu131'\n \"\"\"\n return f\"https://download.pytorch.org/whl/{cuda_wheel_suffix(cuda)}\"\n\n\ndef pytorch_install_instructions(cuda_major: Optional[int] = None) -> str:\n \"\"\"\n Generate PyTorch installation instructions.\n\n Args:\n cuda_major: If specified, only show instructions for this CUDA major version.\n Otherwise show all available versions.\n\n Returns:\n Multi-line string with pip install commands\n \"\"\"\n if cuda_major is not None:\n # Filter to matching CUDA major version\n matching = [cuda for cuda in CUDA_AVAILABLE if cuda[0] == cuda_major]\n versions_to_show = matching if matching else CUDA_AVAILABLE\n else:\n versions_to_show = CUDA_AVAILABLE\n","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.pytorch_install_instructions","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.pytorch_install_instructions#L180-L202","kind":"function","name":"pytorch_install_instructions","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":180,"end_line":202,"context_start_line":160,"context_end_line":222,"code":" 'cu128'\n >>> cuda_wheel_suffix((13, 1))\n 'cu131'\n \"\"\"\n return f\"cu{cuda[0]}{cuda[1]}\"\n\n\ndef pytorch_index_url(cuda: Tuple[int, int]) -> str:\n \"\"\"\n Generate PyTorch wheel index URL for a CUDA version.\n\n Examples:\n >>> pytorch_index_url((12, 8))\n 'https://download.pytorch.org/whl/cu128'\n >>> pytorch_index_url((13, 1))\n 'https://download.pytorch.org/whl/cu131'\n \"\"\"\n return f\"https://download.pytorch.org/whl/{cuda_wheel_suffix(cuda)}\"\n\n\ndef pytorch_install_instructions(cuda_major: Optional[int] = None) -> str:\n \"\"\"\n Generate PyTorch installation instructions.\n\n Args:\n cuda_major: If specified, only show instructions for this CUDA major version.\n Otherwise show all available versions.\n\n Returns:\n Multi-line string with pip install commands\n \"\"\"\n if cuda_major is not None:\n # Filter to matching CUDA major version\n matching = [cuda for cuda in CUDA_AVAILABLE if cuda[0] == cuda_major]\n versions_to_show = matching if matching else CUDA_AVAILABLE\n else:\n versions_to_show = CUDA_AVAILABLE\n\n lines = []\n for cuda in versions_to_show:\n lines.append(f\" # For CUDA {format_version(cuda)}:\")\n lines.append(f\" pip install torch --index-url {pytorch_index_url(cuda)}\")\n return \"\\n\".join(lines)\n\n\ndef llvm_download_url(version: Optional[Tuple[int, ...]] = None) -> str:\n \"\"\"\n Generate LLVM prebuilt binary download URL.\n\n Args:\n version: LLVM version tuple. If None, uses (18, 1, 8) as default.\n\n Returns:\n GitHub release URL for prebuilt binary matching current platform\n\n Raises:\n NotImplementedError: If platform is not supported\n\n Example:\n >>> llvm_download_url((18, 1, 8)) # doctest: +SKIP\n 'https://github.com/llvm/llvm-project/releases/download/llvmorg-18.1.8/clang+llvm-18.1.8-x86_64-linux-gnu-ubuntu-18.04.tar.xz'\n \"\"\"\n if version is None:","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.llvm_download_url","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.llvm_download_url#L205-L247","kind":"function","name":"llvm_download_url","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":205,"end_line":247,"context_start_line":185,"context_end_line":257,"code":" cuda_major: If specified, only show instructions for this CUDA major version.\n Otherwise show all available versions.\n\n Returns:\n Multi-line string with pip install commands\n \"\"\"\n if cuda_major is not None:\n # Filter to matching CUDA major version\n matching = [cuda for cuda in CUDA_AVAILABLE if cuda[0] == cuda_major]\n versions_to_show = matching if matching else CUDA_AVAILABLE\n else:\n versions_to_show = CUDA_AVAILABLE\n\n lines = []\n for cuda in versions_to_show:\n lines.append(f\" # For CUDA {format_version(cuda)}:\")\n lines.append(f\" pip install torch --index-url {pytorch_index_url(cuda)}\")\n return \"\\n\".join(lines)\n\n\ndef llvm_download_url(version: Optional[Tuple[int, ...]] = None) -> str:\n \"\"\"\n Generate LLVM prebuilt binary download URL.\n\n Args:\n version: LLVM version tuple. If None, uses (18, 1, 8) as default.\n\n Returns:\n GitHub release URL for prebuilt binary matching current platform\n\n Raises:\n NotImplementedError: If platform is not supported\n\n Example:\n >>> llvm_download_url((18, 1, 8)) # doctest: +SKIP\n 'https://github.com/llvm/llvm-project/releases/download/llvmorg-18.1.8/clang+llvm-18.1.8-x86_64-linux-gnu-ubuntu-18.04.tar.xz'\n \"\"\"\n if version is None:\n version = (18, 1, 8)\n\n v = format_version(version)\n machine = platform.machine()\n\n if machine == \"x86_64\":\n return (\n f\"https://github.com/llvm/llvm-project/releases/download/\"\n f\"llvmorg-{v}/clang+llvm-{v}-x86_64-linux-gnu-ubuntu-18.04.tar.xz\"\n )\n elif machine == \"aarch64\":\n return (\n f\"https://github.com/llvm/llvm-project/releases/download/\"\n f\"llvmorg-{v}/clang+llvm-{v}-aarch64-linux-gnu.tar.xz\"\n )\n elif machine.startswith(\"arm64\"):\n # 64-bit ARM (macOS)\n return (\n f\"https://github.com/llvm/llvm-project/releases/download/\"\n f\"llvmorg-{v}/clang+llvm-{v}-arm64-apple-macos11.tar.xz\"\n )\n else:\n raise NotImplementedError(\n f\"LLVM prebuilt binaries not available for: {machine}\"\n )\n\n\ndef cuda_toolkit_download_url() -> str:\n \"\"\"\n Return NVIDIA CUDA Toolkit download page URL.\n\n Returns:\n URL to CUDA downloads page\n \"\"\"\n return \"https://developer.nvidia.com/cuda-downloads\"","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.cuda_toolkit_download_url","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.cuda_toolkit_download_url#L250-L257","kind":"function","name":"cuda_toolkit_download_url","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":250,"end_line":257,"context_start_line":230,"context_end_line":257,"code":" f\"https://github.com/llvm/llvm-project/releases/download/\"\n f\"llvmorg-{v}/clang+llvm-{v}-x86_64-linux-gnu-ubuntu-18.04.tar.xz\"\n )\n elif machine == \"aarch64\":\n return (\n f\"https://github.com/llvm/llvm-project/releases/download/\"\n f\"llvmorg-{v}/clang+llvm-{v}-aarch64-linux-gnu.tar.xz\"\n )\n elif machine.startswith(\"arm64\"):\n # 64-bit ARM (macOS)\n return (\n f\"https://github.com/llvm/llvm-project/releases/download/\"\n f\"llvmorg-{v}/clang+llvm-{v}-arm64-apple-macos11.tar.xz\"\n )\n else:\n raise NotImplementedError(\n f\"LLVM prebuilt binaries not available for: {machine}\"\n )\n\n\ndef cuda_toolkit_download_url() -> str:\n \"\"\"\n Return NVIDIA CUDA Toolkit download page URL.\n\n Returns:\n URL to CUDA downloads page\n \"\"\"\n return \"https://developer.nvidia.com/cuda-downloads\"","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.min_str","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.min_str#L101-L105","kind":"function","name":"min_str","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":101,"end_line":105,"context_start_line":81,"context_end_line":125,"code":"\n@dataclass\nclass Requirement:\n \"\"\"\n A version requirement utility class (NOT the source of truth).\n\n NOTE: This is for utility methods only. Actual version requirements come from\n CMake's DependencyRequirements.cmake and are exported via JSON.\n\n Attributes:\n name: Human-readable name (e.g., \"CMake\", \"LLVM\")\n min_version: Minimum required version tuple, or None for \"any version\"\n recommended: Recommended version tuple for download URLs (optional)\n \"\"\"\n\n name: str\n min_version: Optional[Tuple[int, ...]]\n recommended: Optional[Tuple[int, ...]] = None\n\n @property\n def min_str(self) -> str:\n \"\"\"Minimum version as string: '3.18' or 'any'\"\"\"\n if self.min_version is None:\n return \"any\"\n return format_version(self.min_version)\n\n @property\n def min_display(self) -> str:\n \"\"\"Minimum version for display: '3.18+' or 'any version'\"\"\"\n if self.min_version is None:\n return \"any version\"\n return f\"{self.min_str}+\"\n\n @property\n def recommended_str(self) -> str:\n \"\"\"Recommended version as string, falls back to min_str\"\"\"\n if self.recommended is None:\n return self.min_str\n return format_version(self.recommended)\n\n def check(self, detected: Tuple[int, ...]) -> bool:\n \"\"\"\n Check if detected version meets minimum requirement.\n\n Args:","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.min_display","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.min_display#L108-L112","kind":"function","name":"min_display","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":108,"end_line":112,"context_start_line":88,"context_end_line":132,"code":" CMake's DependencyRequirements.cmake and are exported via JSON.\n\n Attributes:\n name: Human-readable name (e.g., \"CMake\", \"LLVM\")\n min_version: Minimum required version tuple, or None for \"any version\"\n recommended: Recommended version tuple for download URLs (optional)\n \"\"\"\n\n name: str\n min_version: Optional[Tuple[int, ...]]\n recommended: Optional[Tuple[int, ...]] = None\n\n @property\n def min_str(self) -> str:\n \"\"\"Minimum version as string: '3.18' or 'any'\"\"\"\n if self.min_version is None:\n return \"any\"\n return format_version(self.min_version)\n\n @property\n def min_display(self) -> str:\n \"\"\"Minimum version for display: '3.18+' or 'any version'\"\"\"\n if self.min_version is None:\n return \"any version\"\n return f\"{self.min_str}+\"\n\n @property\n def recommended_str(self) -> str:\n \"\"\"Recommended version as string, falls back to min_str\"\"\"\n if self.recommended is None:\n return self.min_str\n return format_version(self.recommended)\n\n def check(self, detected: Tuple[int, ...]) -> bool:\n \"\"\"\n Check if detected version meets minimum requirement.\n\n Args:\n detected: Detected version tuple (e.g., from parse_version)\n\n Returns:\n True if detected >= min_version (or min_version is None)\n\n Note:\n Compares only as many parts as min_version specifies.","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.recommended_str","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.recommended_str#L115-L119","kind":"function","name":"recommended_str","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":115,"end_line":119,"context_start_line":95,"context_end_line":139,"code":"\n name: str\n min_version: Optional[Tuple[int, ...]]\n recommended: Optional[Tuple[int, ...]] = None\n\n @property\n def min_str(self) -> str:\n \"\"\"Minimum version as string: '3.18' or 'any'\"\"\"\n if self.min_version is None:\n return \"any\"\n return format_version(self.min_version)\n\n @property\n def min_display(self) -> str:\n \"\"\"Minimum version for display: '3.18+' or 'any version'\"\"\"\n if self.min_version is None:\n return \"any version\"\n return f\"{self.min_str}+\"\n\n @property\n def recommended_str(self) -> str:\n \"\"\"Recommended version as string, falls back to min_str\"\"\"\n if self.recommended is None:\n return self.min_str\n return format_version(self.recommended)\n\n def check(self, detected: Tuple[int, ...]) -> bool:\n \"\"\"\n Check if detected version meets minimum requirement.\n\n Args:\n detected: Detected version tuple (e.g., from parse_version)\n\n Returns:\n True if detected >= min_version (or min_version is None)\n\n Note:\n Compares only as many parts as min_version specifies.\n So (3, 22, 1) >= (3, 18) compares (3, 22) >= (3, 18) -> True\n \"\"\"\n if self.min_version is None:\n return True\n # Compare only as many parts as min_version specifies\n return detected[: len(self.min_version)] >= self.min_version\n","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirement_utils.check","uri":"program://Fuser/function/python.tools.prereqs.requirement_utils.check#L121-L138","kind":"function","name":"check","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":121,"end_line":138,"context_start_line":101,"context_end_line":158,"code":" def min_str(self) -> str:\n \"\"\"Minimum version as string: '3.18' or 'any'\"\"\"\n if self.min_version is None:\n return \"any\"\n return format_version(self.min_version)\n\n @property\n def min_display(self) -> str:\n \"\"\"Minimum version for display: '3.18+' or 'any version'\"\"\"\n if self.min_version is None:\n return \"any version\"\n return f\"{self.min_str}+\"\n\n @property\n def recommended_str(self) -> str:\n \"\"\"Recommended version as string, falls back to min_str\"\"\"\n if self.recommended is None:\n return self.min_str\n return format_version(self.recommended)\n\n def check(self, detected: Tuple[int, ...]) -> bool:\n \"\"\"\n Check if detected version meets minimum requirement.\n\n Args:\n detected: Detected version tuple (e.g., from parse_version)\n\n Returns:\n True if detected >= min_version (or min_version is None)\n\n Note:\n Compares only as many parts as min_version specifies.\n So (3, 22, 1) >= (3, 18) compares (3, 22) >= (3, 18) -> True\n \"\"\"\n if self.min_version is None:\n return True\n # Compare only as many parts as min_version specifies\n return detected[: len(self.min_version)] >= self.min_version\n\n\n# =============================================================================\n# CUDA VERSIONS - For PyTorch wheel URLs\n# =============================================================================\n\n# PyTorch wheel CUDA versions currently available (newest first)\nCUDA_AVAILABLE = [(13, 1), (13, 0), (12, 8)]\n\n\n# =============================================================================\n# URL GENERATORS\n# =============================================================================\n\n\ndef cuda_wheel_suffix(cuda: Tuple[int, int]) -> str:\n \"\"\"\n Convert CUDA version tuple to PyTorch wheel suffix.\n\n Examples:","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.git_submodules","uri":"program://Fuser/module/python.tools.prereqs.requirements.git_submodules#L1-L60","kind":"module","name":"python.tools.prereqs.requirements.git_submodules","path":"python/tools/prereqs/requirements/git_submodules.py","language":"python","start_line":1,"end_line":60,"context_start_line":1,"context_end_line":60,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Git submodules dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass GitSubmodulesRequirement(BooleanRequirement):\n \"\"\"\n Git submodules initialization check.\n\n CMake variables used:\n - GitSubmodules_FOUND: Whether submodules are initialized\n - NVFUSER_REQUIREMENT_GitSubmodules_STATUS: Validation status\n - NVFUSER_REQUIREMENT_GitSubmodules_OPTIONAL: Whether submodules are optional\n\n No version checking - simple pass/fail.\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Git submodules requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Submodule status\"\n found_var = \"GitSubmodules_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_GitSubmodules_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_GitSubmodules_OPTIONAL\"\n location_var = \"NVFUSER_REQUIREMENT_GitSubmodules_LOCATION_VAR\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Git submodules help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"Git Submodules Not Initialized\")\n print()\n print(\n \"Why: nvFuser depends on third-party libraries included as Git submodules.\"\n )\n print()\n print(\"Initialize and update Git submodules:\")\n print()\n print(\" # From the repository root:\")\n print(\" git submodule update --init --recursive\")\n print()\n print(\" # Or if you just cloned:\")\n print(\" git clone --recursive \")\n print()","source_hash":"7407cc39e96d519067a1f528baa9be6e22ef552d0b6cdbb499962fef39853afd","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.git_submodules.GitSubmodulesRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.git_submodules.GitSubmodulesRequirement#L10-L60","kind":"class","name":"GitSubmodulesRequirement","path":"python/tools/prereqs/requirements/git_submodules.py","language":"python","start_line":10,"end_line":60,"context_start_line":1,"context_end_line":60,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Git submodules dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass GitSubmodulesRequirement(BooleanRequirement):\n \"\"\"\n Git submodules initialization check.\n\n CMake variables used:\n - GitSubmodules_FOUND: Whether submodules are initialized\n - NVFUSER_REQUIREMENT_GitSubmodules_STATUS: Validation status\n - NVFUSER_REQUIREMENT_GitSubmodules_OPTIONAL: Whether submodules are optional\n\n No version checking - simple pass/fail.\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Git submodules requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Submodule status\"\n found_var = \"GitSubmodules_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_GitSubmodules_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_GitSubmodules_OPTIONAL\"\n location_var = \"NVFUSER_REQUIREMENT_GitSubmodules_LOCATION_VAR\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Git submodules help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"Git Submodules Not Initialized\")\n print()\n print(\n \"Why: nvFuser depends on third-party libraries included as Git submodules.\"\n )\n print()\n print(\"Initialize and update Git submodules:\")\n print()\n print(\" # From the repository root:\")\n print(\" git submodule update --init --recursive\")\n print()\n print(\" # Or if you just cloned:\")\n print(\" git clone --recursive \")\n print()","source_hash":"7407cc39e96d519067a1f528baa9be6e22ef552d0b6cdbb499962fef39853afd","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.git_submodules.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.git_submodules.__init__#L22-L38","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/git_submodules.py","language":"python","start_line":22,"end_line":38,"context_start_line":2,"context_end_line":58,"code":"# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Git submodules dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass GitSubmodulesRequirement(BooleanRequirement):\n \"\"\"\n Git submodules initialization check.\n\n CMake variables used:\n - GitSubmodules_FOUND: Whether submodules are initialized\n - NVFUSER_REQUIREMENT_GitSubmodules_STATUS: Validation status\n - NVFUSER_REQUIREMENT_GitSubmodules_OPTIONAL: Whether submodules are optional\n\n No version checking - simple pass/fail.\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Git submodules requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Submodule status\"\n found_var = \"GitSubmodules_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_GitSubmodules_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_GitSubmodules_OPTIONAL\"\n location_var = \"NVFUSER_REQUIREMENT_GitSubmodules_LOCATION_VAR\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Git submodules help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"Git Submodules Not Initialized\")\n print()\n print(\n \"Why: nvFuser depends on third-party libraries included as Git submodules.\"\n )\n print()\n print(\"Initialize and update Git submodules:\")\n print()\n print(\" # From the repository root:\")\n print(\" git submodule update --init --recursive\")\n print()\n print(\" # Or if you just cloned:\")","source_hash":"7407cc39e96d519067a1f528baa9be6e22ef552d0b6cdbb499962fef39853afd","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.git_submodules.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.git_submodules.generate_help#L40-L60","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/git_submodules.py","language":"python","start_line":40,"end_line":60,"context_start_line":20,"context_end_line":60,"code":" \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Git submodules requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Submodule status\"\n found_var = \"GitSubmodules_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_GitSubmodules_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_GitSubmodules_OPTIONAL\"\n location_var = \"NVFUSER_REQUIREMENT_GitSubmodules_LOCATION_VAR\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Git submodules help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"Git Submodules Not Initialized\")\n print()\n print(\n \"Why: nvFuser depends on third-party libraries included as Git submodules.\"\n )\n print()\n print(\"Initialize and update Git submodules:\")\n print()\n print(\" # From the repository root:\")\n print(\" git submodule update --init --recursive\")\n print()\n print(\" # Or if you just cloned:\")\n print(\" git clone --recursive \")\n print()","source_hash":"7407cc39e96d519067a1f528baa9be6e22ef552d0b6cdbb499962fef39853afd","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base","uri":"program://Fuser/module/python.tools.prereqs.requirements.base#L1-L274","kind":"module","name":"python.tools.prereqs.requirements.base","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":1,"end_line":274,"context_start_line":1,"context_end_line":274,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nBase classes for requirement types.\n\nThis module provides the foundational classes for all dependency requirements.\nEach requirement knows how to format its status and determine if it represents a failure.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import Optional, Dict\nfrom dataclasses import dataclass\n\nfrom ..colors import colorize\n\n\n@dataclass\nclass RequirementStatus:\n \"\"\"Validation status constants.\"\"\"\n\n SUCCESS = \"SUCCESS\"\n NOT_FOUND = \"NOT_FOUND\"\n INCOMPATIBLE = \"INCOMPATIBLE\"\n\n\nclass Requirement(ABC):\n \"\"\"\n Base class for all requirement types.\n\n All requirements must implement:\n - format_status_line(): Format output for terminal\n - is_failure(): Determine if this represents a build failure\n \"\"\"\n\n def __init__(\n self,\n name: str,\n cmake_vars: Dict,\n found_var: str,\n status_var: str,\n optional_var: str,\n location_var: Optional[str] = None,\n ):\n \"\"\"\n Initialize from CMake variable names.\n\n Args:\n name: Dependency name\n cmake_vars: Dictionary of all CMake variables\n found_var: Name of CMake variable for found status (e.g., \"Python_FOUND\")\n status_var: Name of CMake variable for validation status (e.g., \"Python_STATUS\")\n optional_var: Name of CMake variable for optional flag (e.g., \"NVFUSER_REQUIREMENT_Python_OPTIONAL\")\n location_var: Optional name of CMake variable for location (e.g., \"Python_EXECUTABLE\")\n \"\"\"\n self.name = name\n self.found = self._to_bool(cmake_vars.get(found_var, \"FALSE\"))\n self.status = cmake_vars.get(status_var, \"UNKNOWN\")\n self.optional = self._to_bool(cmake_vars.get(optional_var, \"FALSE\"))\n\n # Look up location if location_var is provided\n self.location = cmake_vars.get(location_var) if location_var else None\n\n @staticmethod\n def _to_bool(value) -> bool:\n \"\"\"Convert CMake boolean string to Python bool.\"\"\"\n if isinstance(value, bool):\n return value\n if isinstance(value, str):\n return value.upper() in (\"TRUE\", \"ON\", \"YES\", \"1\")\n return bool(value)\n\n @abstractmethod\n def format_status_line(self, colors) -> str:\n \"\"\"Format terminal status line for this requirement.\"\"\"\n pass\n\n def is_failure(self) -> bool:\n \"\"\"Check if this requirement represents a failure.\"\"\"\n return not self.optional and self.status != RequirementStatus.SUCCESS\n\n def get_failure_data(self):\n \"\"\"Get data for help text generation.\"\"\"\n # Return a dict compatible with help system\n return {\n \"name\": self.name,\n \"status\": self.status,\n \"found\": self.found,\n \"optional\": self.optional,\n \"location\": self.location,\n }\n\n @abstractmethod\n def generate_help(self, platform_info):\n \"\"\"Generate help text for this requirement when it fails.\n\n Subclasses should override this to provide specific installation instructions.\n \"\"\"\n pass # Default: no help text\n\n\nclass VersionRequirement(Requirement):\n \"\"\"\n Base class for requirements with version checking.\n\n Provides standard version display formatting.\n Subclasses inherit all version comparison logic.\n \"\"\"\n\n def __init__(\n self,\n name: str,\n cmake_vars: Dict,\n found_var: str,\n status_var: str,\n optional_var: str,\n version_found_var: Optional[str] = None,\n version_required_var: Optional[str] = None,\n location_var: Optional[str] = None,\n ):\n \"\"\"\n Initialize version requirement.\n\n Args:\n name: Dependency name\n cmake_vars: Dictionary of all CMake variables\n found_var: Name of CMake variable for found status\n status_var: Name of CMake variable for validation status\n optional_var: Name of CMake variable for optional flag\n version_found_var: Name of CMake variable for detected version (e.g., \"Python_VERSION\")\n version_required_var: Name of CMake variable for minimum required version (e.g., \"NVFUSER_REQUIREMENT_Python_VERSION_MIN\")\n location_var: Optional name of CMake variable for location\n \"\"\"\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n self.version_found = (\n cmake_vars.get(version_found_var) if version_found_var else None\n )\n self.version_required = (\n cmake_vars.get(version_required_var) if version_required_var else None\n )\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format status line with version information.\"\"\"\n if self.status == RequirementStatus.SUCCESS:\n return self._format_success(colors)\n elif self.status == RequirementStatus.NOT_FOUND:\n return self._format_not_found(colors)\n elif self.status == RequirementStatus.INCOMPATIBLE:\n return self._format_incompatible(colors)\n else:\n return colorize(colors.BOLD_RED, f\"[nvFuser] ✗ {self.name} unknown status\")\n\n def _format_success(self, colors) -> str:\n \"\"\"For example:\n Format success: [nvFuser] ✓ Python 3.12.3 >= 3.10 (/usr/bin/python3)\n \"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n # Status symbol and name in white/green with padding\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓ \") + name_padded\n\n # Version info in green\n if self.version_found and self.version_required:\n version_part = colorize(\n colors.GREEN, f\"{self.version_found} >= {self.version_required}\"\n )\n elif self.version_found:\n version_part = colorize(colors.GREEN, self.version_found)\n else:\n version_part = \"\"\n\n # Combine parts\n if version_part:\n main_line = f\"{status_part} {version_part}\"\n else:\n main_line = status_part\n\n # Add location in cyan if available\n if self.location:\n main_line += \" \" + colorize(colors.CYAN, f\"({self.location})\")\n\n return main_line\n\n def _format_not_found(self, colors) -> str:\n \"\"\"Format not found line.\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n\n if self.optional:\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○ \") + name_padded\n if self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.YELLOW,\n f\"Not found (optional, v{self.version_required}+ recommended)\",\n )\n )\n else:\n return (\n status_part + \" \" + colorize(colors.YELLOW, \"Not found (optional)\")\n )\n else:\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n if self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED,\n f\"Not found (requires {self.version_required}+)\",\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"Not found\")\n\n def _format_incompatible(self, colors) -> str:\n \"\"\"Format incompatible: [nvFuser] ✗ Python 3.7.0 < 3.8\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n\n if self.version_found and self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED, f\"{self.version_found} < {self.version_required}\"\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"incompatible\")\n\n\nclass BooleanRequirement(Requirement):\n \"\"\"\n Base class for requirements without version checking.\n\n Simple pass/fail validation (Git submodules, Ninja).\n \"\"\"\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format status line without version information.\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n\n if self.status == RequirementStatus.SUCCESS:\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓ \") + name_padded\n if self.location:\n return status_part + \" \" + colorize(colors.CYAN, f\"({self.location})\")\n return status_part\n elif self.status == RequirementStatus.NOT_FOUND:\n if self.optional:\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○ \") + name_padded\n return (\n status_part + \" \" + colorize(colors.YELLOW, \"Not found (optional)\")\n )\n else:\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n return status_part + \" \" + colorize(colors.BOLD_RED, \"Not found\")\n else:\n return (\n colorize(colors.BOLD_RED, \"[nvFuser] ✗ \")\n + name_padded\n + \" \"\n + colorize(colors.BOLD_RED, \"validation failed\")\n )","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base.RequirementStatus","uri":"program://Fuser/class/python.tools.prereqs.requirements.base.RequirementStatus#L19-L24","kind":"class","name":"RequirementStatus","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":19,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nBase classes for requirement types.\n\nThis module provides the foundational classes for all dependency requirements.\nEach requirement knows how to format its status and determine if it represents a failure.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import Optional, Dict\nfrom dataclasses import dataclass\n\nfrom ..colors import colorize\n\n\n@dataclass\nclass RequirementStatus:\n \"\"\"Validation status constants.\"\"\"\n\n SUCCESS = \"SUCCESS\"\n NOT_FOUND = \"NOT_FOUND\"\n INCOMPATIBLE = \"INCOMPATIBLE\"\n\n\nclass Requirement(ABC):\n \"\"\"\n Base class for all requirement types.\n\n All requirements must implement:\n - format_status_line(): Format output for terminal\n - is_failure(): Determine if this represents a build failure\n \"\"\"\n\n def __init__(\n self,\n name: str,\n cmake_vars: Dict,\n found_var: str,\n status_var: str,\n optional_var: str,\n location_var: Optional[str] = None,\n ):","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base.Requirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.base.Requirement#L27-L99","kind":"class","name":"Requirement","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":27,"end_line":99,"context_start_line":7,"context_end_line":119,"code":"This module provides the foundational classes for all dependency requirements.\nEach requirement knows how to format its status and determine if it represents a failure.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import Optional, Dict\nfrom dataclasses import dataclass\n\nfrom ..colors import colorize\n\n\n@dataclass\nclass RequirementStatus:\n \"\"\"Validation status constants.\"\"\"\n\n SUCCESS = \"SUCCESS\"\n NOT_FOUND = \"NOT_FOUND\"\n INCOMPATIBLE = \"INCOMPATIBLE\"\n\n\nclass Requirement(ABC):\n \"\"\"\n Base class for all requirement types.\n\n All requirements must implement:\n - format_status_line(): Format output for terminal\n - is_failure(): Determine if this represents a build failure\n \"\"\"\n\n def __init__(\n self,\n name: str,\n cmake_vars: Dict,\n found_var: str,\n status_var: str,\n optional_var: str,\n location_var: Optional[str] = None,\n ):\n \"\"\"\n Initialize from CMake variable names.\n\n Args:\n name: Dependency name\n cmake_vars: Dictionary of all CMake variables\n found_var: Name of CMake variable for found status (e.g., \"Python_FOUND\")\n status_var: Name of CMake variable for validation status (e.g., \"Python_STATUS\")\n optional_var: Name of CMake variable for optional flag (e.g., \"NVFUSER_REQUIREMENT_Python_OPTIONAL\")\n location_var: Optional name of CMake variable for location (e.g., \"Python_EXECUTABLE\")\n \"\"\"\n self.name = name\n self.found = self._to_bool(cmake_vars.get(found_var, \"FALSE\"))\n self.status = cmake_vars.get(status_var, \"UNKNOWN\")\n self.optional = self._to_bool(cmake_vars.get(optional_var, \"FALSE\"))\n\n # Look up location if location_var is provided\n self.location = cmake_vars.get(location_var) if location_var else None\n\n @staticmethod\n def _to_bool(value) -> bool:\n \"\"\"Convert CMake boolean string to Python bool.\"\"\"\n if isinstance(value, bool):\n return value\n if isinstance(value, str):\n return value.upper() in (\"TRUE\", \"ON\", \"YES\", \"1\")\n return bool(value)\n\n @abstractmethod\n def format_status_line(self, colors) -> str:\n \"\"\"Format terminal status line for this requirement.\"\"\"\n pass\n\n def is_failure(self) -> bool:\n \"\"\"Check if this requirement represents a failure.\"\"\"\n return not self.optional and self.status != RequirementStatus.SUCCESS\n\n def get_failure_data(self):\n \"\"\"Get data for help text generation.\"\"\"\n # Return a dict compatible with help system\n return {\n \"name\": self.name,\n \"status\": self.status,\n \"found\": self.found,\n \"optional\": self.optional,\n \"location\": self.location,\n }\n\n @abstractmethod\n def generate_help(self, platform_info):\n \"\"\"Generate help text for this requirement when it fails.\n\n Subclasses should override this to provide specific installation instructions.\n \"\"\"\n pass # Default: no help text\n\n\nclass VersionRequirement(Requirement):\n \"\"\"\n Base class for requirements with version checking.\n\n Provides standard version display formatting.\n Subclasses inherit all version comparison logic.\n \"\"\"\n\n def __init__(\n self,\n name: str,\n cmake_vars: Dict,\n found_var: str,\n status_var: str,\n optional_var: str,\n version_found_var: Optional[str] = None,\n version_required_var: Optional[str] = None,\n location_var: Optional[str] = None,","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base.VersionRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.base.VersionRequirement#L102-L238","kind":"class","name":"VersionRequirement","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":102,"end_line":238,"context_start_line":82,"context_end_line":258,"code":" def get_failure_data(self):\n \"\"\"Get data for help text generation.\"\"\"\n # Return a dict compatible with help system\n return {\n \"name\": self.name,\n \"status\": self.status,\n \"found\": self.found,\n \"optional\": self.optional,\n \"location\": self.location,\n }\n\n @abstractmethod\n def generate_help(self, platform_info):\n \"\"\"Generate help text for this requirement when it fails.\n\n Subclasses should override this to provide specific installation instructions.\n \"\"\"\n pass # Default: no help text\n\n\nclass VersionRequirement(Requirement):\n \"\"\"\n Base class for requirements with version checking.\n\n Provides standard version display formatting.\n Subclasses inherit all version comparison logic.\n \"\"\"\n\n def __init__(\n self,\n name: str,\n cmake_vars: Dict,\n found_var: str,\n status_var: str,\n optional_var: str,\n version_found_var: Optional[str] = None,\n version_required_var: Optional[str] = None,\n location_var: Optional[str] = None,\n ):\n \"\"\"\n Initialize version requirement.\n\n Args:\n name: Dependency name\n cmake_vars: Dictionary of all CMake variables\n found_var: Name of CMake variable for found status\n status_var: Name of CMake variable for validation status\n optional_var: Name of CMake variable for optional flag\n version_found_var: Name of CMake variable for detected version (e.g., \"Python_VERSION\")\n version_required_var: Name of CMake variable for minimum required version (e.g., \"NVFUSER_REQUIREMENT_Python_VERSION_MIN\")\n location_var: Optional name of CMake variable for location\n \"\"\"\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n self.version_found = (\n cmake_vars.get(version_found_var) if version_found_var else None\n )\n self.version_required = (\n cmake_vars.get(version_required_var) if version_required_var else None\n )\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format status line with version information.\"\"\"\n if self.status == RequirementStatus.SUCCESS:\n return self._format_success(colors)\n elif self.status == RequirementStatus.NOT_FOUND:\n return self._format_not_found(colors)\n elif self.status == RequirementStatus.INCOMPATIBLE:\n return self._format_incompatible(colors)\n else:\n return colorize(colors.BOLD_RED, f\"[nvFuser] ✗ {self.name} unknown status\")\n\n def _format_success(self, colors) -> str:\n \"\"\"For example:\n Format success: [nvFuser] ✓ Python 3.12.3 >= 3.10 (/usr/bin/python3)\n \"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n # Status symbol and name in white/green with padding\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓ \") + name_padded\n\n # Version info in green\n if self.version_found and self.version_required:\n version_part = colorize(\n colors.GREEN, f\"{self.version_found} >= {self.version_required}\"\n )\n elif self.version_found:\n version_part = colorize(colors.GREEN, self.version_found)\n else:\n version_part = \"\"\n\n # Combine parts\n if version_part:\n main_line = f\"{status_part} {version_part}\"\n else:\n main_line = status_part\n\n # Add location in cyan if available\n if self.location:\n main_line += \" \" + colorize(colors.CYAN, f\"({self.location})\")\n\n return main_line\n\n def _format_not_found(self, colors) -> str:\n \"\"\"Format not found line.\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n\n if self.optional:\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○ \") + name_padded\n if self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.YELLOW,\n f\"Not found (optional, v{self.version_required}+ recommended)\",\n )\n )\n else:\n return (\n status_part + \" \" + colorize(colors.YELLOW, \"Not found (optional)\")\n )\n else:\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n if self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED,\n f\"Not found (requires {self.version_required}+)\",\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"Not found\")\n\n def _format_incompatible(self, colors) -> str:\n \"\"\"Format incompatible: [nvFuser] ✗ Python 3.7.0 < 3.8\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n\n if self.version_found and self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED, f\"{self.version_found} < {self.version_required}\"\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"incompatible\")\n\n\nclass BooleanRequirement(Requirement):\n \"\"\"\n Base class for requirements without version checking.\n\n Simple pass/fail validation (Git submodules, Ninja).\n \"\"\"\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format status line without version information.\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n\n if self.status == RequirementStatus.SUCCESS:\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓ \") + name_padded\n if self.location:\n return status_part + \" \" + colorize(colors.CYAN, f\"({self.location})\")\n return status_part","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base.BooleanRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.base.BooleanRequirement#L241-L274","kind":"class","name":"BooleanRequirement","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":241,"end_line":274,"context_start_line":221,"context_end_line":274,"code":"\n def _format_incompatible(self, colors) -> str:\n \"\"\"Format incompatible: [nvFuser] ✗ Python 3.7.0 < 3.8\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n\n if self.version_found and self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED, f\"{self.version_found} < {self.version_required}\"\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"incompatible\")\n\n\nclass BooleanRequirement(Requirement):\n \"\"\"\n Base class for requirements without version checking.\n\n Simple pass/fail validation (Git submodules, Ninja).\n \"\"\"\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format status line without version information.\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n\n if self.status == RequirementStatus.SUCCESS:\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓ \") + name_padded\n if self.location:\n return status_part + \" \" + colorize(colors.CYAN, f\"({self.location})\")\n return status_part\n elif self.status == RequirementStatus.NOT_FOUND:\n if self.optional:\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○ \") + name_padded\n return (\n status_part + \" \" + colorize(colors.YELLOW, \"Not found (optional)\")\n )\n else:\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n return status_part + \" \" + colorize(colors.BOLD_RED, \"Not found\")\n else:\n return (\n colorize(colors.BOLD_RED, \"[nvFuser] ✗ \")\n + name_padded\n + \" \"\n + colorize(colors.BOLD_RED, \"validation failed\")\n )","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.base.__init__#L110-L142","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":110,"end_line":142,"context_start_line":90,"context_end_line":162,"code":" \"location\": self.location,\n }\n\n @abstractmethod\n def generate_help(self, platform_info):\n \"\"\"Generate help text for this requirement when it fails.\n\n Subclasses should override this to provide specific installation instructions.\n \"\"\"\n pass # Default: no help text\n\n\nclass VersionRequirement(Requirement):\n \"\"\"\n Base class for requirements with version checking.\n\n Provides standard version display formatting.\n Subclasses inherit all version comparison logic.\n \"\"\"\n\n def __init__(\n self,\n name: str,\n cmake_vars: Dict,\n found_var: str,\n status_var: str,\n optional_var: str,\n version_found_var: Optional[str] = None,\n version_required_var: Optional[str] = None,\n location_var: Optional[str] = None,\n ):\n \"\"\"\n Initialize version requirement.\n\n Args:\n name: Dependency name\n cmake_vars: Dictionary of all CMake variables\n found_var: Name of CMake variable for found status\n status_var: Name of CMake variable for validation status\n optional_var: Name of CMake variable for optional flag\n version_found_var: Name of CMake variable for detected version (e.g., \"Python_VERSION\")\n version_required_var: Name of CMake variable for minimum required version (e.g., \"NVFUSER_REQUIREMENT_Python_VERSION_MIN\")\n location_var: Optional name of CMake variable for location\n \"\"\"\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n self.version_found = (\n cmake_vars.get(version_found_var) if version_found_var else None\n )\n self.version_required = (\n cmake_vars.get(version_required_var) if version_required_var else None\n )\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format status line with version information.\"\"\"\n if self.status == RequirementStatus.SUCCESS:\n return self._format_success(colors)\n elif self.status == RequirementStatus.NOT_FOUND:\n return self._format_not_found(colors)\n elif self.status == RequirementStatus.INCOMPATIBLE:\n return self._format_incompatible(colors)\n else:\n return colorize(colors.BOLD_RED, f\"[nvFuser] ✗ {self.name} unknown status\")\n\n def _format_success(self, colors) -> str:\n \"\"\"For example:\n Format success: [nvFuser] ✓ Python 3.12.3 >= 3.10 (/usr/bin/python3)\n \"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n # Status symbol and name in white/green with padding\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base._to_bool","uri":"program://Fuser/function/python.tools.prereqs.requirements.base._to_bool#L65-L71","kind":"function","name":"_to_bool","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":65,"end_line":71,"context_start_line":45,"context_end_line":91,"code":" \"\"\"\n Initialize from CMake variable names.\n\n Args:\n name: Dependency name\n cmake_vars: Dictionary of all CMake variables\n found_var: Name of CMake variable for found status (e.g., \"Python_FOUND\")\n status_var: Name of CMake variable for validation status (e.g., \"Python_STATUS\")\n optional_var: Name of CMake variable for optional flag (e.g., \"NVFUSER_REQUIREMENT_Python_OPTIONAL\")\n location_var: Optional name of CMake variable for location (e.g., \"Python_EXECUTABLE\")\n \"\"\"\n self.name = name\n self.found = self._to_bool(cmake_vars.get(found_var, \"FALSE\"))\n self.status = cmake_vars.get(status_var, \"UNKNOWN\")\n self.optional = self._to_bool(cmake_vars.get(optional_var, \"FALSE\"))\n\n # Look up location if location_var is provided\n self.location = cmake_vars.get(location_var) if location_var else None\n\n @staticmethod\n def _to_bool(value) -> bool:\n \"\"\"Convert CMake boolean string to Python bool.\"\"\"\n if isinstance(value, bool):\n return value\n if isinstance(value, str):\n return value.upper() in (\"TRUE\", \"ON\", \"YES\", \"1\")\n return bool(value)\n\n @abstractmethod\n def format_status_line(self, colors) -> str:\n \"\"\"Format terminal status line for this requirement.\"\"\"\n pass\n\n def is_failure(self) -> bool:\n \"\"\"Check if this requirement represents a failure.\"\"\"\n return not self.optional and self.status != RequirementStatus.SUCCESS\n\n def get_failure_data(self):\n \"\"\"Get data for help text generation.\"\"\"\n # Return a dict compatible with help system\n return {\n \"name\": self.name,\n \"status\": self.status,\n \"found\": self.found,\n \"optional\": self.optional,\n \"location\": self.location,\n }","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base.format_status_line","uri":"program://Fuser/function/python.tools.prereqs.requirements.base.format_status_line#L248-L274","kind":"function","name":"format_status_line","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":248,"end_line":274,"context_start_line":228,"context_end_line":274,"code":"\n if self.version_found and self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED, f\"{self.version_found} < {self.version_required}\"\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"incompatible\")\n\n\nclass BooleanRequirement(Requirement):\n \"\"\"\n Base class for requirements without version checking.\n\n Simple pass/fail validation (Git submodules, Ninja).\n \"\"\"\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format status line without version information.\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n\n if self.status == RequirementStatus.SUCCESS:\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓ \") + name_padded\n if self.location:\n return status_part + \" \" + colorize(colors.CYAN, f\"({self.location})\")\n return status_part\n elif self.status == RequirementStatus.NOT_FOUND:\n if self.optional:\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○ \") + name_padded\n return (\n status_part + \" \" + colorize(colors.YELLOW, \"Not found (optional)\")\n )\n else:\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n return status_part + \" \" + colorize(colors.BOLD_RED, \"Not found\")\n else:\n return (\n colorize(colors.BOLD_RED, \"[nvFuser] ✗ \")\n + name_padded\n + \" \"\n + colorize(colors.BOLD_RED, \"validation failed\")\n )","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base.is_failure","uri":"program://Fuser/function/python.tools.prereqs.requirements.base.is_failure#L78-L80","kind":"function","name":"is_failure","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":78,"end_line":80,"context_start_line":58,"context_end_line":100,"code":" self.status = cmake_vars.get(status_var, \"UNKNOWN\")\n self.optional = self._to_bool(cmake_vars.get(optional_var, \"FALSE\"))\n\n # Look up location if location_var is provided\n self.location = cmake_vars.get(location_var) if location_var else None\n\n @staticmethod\n def _to_bool(value) -> bool:\n \"\"\"Convert CMake boolean string to Python bool.\"\"\"\n if isinstance(value, bool):\n return value\n if isinstance(value, str):\n return value.upper() in (\"TRUE\", \"ON\", \"YES\", \"1\")\n return bool(value)\n\n @abstractmethod\n def format_status_line(self, colors) -> str:\n \"\"\"Format terminal status line for this requirement.\"\"\"\n pass\n\n def is_failure(self) -> bool:\n \"\"\"Check if this requirement represents a failure.\"\"\"\n return not self.optional and self.status != RequirementStatus.SUCCESS\n\n def get_failure_data(self):\n \"\"\"Get data for help text generation.\"\"\"\n # Return a dict compatible with help system\n return {\n \"name\": self.name,\n \"status\": self.status,\n \"found\": self.found,\n \"optional\": self.optional,\n \"location\": self.location,\n }\n\n @abstractmethod\n def generate_help(self, platform_info):\n \"\"\"Generate help text for this requirement when it fails.\n\n Subclasses should override this to provide specific installation instructions.\n \"\"\"\n pass # Default: no help text\n","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base.get_failure_data","uri":"program://Fuser/function/python.tools.prereqs.requirements.base.get_failure_data#L82-L91","kind":"function","name":"get_failure_data","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":82,"end_line":91,"context_start_line":62,"context_end_line":111,"code":" self.location = cmake_vars.get(location_var) if location_var else None\n\n @staticmethod\n def _to_bool(value) -> bool:\n \"\"\"Convert CMake boolean string to Python bool.\"\"\"\n if isinstance(value, bool):\n return value\n if isinstance(value, str):\n return value.upper() in (\"TRUE\", \"ON\", \"YES\", \"1\")\n return bool(value)\n\n @abstractmethod\n def format_status_line(self, colors) -> str:\n \"\"\"Format terminal status line for this requirement.\"\"\"\n pass\n\n def is_failure(self) -> bool:\n \"\"\"Check if this requirement represents a failure.\"\"\"\n return not self.optional and self.status != RequirementStatus.SUCCESS\n\n def get_failure_data(self):\n \"\"\"Get data for help text generation.\"\"\"\n # Return a dict compatible with help system\n return {\n \"name\": self.name,\n \"status\": self.status,\n \"found\": self.found,\n \"optional\": self.optional,\n \"location\": self.location,\n }\n\n @abstractmethod\n def generate_help(self, platform_info):\n \"\"\"Generate help text for this requirement when it fails.\n\n Subclasses should override this to provide specific installation instructions.\n \"\"\"\n pass # Default: no help text\n\n\nclass VersionRequirement(Requirement):\n \"\"\"\n Base class for requirements with version checking.\n\n Provides standard version display formatting.\n Subclasses inherit all version comparison logic.\n \"\"\"\n\n def __init__(\n self,","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.base.generate_help#L94-L99","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":94,"end_line":99,"context_start_line":74,"context_end_line":119,"code":" def format_status_line(self, colors) -> str:\n \"\"\"Format terminal status line for this requirement.\"\"\"\n pass\n\n def is_failure(self) -> bool:\n \"\"\"Check if this requirement represents a failure.\"\"\"\n return not self.optional and self.status != RequirementStatus.SUCCESS\n\n def get_failure_data(self):\n \"\"\"Get data for help text generation.\"\"\"\n # Return a dict compatible with help system\n return {\n \"name\": self.name,\n \"status\": self.status,\n \"found\": self.found,\n \"optional\": self.optional,\n \"location\": self.location,\n }\n\n @abstractmethod\n def generate_help(self, platform_info):\n \"\"\"Generate help text for this requirement when it fails.\n\n Subclasses should override this to provide specific installation instructions.\n \"\"\"\n pass # Default: no help text\n\n\nclass VersionRequirement(Requirement):\n \"\"\"\n Base class for requirements with version checking.\n\n Provides standard version display formatting.\n Subclasses inherit all version comparison logic.\n \"\"\"\n\n def __init__(\n self,\n name: str,\n cmake_vars: Dict,\n found_var: str,\n status_var: str,\n optional_var: str,\n version_found_var: Optional[str] = None,\n version_required_var: Optional[str] = None,\n location_var: Optional[str] = None,","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base._format_success","uri":"program://Fuser/function/python.tools.prereqs.requirements.base._format_success#L155-L185","kind":"function","name":"_format_success","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":155,"end_line":185,"context_start_line":135,"context_end_line":205,"code":" name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n self.version_found = (\n cmake_vars.get(version_found_var) if version_found_var else None\n )\n self.version_required = (\n cmake_vars.get(version_required_var) if version_required_var else None\n )\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format status line with version information.\"\"\"\n if self.status == RequirementStatus.SUCCESS:\n return self._format_success(colors)\n elif self.status == RequirementStatus.NOT_FOUND:\n return self._format_not_found(colors)\n elif self.status == RequirementStatus.INCOMPATIBLE:\n return self._format_incompatible(colors)\n else:\n return colorize(colors.BOLD_RED, f\"[nvFuser] ✗ {self.name} unknown status\")\n\n def _format_success(self, colors) -> str:\n \"\"\"For example:\n Format success: [nvFuser] ✓ Python 3.12.3 >= 3.10 (/usr/bin/python3)\n \"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n # Status symbol and name in white/green with padding\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓ \") + name_padded\n\n # Version info in green\n if self.version_found and self.version_required:\n version_part = colorize(\n colors.GREEN, f\"{self.version_found} >= {self.version_required}\"\n )\n elif self.version_found:\n version_part = colorize(colors.GREEN, self.version_found)\n else:\n version_part = \"\"\n\n # Combine parts\n if version_part:\n main_line = f\"{status_part} {version_part}\"\n else:\n main_line = status_part\n\n # Add location in cyan if available\n if self.location:\n main_line += \" \" + colorize(colors.CYAN, f\"({self.location})\")\n\n return main_line\n\n def _format_not_found(self, colors) -> str:\n \"\"\"Format not found line.\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n\n if self.optional:\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○ \") + name_padded\n if self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.YELLOW,\n f\"Not found (optional, v{self.version_required}+ recommended)\",\n )\n )\n else:\n return (","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base._format_not_found","uri":"program://Fuser/function/python.tools.prereqs.requirements.base._format_not_found#L187-L220","kind":"function","name":"_format_not_found","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":187,"end_line":220,"context_start_line":167,"context_end_line":240,"code":" version_part = colorize(\n colors.GREEN, f\"{self.version_found} >= {self.version_required}\"\n )\n elif self.version_found:\n version_part = colorize(colors.GREEN, self.version_found)\n else:\n version_part = \"\"\n\n # Combine parts\n if version_part:\n main_line = f\"{status_part} {version_part}\"\n else:\n main_line = status_part\n\n # Add location in cyan if available\n if self.location:\n main_line += \" \" + colorize(colors.CYAN, f\"({self.location})\")\n\n return main_line\n\n def _format_not_found(self, colors) -> str:\n \"\"\"Format not found line.\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n\n if self.optional:\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○ \") + name_padded\n if self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.YELLOW,\n f\"Not found (optional, v{self.version_required}+ recommended)\",\n )\n )\n else:\n return (\n status_part + \" \" + colorize(colors.YELLOW, \"Not found (optional)\")\n )\n else:\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n if self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED,\n f\"Not found (requires {self.version_required}+)\",\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"Not found\")\n\n def _format_incompatible(self, colors) -> str:\n \"\"\"Format incompatible: [nvFuser] ✗ Python 3.7.0 < 3.8\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n\n if self.version_found and self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED, f\"{self.version_found} < {self.version_required}\"\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"incompatible\")\n\n","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.base._format_incompatible","uri":"program://Fuser/function/python.tools.prereqs.requirements.base._format_incompatible#L222-L238","kind":"function","name":"_format_incompatible","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":222,"end_line":238,"context_start_line":202,"context_end_line":258,"code":" )\n )\n else:\n return (\n status_part + \" \" + colorize(colors.YELLOW, \"Not found (optional)\")\n )\n else:\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n if self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED,\n f\"Not found (requires {self.version_required}+)\",\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"Not found\")\n\n def _format_incompatible(self, colors) -> str:\n \"\"\"Format incompatible: [nvFuser] ✗ Python 3.7.0 < 3.8\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗ \") + name_padded\n\n if self.version_found and self.version_required:\n return (\n status_part\n + \" \"\n + colorize(\n colors.BOLD_RED, f\"{self.version_found} < {self.version_required}\"\n )\n )\n else:\n return status_part + \" \" + colorize(colors.BOLD_RED, \"incompatible\")\n\n\nclass BooleanRequirement(Requirement):\n \"\"\"\n Base class for requirements without version checking.\n\n Simple pass/fail validation (Git submodules, Ninja).\n \"\"\"\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format status line without version information.\"\"\"\n # Add asterisk for optional requirements\n name_with_marker = f\"{self.name}*\" if self.optional else self.name\n name_padded = f\"{name_with_marker:<15}\" # Left-align with 15 char width\n\n if self.status == RequirementStatus.SUCCESS:\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓ \") + name_padded\n if self.location:\n return status_part + \" \" + colorize(colors.CYAN, f\"({self.location})\")\n return status_part","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.pybind11","uri":"program://Fuser/module/python.tools.prereqs.requirements.pybind11#L1-L68","kind":"module","name":"python.tools.prereqs.requirements.pybind11","path":"python/tools/prereqs/requirements/pybind11.py","language":"python","start_line":1,"end_line":68,"context_start_line":1,"context_end_line":68,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"pybind11 dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass Pybind11Requirement(VersionRequirement):\n \"\"\"\n pybind11 requirement for Python bindings.\n\n CMake variables used:\n - pybind11_FOUND: Whether pybind11 was found\n - pybind11_VERSION: Detected version (e.g., \"3.0.1\")\n - pybind11_DIR: Path to pybind11 CMake config\n - NVFUSER_REQUIREMENT_pybind11_STATUS: Validation status\n - NVFUSER_REQUIREMENT_pybind11_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_pybind11_OPTIONAL: Whether pybind11 is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize pybind11 requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"pybind11\"\n found_var = \"pybind11_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_pybind11_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_pybind11_OPTIONAL\"\n version_found_var = \"pybind11_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_pybind11_VERSION_MIN\"\n location_var = \"pybind11_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate pybind11 installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"pybind11 {version_min}+ Required\")\n print()\n print(\"Why: pybind11 provides Python bindings for nvFuser's C++ code.\")\n print()\n print(f\"Install pybind11 {version_min} or higher:\")\n print()\n print(f\" pip install 'pybind11[global]>={version_min}'\")\n print()\n print(\" Note: The [global] extra provides CMake integration.\")\n print()","source_hash":"b055e2338897dd76460b99d43961101e68f5ca2e45213e45b71a7ffea3ffc2d5","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.pybind11.Pybind11Requirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.pybind11.Pybind11Requirement#L10-L68","kind":"class","name":"Pybind11Requirement","path":"python/tools/prereqs/requirements/pybind11.py","language":"python","start_line":10,"end_line":68,"context_start_line":1,"context_end_line":68,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"pybind11 dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass Pybind11Requirement(VersionRequirement):\n \"\"\"\n pybind11 requirement for Python bindings.\n\n CMake variables used:\n - pybind11_FOUND: Whether pybind11 was found\n - pybind11_VERSION: Detected version (e.g., \"3.0.1\")\n - pybind11_DIR: Path to pybind11 CMake config\n - NVFUSER_REQUIREMENT_pybind11_STATUS: Validation status\n - NVFUSER_REQUIREMENT_pybind11_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_pybind11_OPTIONAL: Whether pybind11 is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize pybind11 requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"pybind11\"\n found_var = \"pybind11_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_pybind11_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_pybind11_OPTIONAL\"\n version_found_var = \"pybind11_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_pybind11_VERSION_MIN\"\n location_var = \"pybind11_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate pybind11 installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"pybind11 {version_min}+ Required\")\n print()\n print(\"Why: pybind11 provides Python bindings for nvFuser's C++ code.\")\n print()\n print(f\"Install pybind11 {version_min} or higher:\")\n print()\n print(f\" pip install 'pybind11[global]>={version_min}'\")\n print()\n print(\" Note: The [global] extra provides CMake integration.\")\n print()","source_hash":"b055e2338897dd76460b99d43961101e68f5ca2e45213e45b71a7ffea3ffc2d5","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.pybind11.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.pybind11.__init__#L23-L48","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/pybind11.py","language":"python","start_line":23,"end_line":48,"context_start_line":3,"context_end_line":68,"code":"# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"pybind11 dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass Pybind11Requirement(VersionRequirement):\n \"\"\"\n pybind11 requirement for Python bindings.\n\n CMake variables used:\n - pybind11_FOUND: Whether pybind11 was found\n - pybind11_VERSION: Detected version (e.g., \"3.0.1\")\n - pybind11_DIR: Path to pybind11 CMake config\n - NVFUSER_REQUIREMENT_pybind11_STATUS: Validation status\n - NVFUSER_REQUIREMENT_pybind11_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_pybind11_OPTIONAL: Whether pybind11 is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize pybind11 requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"pybind11\"\n found_var = \"pybind11_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_pybind11_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_pybind11_OPTIONAL\"\n version_found_var = \"pybind11_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_pybind11_VERSION_MIN\"\n location_var = \"pybind11_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate pybind11 installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"pybind11 {version_min}+ Required\")\n print()\n print(\"Why: pybind11 provides Python bindings for nvFuser's C++ code.\")\n print()\n print(f\"Install pybind11 {version_min} or higher:\")\n print()\n print(f\" pip install 'pybind11[global]>={version_min}'\")\n print()\n print(\" Note: The [global] extra provides CMake integration.\")\n print()","source_hash":"b055e2338897dd76460b99d43961101e68f5ca2e45213e45b71a7ffea3ffc2d5","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.pybind11.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.pybind11.generate_help#L50-L68","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/pybind11.py","language":"python","start_line":50,"end_line":68,"context_start_line":30,"context_end_line":68,"code":" # Define dependency name and CMake variable names for this requirement\n name = \"pybind11\"\n found_var = \"pybind11_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_pybind11_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_pybind11_OPTIONAL\"\n version_found_var = \"pybind11_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_pybind11_VERSION_MIN\"\n location_var = \"pybind11_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate pybind11 installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"pybind11 {version_min}+ Required\")\n print()\n print(\"Why: pybind11 provides Python bindings for nvFuser's C++ code.\")\n print()\n print(f\"Install pybind11 {version_min} or higher:\")\n print()\n print(f\" pip install 'pybind11[global]>={version_min}'\")\n print()\n print(\" Note: The [global] extra provides CMake integration.\")\n print()","source_hash":"b055e2338897dd76460b99d43961101e68f5ca2e45213e45b71a7ffea3ffc2d5","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.cuda_toolkit","uri":"program://Fuser/module/python.tools.prereqs.requirements.cuda_toolkit#L1-L73","kind":"module","name":"python.tools.prereqs.requirements.cuda_toolkit","path":"python/tools/prereqs/requirements/cuda_toolkit.py","language":"python","start_line":1,"end_line":73,"context_start_line":1,"context_end_line":73,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"CUDA Toolkit dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass CUDAToolkitRequirement(VersionRequirement):\n \"\"\"\n NVIDIA CUDA Toolkit requirement.\n\n CMake variables used:\n - CUDAToolkit_FOUND: Whether CUDA was found\n - CUDAToolkit_VERSION: Detected version (e.g., \"13.1.80\")\n - CUDAToolkit_ROOT: Path to CUDA installation\n - NVFUSER_REQUIREMENT_CUDAToolkit_STATUS: Validation status\n - NVFUSER_REQUIREMENT_CUDAToolkit_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_CUDAToolkit_OPTIONAL: Whether CUDA is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize CUDAToolkit requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"CUDAToolkit\"\n found_var = \"CUDAToolkit_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_OPTIONAL\"\n version_found_var = \"CUDAToolkit_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_VERSION_MIN\"\n location_var = \"CUDAToolkit_ROOT\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate CUDA Toolkit installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"CUDA Toolkit {version_min}+ Required\")\n print()\n print(\"Why: nvFuser needs the CUDA compiler (nvcc) for GPU kernel generation.\")\n print()\n print(f\"Install CUDA Toolkit {version_min} or higher:\")\n print()\n print(\" Download from NVIDIA:\")\n print()\n print(\" https://developer.nvidia.com/cuda-downloads\")\n print()\n print(\" After installation, ensure CUDA is in your PATH:\")\n print()\n print(\" export PATH=/usr/local/cuda/bin:$PATH\")\n print(\" export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH\")\n print()","source_hash":"93fadc51b743e38bdc6ddc54e2f61a8b05ecccc6ea6ed4104452e0dde39c47a6","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.cuda_toolkit.CUDAToolkitRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.cuda_toolkit.CUDAToolkitRequirement#L10-L73","kind":"class","name":"CUDAToolkitRequirement","path":"python/tools/prereqs/requirements/cuda_toolkit.py","language":"python","start_line":10,"end_line":73,"context_start_line":1,"context_end_line":73,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"CUDA Toolkit dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass CUDAToolkitRequirement(VersionRequirement):\n \"\"\"\n NVIDIA CUDA Toolkit requirement.\n\n CMake variables used:\n - CUDAToolkit_FOUND: Whether CUDA was found\n - CUDAToolkit_VERSION: Detected version (e.g., \"13.1.80\")\n - CUDAToolkit_ROOT: Path to CUDA installation\n - NVFUSER_REQUIREMENT_CUDAToolkit_STATUS: Validation status\n - NVFUSER_REQUIREMENT_CUDAToolkit_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_CUDAToolkit_OPTIONAL: Whether CUDA is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize CUDAToolkit requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"CUDAToolkit\"\n found_var = \"CUDAToolkit_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_OPTIONAL\"\n version_found_var = \"CUDAToolkit_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_VERSION_MIN\"\n location_var = \"CUDAToolkit_ROOT\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate CUDA Toolkit installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"CUDA Toolkit {version_min}+ Required\")\n print()\n print(\"Why: nvFuser needs the CUDA compiler (nvcc) for GPU kernel generation.\")\n print()\n print(f\"Install CUDA Toolkit {version_min} or higher:\")\n print()\n print(\" Download from NVIDIA:\")\n print()\n print(\" https://developer.nvidia.com/cuda-downloads\")\n print()\n print(\" After installation, ensure CUDA is in your PATH:\")\n print()\n print(\" export PATH=/usr/local/cuda/bin:$PATH\")\n print(\" export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH\")\n print()","source_hash":"93fadc51b743e38bdc6ddc54e2f61a8b05ecccc6ea6ed4104452e0dde39c47a6","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.cuda_toolkit.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.cuda_toolkit.__init__#L23-L48","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/cuda_toolkit.py","language":"python","start_line":23,"end_line":48,"context_start_line":3,"context_end_line":68,"code":"# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"CUDA Toolkit dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass CUDAToolkitRequirement(VersionRequirement):\n \"\"\"\n NVIDIA CUDA Toolkit requirement.\n\n CMake variables used:\n - CUDAToolkit_FOUND: Whether CUDA was found\n - CUDAToolkit_VERSION: Detected version (e.g., \"13.1.80\")\n - CUDAToolkit_ROOT: Path to CUDA installation\n - NVFUSER_REQUIREMENT_CUDAToolkit_STATUS: Validation status\n - NVFUSER_REQUIREMENT_CUDAToolkit_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_CUDAToolkit_OPTIONAL: Whether CUDA is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize CUDAToolkit requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"CUDAToolkit\"\n found_var = \"CUDAToolkit_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_OPTIONAL\"\n version_found_var = \"CUDAToolkit_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_VERSION_MIN\"\n location_var = \"CUDAToolkit_ROOT\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate CUDA Toolkit installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"CUDA Toolkit {version_min}+ Required\")\n print()\n print(\"Why: nvFuser needs the CUDA compiler (nvcc) for GPU kernel generation.\")\n print()\n print(f\"Install CUDA Toolkit {version_min} or higher:\")\n print()\n print(\" Download from NVIDIA:\")\n print()\n print(\" https://developer.nvidia.com/cuda-downloads\")\n print()","source_hash":"93fadc51b743e38bdc6ddc54e2f61a8b05ecccc6ea6ed4104452e0dde39c47a6","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.cuda_toolkit.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.cuda_toolkit.generate_help#L50-L73","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/cuda_toolkit.py","language":"python","start_line":50,"end_line":73,"context_start_line":30,"context_end_line":73,"code":" # Define dependency name and CMake variable names for this requirement\n name = \"CUDAToolkit\"\n found_var = \"CUDAToolkit_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_OPTIONAL\"\n version_found_var = \"CUDAToolkit_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_CUDAToolkit_VERSION_MIN\"\n location_var = \"CUDAToolkit_ROOT\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate CUDA Toolkit installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"CUDA Toolkit {version_min}+ Required\")\n print()\n print(\"Why: nvFuser needs the CUDA compiler (nvcc) for GPU kernel generation.\")\n print()\n print(f\"Install CUDA Toolkit {version_min} or higher:\")\n print()\n print(\" Download from NVIDIA:\")\n print()\n print(\" https://developer.nvidia.com/cuda-downloads\")\n print()\n print(\" After installation, ensure CUDA is in your PATH:\")\n print()\n print(\" export PATH=/usr/local/cuda/bin:$PATH\")\n print(\" export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH\")\n print()","source_hash":"93fadc51b743e38bdc6ddc54e2f61a8b05ecccc6ea6ed4104452e0dde39c47a6","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.llvm","uri":"program://Fuser/module/python.tools.prereqs.requirements.llvm#L1-L119","kind":"module","name":"python.tools.prereqs.requirements.llvm","path":"python/tools/prereqs/requirements/llvm.py","language":"python","start_line":1,"end_line":119,"context_start_line":1,"context_end_line":119,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"LLVM dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass LLVMRequirement(VersionRequirement):\n \"\"\"\n LLVM requirement for Host IR JIT compilation.\n\n CMake variables used:\n - LLVM_FOUND: Whether LLVM was found\n - LLVM_VERSION: Detected version (e.g., \"18.1.3\")\n - LLVM_DIR: Path to LLVM CMake config\n - NVFUSER_REQUIREMENT_LLVM_STATUS: Validation status\n - NVFUSER_REQUIREMENT_LLVM_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_LLVM_OPTIONAL: Whether LLVM is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize LLVM requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"LLVM\"\n found_var = \"LLVM_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_LLVM_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_LLVM_OPTIONAL\"\n version_found_var = \"LLVM_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_LLVM_VERSION_MIN\"\n location_var = \"LLVM_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate LLVM installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n import re\n\n version_min = self.version_required\n\n # Parse version to recommend a specific patch version\n try:\n clean = re.match(r\"^[\\d.]+\", version_min.strip())\n if clean:\n parts = clean.group().rstrip(\".\").split(\".\")\n version_parts = tuple(int(p) for p in parts if p)\n if len(version_parts) >= 2:\n recommended = f\"{version_parts[0]}.{version_parts[1]}.8\"\n major_version = version_parts[0]\n else:\n recommended = f\"{version_parts[0]}.1.8\"\n major_version = version_parts[0]\n else:\n recommended = \"18.1.8\"\n major_version = 18\n except Exception:\n recommended = \"18.1.8\"\n major_version = 18\n\n print(f\"LLVM {version_min}+ Required\")\n print()\n print(\"Why: nvFuser uses LLVM for runtime Host IR JIT compilation.\")\n print()\n print(f\"Install LLVM {recommended} (recommended):\")\n print()\n\n print(\" Option 1: Prebuilt binaries (recommended, no sudo needed):\")\n print()\n print(\n f\" wget https://github.com/llvm/llvm-project/releases/download/llvmorg-{recommended}/clang+llvm-{recommended}-x86_64-linux-gnu-ubuntu-18.04.tar.xz\"\n )\n print(f\" tar -xf clang+llvm-{recommended}-*.tar.xz\")\n print(f\" mv clang+llvm-{recommended}-* ~/.llvm/{recommended}\")\n print()\n print(\" # Add to PATH:\")\n print(f\" export PATH=$HOME/.llvm/{recommended}/bin:$PATH\")\n print()\n\n print(\" Option 2: System package manager:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" # Ubuntu/Debian (LLVM APT repository):\")\n print(\" wget https://apt.llvm.org/llvm.sh\")\n print(\" chmod +x llvm.sh\")\n print(f\" sudo ./llvm.sh {major_version}\")\n print()\n else:\n print(\" # Check your distribution's package manager\")\n print()\n elif os_type == \"Darwin\":\n print(f\" brew install llvm@{major_version}\")\n print()\n print(\" # Add to PATH:\")\n print(f\" export PATH=/opt/homebrew/opt/llvm@{major_version}/bin:$PATH\")\n print()","source_hash":"e011976ebb5656717c00005ef4f6564589df2f99b35b0ac06b7543c6fad2279d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.llvm.LLVMRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.llvm.LLVMRequirement#L10-L119","kind":"class","name":"LLVMRequirement","path":"python/tools/prereqs/requirements/llvm.py","language":"python","start_line":10,"end_line":119,"context_start_line":1,"context_end_line":119,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"LLVM dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass LLVMRequirement(VersionRequirement):\n \"\"\"\n LLVM requirement for Host IR JIT compilation.\n\n CMake variables used:\n - LLVM_FOUND: Whether LLVM was found\n - LLVM_VERSION: Detected version (e.g., \"18.1.3\")\n - LLVM_DIR: Path to LLVM CMake config\n - NVFUSER_REQUIREMENT_LLVM_STATUS: Validation status\n - NVFUSER_REQUIREMENT_LLVM_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_LLVM_OPTIONAL: Whether LLVM is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize LLVM requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"LLVM\"\n found_var = \"LLVM_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_LLVM_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_LLVM_OPTIONAL\"\n version_found_var = \"LLVM_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_LLVM_VERSION_MIN\"\n location_var = \"LLVM_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate LLVM installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n import re\n\n version_min = self.version_required\n\n # Parse version to recommend a specific patch version\n try:\n clean = re.match(r\"^[\\d.]+\", version_min.strip())\n if clean:\n parts = clean.group().rstrip(\".\").split(\".\")\n version_parts = tuple(int(p) for p in parts if p)\n if len(version_parts) >= 2:\n recommended = f\"{version_parts[0]}.{version_parts[1]}.8\"\n major_version = version_parts[0]\n else:\n recommended = f\"{version_parts[0]}.1.8\"\n major_version = version_parts[0]\n else:\n recommended = \"18.1.8\"\n major_version = 18\n except Exception:\n recommended = \"18.1.8\"\n major_version = 18\n\n print(f\"LLVM {version_min}+ Required\")\n print()\n print(\"Why: nvFuser uses LLVM for runtime Host IR JIT compilation.\")\n print()\n print(f\"Install LLVM {recommended} (recommended):\")\n print()\n\n print(\" Option 1: Prebuilt binaries (recommended, no sudo needed):\")\n print()\n print(\n f\" wget https://github.com/llvm/llvm-project/releases/download/llvmorg-{recommended}/clang+llvm-{recommended}-x86_64-linux-gnu-ubuntu-18.04.tar.xz\"\n )\n print(f\" tar -xf clang+llvm-{recommended}-*.tar.xz\")\n print(f\" mv clang+llvm-{recommended}-* ~/.llvm/{recommended}\")\n print()\n print(\" # Add to PATH:\")\n print(f\" export PATH=$HOME/.llvm/{recommended}/bin:$PATH\")\n print()\n\n print(\" Option 2: System package manager:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" # Ubuntu/Debian (LLVM APT repository):\")\n print(\" wget https://apt.llvm.org/llvm.sh\")\n print(\" chmod +x llvm.sh\")\n print(f\" sudo ./llvm.sh {major_version}\")\n print()\n else:\n print(\" # Check your distribution's package manager\")\n print()\n elif os_type == \"Darwin\":\n print(f\" brew install llvm@{major_version}\")\n print()\n print(\" # Add to PATH:\")\n print(f\" export PATH=/opt/homebrew/opt/llvm@{major_version}/bin:$PATH\")\n print()","source_hash":"e011976ebb5656717c00005ef4f6564589df2f99b35b0ac06b7543c6fad2279d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.llvm.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.llvm.__init__#L23-L48","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/llvm.py","language":"python","start_line":23,"end_line":48,"context_start_line":3,"context_end_line":68,"code":"# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"LLVM dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass LLVMRequirement(VersionRequirement):\n \"\"\"\n LLVM requirement for Host IR JIT compilation.\n\n CMake variables used:\n - LLVM_FOUND: Whether LLVM was found\n - LLVM_VERSION: Detected version (e.g., \"18.1.3\")\n - LLVM_DIR: Path to LLVM CMake config\n - NVFUSER_REQUIREMENT_LLVM_STATUS: Validation status\n - NVFUSER_REQUIREMENT_LLVM_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_LLVM_OPTIONAL: Whether LLVM is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize LLVM requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"LLVM\"\n found_var = \"LLVM_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_LLVM_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_LLVM_OPTIONAL\"\n version_found_var = \"LLVM_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_LLVM_VERSION_MIN\"\n location_var = \"LLVM_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate LLVM installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n import re\n\n version_min = self.version_required\n\n # Parse version to recommend a specific patch version\n try:\n clean = re.match(r\"^[\\d.]+\", version_min.strip())\n if clean:\n parts = clean.group().rstrip(\".\").split(\".\")\n version_parts = tuple(int(p) for p in parts if p)\n if len(version_parts) >= 2:\n recommended = f\"{version_parts[0]}.{version_parts[1]}.8\"","source_hash":"e011976ebb5656717c00005ef4f6564589df2f99b35b0ac06b7543c6fad2279d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.llvm.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.llvm.generate_help#L50-L119","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/llvm.py","language":"python","start_line":50,"end_line":119,"context_start_line":30,"context_end_line":119,"code":" # Define dependency name and CMake variable names for this requirement\n name = \"LLVM\"\n found_var = \"LLVM_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_LLVM_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_LLVM_OPTIONAL\"\n version_found_var = \"LLVM_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_LLVM_VERSION_MIN\"\n location_var = \"LLVM_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate LLVM installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n import re\n\n version_min = self.version_required\n\n # Parse version to recommend a specific patch version\n try:\n clean = re.match(r\"^[\\d.]+\", version_min.strip())\n if clean:\n parts = clean.group().rstrip(\".\").split(\".\")\n version_parts = tuple(int(p) for p in parts if p)\n if len(version_parts) >= 2:\n recommended = f\"{version_parts[0]}.{version_parts[1]}.8\"\n major_version = version_parts[0]\n else:\n recommended = f\"{version_parts[0]}.1.8\"\n major_version = version_parts[0]\n else:\n recommended = \"18.1.8\"\n major_version = 18\n except Exception:\n recommended = \"18.1.8\"\n major_version = 18\n\n print(f\"LLVM {version_min}+ Required\")\n print()\n print(\"Why: nvFuser uses LLVM for runtime Host IR JIT compilation.\")\n print()\n print(f\"Install LLVM {recommended} (recommended):\")\n print()\n\n print(\" Option 1: Prebuilt binaries (recommended, no sudo needed):\")\n print()\n print(\n f\" wget https://github.com/llvm/llvm-project/releases/download/llvmorg-{recommended}/clang+llvm-{recommended}-x86_64-linux-gnu-ubuntu-18.04.tar.xz\"\n )\n print(f\" tar -xf clang+llvm-{recommended}-*.tar.xz\")\n print(f\" mv clang+llvm-{recommended}-* ~/.llvm/{recommended}\")\n print()\n print(\" # Add to PATH:\")\n print(f\" export PATH=$HOME/.llvm/{recommended}/bin:$PATH\")\n print()\n\n print(\" Option 2: System package manager:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" # Ubuntu/Debian (LLVM APT repository):\")\n print(\" wget https://apt.llvm.org/llvm.sh\")\n print(\" chmod +x llvm.sh\")\n print(f\" sudo ./llvm.sh {major_version}\")\n print()\n else:\n print(\" # Check your distribution's package manager\")\n print()\n elif os_type == \"Darwin\":\n print(f\" brew install llvm@{major_version}\")\n print()\n print(\" # Add to PATH:\")\n print(f\" export PATH=/opt/homebrew/opt/llvm@{major_version}/bin:$PATH\")\n print()","source_hash":"e011976ebb5656717c00005ef4f6564589df2f99b35b0ac06b7543c6fad2279d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.compiler","uri":"program://Fuser/module/python.tools.prereqs.requirements.compiler#L1-L136","kind":"module","name":"python.tools.prereqs.requirements.compiler","path":"python/tools/prereqs/requirements/compiler.py","language":"python","start_line":1,"end_line":136,"context_start_line":1,"context_end_line":136,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Compiler dependency requirement (GNU/Clang).\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass CompilerRequirement(VersionRequirement):\n \"\"\"\n C++ compiler requirement with name mapping.\n\n CMake variables used:\n - CMAKE_CXX_COMPILER_ID: Compiler name (GNU or Clang)\n - Compiler_FOUND: Whether compiler is available (always TRUE)\n - CMAKE_CXX_COMPILER_VERSION: Detected compiler version\n - CMAKE_CXX_COMPILER: Path to compiler executable\n - NVFUSER_REQUIREMENT_Compiler_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Compiler_VERSION_MIN: Minimum required version (set based on compiler ID)\n - NVFUSER_REQUIREMENT_Compiler_OPTIONAL: Whether compiler is optional\n - NVFUSER_REQUIREMENT_GNU_VERSION_MIN: Minimum GNU version (from DependencyRequirements.cmake)\n - NVFUSER_REQUIREMENT_Clang_VERSION_MIN: Minimum Clang version (from DependencyRequirements.cmake)\n\n Note: CMake exports \"GNU\" or \"Clang\" as the name, but variables are prefixed with \"Compiler_\"\n\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize compiler requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Extract compiler name from CMake (GNU or Clang)\n name = cmake_vars.get(\"CMAKE_CXX_COMPILER_ID\", \"Unknown\")\n\n # Compiler uses \"Compiler_\" prefix for all variables, regardless of actual name\n found_var = \"Compiler_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Compiler_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Compiler_OPTIONAL\"\n version_found_var = \"CMAKE_CXX_COMPILER_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Compiler_VERSION_MIN\"\n location_var = \"CMAKE_CXX_COMPILER\"\n\n self.gnu_min_version = cmake_vars.get(\"NVFUSER_REQUIREMENT_GNU_VERSION_MIN\")\n self.clang_min_version = cmake_vars.get(\"NVFUSER_REQUIREMENT_Clang_VERSION_MIN\")\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate compiler installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n # Use the version requirement that was set during initialization\n version_min = self.version_required\n\n print(f\"{self.name} {version_min}+ Required\")\n print()\n print(\"Why: nvFuser requires a modern C++ compiler with C++20 support,\")\n print(\" including the header.\")\n print()\n print(f\"Install {self.name} {version_min} or higher:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if self.name == \"GNU\":\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: Ubuntu PPA (recommended):\")\n print()\n print(\" sudo add-apt-repository ppa:ubuntu-toolchain-r/test\")\n print(\" sudo apt update\")\n print(f\" sudo apt install gcc-{version_min} g++-{version_min}\")\n print()\n print(\" # Set as default:\")\n print(\n f\" sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-{version_min} 100\"\n )\n print(\n f\" sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-{version_min} 100\"\n )\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(\" # Example for RHEL/CentOS:\")\n print(f\" # sudo yum install gcc-toolset-{version_min}\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" On macOS, use Clang instead:\")\n print()\n print(\" # Xcode Command Line Tools (includes Clang):\")\n print(\" xcode-select --install\")\n print()\n\n elif self.name == \"Clang\":\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: LLVM APT repository:\")\n print()\n print(\" wget https://apt.llvm.org/llvm.sh\")\n print(\" chmod +x llvm.sh\")\n print(f\" sudo ./llvm.sh {version_min}\")\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(f\" # Check your distribution for clang-{version_min}\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" Option 1: Xcode Command Line Tools:\")\n print()\n print(\" xcode-select --install\")\n print()\n\n print(\" Option 2: Build from source:\")\n print()\n print(\" # See compiler documentation for build instructions\")\n print()","source_hash":"a1df35850a37ef58743d1b4419541a76766ba229aecbe8cd85b30f4e3d6355eb","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.compiler.CompilerRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.compiler.CompilerRequirement#L10-L136","kind":"class","name":"CompilerRequirement","path":"python/tools/prereqs/requirements/compiler.py","language":"python","start_line":10,"end_line":136,"context_start_line":1,"context_end_line":136,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Compiler dependency requirement (GNU/Clang).\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass CompilerRequirement(VersionRequirement):\n \"\"\"\n C++ compiler requirement with name mapping.\n\n CMake variables used:\n - CMAKE_CXX_COMPILER_ID: Compiler name (GNU or Clang)\n - Compiler_FOUND: Whether compiler is available (always TRUE)\n - CMAKE_CXX_COMPILER_VERSION: Detected compiler version\n - CMAKE_CXX_COMPILER: Path to compiler executable\n - NVFUSER_REQUIREMENT_Compiler_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Compiler_VERSION_MIN: Minimum required version (set based on compiler ID)\n - NVFUSER_REQUIREMENT_Compiler_OPTIONAL: Whether compiler is optional\n - NVFUSER_REQUIREMENT_GNU_VERSION_MIN: Minimum GNU version (from DependencyRequirements.cmake)\n - NVFUSER_REQUIREMENT_Clang_VERSION_MIN: Minimum Clang version (from DependencyRequirements.cmake)\n\n Note: CMake exports \"GNU\" or \"Clang\" as the name, but variables are prefixed with \"Compiler_\"\n\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize compiler requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Extract compiler name from CMake (GNU or Clang)\n name = cmake_vars.get(\"CMAKE_CXX_COMPILER_ID\", \"Unknown\")\n\n # Compiler uses \"Compiler_\" prefix for all variables, regardless of actual name\n found_var = \"Compiler_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Compiler_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Compiler_OPTIONAL\"\n version_found_var = \"CMAKE_CXX_COMPILER_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Compiler_VERSION_MIN\"\n location_var = \"CMAKE_CXX_COMPILER\"\n\n self.gnu_min_version = cmake_vars.get(\"NVFUSER_REQUIREMENT_GNU_VERSION_MIN\")\n self.clang_min_version = cmake_vars.get(\"NVFUSER_REQUIREMENT_Clang_VERSION_MIN\")\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate compiler installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n # Use the version requirement that was set during initialization\n version_min = self.version_required\n\n print(f\"{self.name} {version_min}+ Required\")\n print()\n print(\"Why: nvFuser requires a modern C++ compiler with C++20 support,\")\n print(\" including the header.\")\n print()\n print(f\"Install {self.name} {version_min} or higher:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if self.name == \"GNU\":\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: Ubuntu PPA (recommended):\")\n print()\n print(\" sudo add-apt-repository ppa:ubuntu-toolchain-r/test\")\n print(\" sudo apt update\")\n print(f\" sudo apt install gcc-{version_min} g++-{version_min}\")\n print()\n print(\" # Set as default:\")\n print(\n f\" sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-{version_min} 100\"\n )\n print(\n f\" sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-{version_min} 100\"\n )\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(\" # Example for RHEL/CentOS:\")\n print(f\" # sudo yum install gcc-toolset-{version_min}\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" On macOS, use Clang instead:\")\n print()\n print(\" # Xcode Command Line Tools (includes Clang):\")\n print(\" xcode-select --install\")\n print()\n\n elif self.name == \"Clang\":\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: LLVM APT repository:\")\n print()\n print(\" wget https://apt.llvm.org/llvm.sh\")\n print(\" chmod +x llvm.sh\")\n print(f\" sudo ./llvm.sh {version_min}\")\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(f\" # Check your distribution for clang-{version_min}\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" Option 1: Xcode Command Line Tools:\")\n print()\n print(\" xcode-select --install\")\n print()\n\n print(\" Option 2: Build from source:\")\n print()\n print(\" # See compiler documentation for build instructions\")\n print()","source_hash":"a1df35850a37ef58743d1b4419541a76766ba229aecbe8cd85b30f4e3d6355eb","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.compiler.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.compiler.__init__#L29-L59","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/compiler.py","language":"python","start_line":29,"end_line":59,"context_start_line":9,"context_end_line":79,"code":"\nclass CompilerRequirement(VersionRequirement):\n \"\"\"\n C++ compiler requirement with name mapping.\n\n CMake variables used:\n - CMAKE_CXX_COMPILER_ID: Compiler name (GNU or Clang)\n - Compiler_FOUND: Whether compiler is available (always TRUE)\n - CMAKE_CXX_COMPILER_VERSION: Detected compiler version\n - CMAKE_CXX_COMPILER: Path to compiler executable\n - NVFUSER_REQUIREMENT_Compiler_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Compiler_VERSION_MIN: Minimum required version (set based on compiler ID)\n - NVFUSER_REQUIREMENT_Compiler_OPTIONAL: Whether compiler is optional\n - NVFUSER_REQUIREMENT_GNU_VERSION_MIN: Minimum GNU version (from DependencyRequirements.cmake)\n - NVFUSER_REQUIREMENT_Clang_VERSION_MIN: Minimum Clang version (from DependencyRequirements.cmake)\n\n Note: CMake exports \"GNU\" or \"Clang\" as the name, but variables are prefixed with \"Compiler_\"\n\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize compiler requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Extract compiler name from CMake (GNU or Clang)\n name = cmake_vars.get(\"CMAKE_CXX_COMPILER_ID\", \"Unknown\")\n\n # Compiler uses \"Compiler_\" prefix for all variables, regardless of actual name\n found_var = \"Compiler_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Compiler_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Compiler_OPTIONAL\"\n version_found_var = \"CMAKE_CXX_COMPILER_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Compiler_VERSION_MIN\"\n location_var = \"CMAKE_CXX_COMPILER\"\n\n self.gnu_min_version = cmake_vars.get(\"NVFUSER_REQUIREMENT_GNU_VERSION_MIN\")\n self.clang_min_version = cmake_vars.get(\"NVFUSER_REQUIREMENT_Clang_VERSION_MIN\")\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate compiler installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n # Use the version requirement that was set during initialization\n version_min = self.version_required\n\n print(f\"{self.name} {version_min}+ Required\")\n print()\n print(\"Why: nvFuser requires a modern C++ compiler with C++20 support,\")\n print(\" including the header.\")\n print()\n print(f\"Install {self.name} {version_min} or higher:\")\n print()\n\n os_type = platform_info[\"os\"]","source_hash":"a1df35850a37ef58743d1b4419541a76766ba229aecbe8cd85b30f4e3d6355eb","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.compiler.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.compiler.generate_help#L61-L136","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/compiler.py","language":"python","start_line":61,"end_line":136,"context_start_line":41,"context_end_line":136,"code":" status_var = \"NVFUSER_REQUIREMENT_Compiler_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Compiler_OPTIONAL\"\n version_found_var = \"CMAKE_CXX_COMPILER_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Compiler_VERSION_MIN\"\n location_var = \"CMAKE_CXX_COMPILER\"\n\n self.gnu_min_version = cmake_vars.get(\"NVFUSER_REQUIREMENT_GNU_VERSION_MIN\")\n self.clang_min_version = cmake_vars.get(\"NVFUSER_REQUIREMENT_Clang_VERSION_MIN\")\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate compiler installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n # Use the version requirement that was set during initialization\n version_min = self.version_required\n\n print(f\"{self.name} {version_min}+ Required\")\n print()\n print(\"Why: nvFuser requires a modern C++ compiler with C++20 support,\")\n print(\" including the header.\")\n print()\n print(f\"Install {self.name} {version_min} or higher:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if self.name == \"GNU\":\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: Ubuntu PPA (recommended):\")\n print()\n print(\" sudo add-apt-repository ppa:ubuntu-toolchain-r/test\")\n print(\" sudo apt update\")\n print(f\" sudo apt install gcc-{version_min} g++-{version_min}\")\n print()\n print(\" # Set as default:\")\n print(\n f\" sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-{version_min} 100\"\n )\n print(\n f\" sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-{version_min} 100\"\n )\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(\" # Example for RHEL/CentOS:\")\n print(f\" # sudo yum install gcc-toolset-{version_min}\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" On macOS, use Clang instead:\")\n print()\n print(\" # Xcode Command Line Tools (includes Clang):\")\n print(\" xcode-select --install\")\n print()\n\n elif self.name == \"Clang\":\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: LLVM APT repository:\")\n print()\n print(\" wget https://apt.llvm.org/llvm.sh\")\n print(\" chmod +x llvm.sh\")\n print(f\" sudo ./llvm.sh {version_min}\")\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(f\" # Check your distribution for clang-{version_min}\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" Option 1: Xcode Command Line Tools:\")\n print()\n print(\" xcode-select --install\")\n print()\n\n print(\" Option 2: Build from source:\")\n print()\n print(\" # See compiler documentation for build instructions\")\n print()","source_hash":"a1df35850a37ef58743d1b4419541a76766ba229aecbe8cd85b30f4e3d6355eb","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.ninja","uri":"program://Fuser/module/python.tools.prereqs.requirements.ninja#L1-L86","kind":"module","name":"python.tools.prereqs.requirements.ninja","path":"python/tools/prereqs/requirements/ninja.py","language":"python","start_line":1,"end_line":86,"context_start_line":1,"context_end_line":86,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Ninja build system dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass NinjaRequirement(BooleanRequirement):\n \"\"\"\n Ninja build system check.\n\n CMake variables used:\n - Ninja_FOUND: Whether Ninja is available\n - NVFUSER_REQUIREMENT_Ninja_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Ninja_OPTIONAL: Whether Ninja is optional\n\n No version checking - just verifies Ninja is available.\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Ninja requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Ninja\"\n found_var = \"Ninja_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Ninja_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Ninja_OPTIONAL\"\n location_var = \"\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Ninja installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"Ninja Build System\")\n print()\n print(\n \"Why: Ninja is a fast build system used by nvFuser for faster compilation.\"\n )\n print()\n print(\"Install Ninja:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: Ubuntu/Debian:\")\n print()\n print(\" sudo apt update\")\n print(\" sudo apt install ninja-build\")\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(\" # Example for RHEL/CentOS:\")\n print(\" # sudo yum install ninja-build\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" Option 1: Homebrew:\")\n print()\n print(\" brew install ninja\")\n print()\n\n print(\" Option 2: pip:\")\n print()\n print(\" pip install ninja\")\n print()\n print(\" Configuring CMake\")\n print()\n print(\" Pass Ninja as the CMake Generator\")\n print(\" CMake -G Ninja\")\n print()","source_hash":"a2094991e81a8ad3c39055137d2dd2b294f8f2b5da871ed347f0c6d7177ce48d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.ninja.NinjaRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.ninja.NinjaRequirement#L10-L86","kind":"class","name":"NinjaRequirement","path":"python/tools/prereqs/requirements/ninja.py","language":"python","start_line":10,"end_line":86,"context_start_line":1,"context_end_line":86,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Ninja build system dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass NinjaRequirement(BooleanRequirement):\n \"\"\"\n Ninja build system check.\n\n CMake variables used:\n - Ninja_FOUND: Whether Ninja is available\n - NVFUSER_REQUIREMENT_Ninja_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Ninja_OPTIONAL: Whether Ninja is optional\n\n No version checking - just verifies Ninja is available.\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Ninja requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Ninja\"\n found_var = \"Ninja_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Ninja_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Ninja_OPTIONAL\"\n location_var = \"\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Ninja installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"Ninja Build System\")\n print()\n print(\n \"Why: Ninja is a fast build system used by nvFuser for faster compilation.\"\n )\n print()\n print(\"Install Ninja:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: Ubuntu/Debian:\")\n print()\n print(\" sudo apt update\")\n print(\" sudo apt install ninja-build\")\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(\" # Example for RHEL/CentOS:\")\n print(\" # sudo yum install ninja-build\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" Option 1: Homebrew:\")\n print()\n print(\" brew install ninja\")\n print()\n\n print(\" Option 2: pip:\")\n print()\n print(\" pip install ninja\")\n print()\n print(\" Configuring CMake\")\n print()\n print(\" Pass Ninja as the CMake Generator\")\n print(\" CMake -G Ninja\")\n print()","source_hash":"a2094991e81a8ad3c39055137d2dd2b294f8f2b5da871ed347f0c6d7177ce48d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.ninja.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.ninja.__init__#L22-L38","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/ninja.py","language":"python","start_line":22,"end_line":38,"context_start_line":2,"context_end_line":58,"code":"# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Ninja build system dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass NinjaRequirement(BooleanRequirement):\n \"\"\"\n Ninja build system check.\n\n CMake variables used:\n - Ninja_FOUND: Whether Ninja is available\n - NVFUSER_REQUIREMENT_Ninja_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Ninja_OPTIONAL: Whether Ninja is optional\n\n No version checking - just verifies Ninja is available.\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Ninja requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Ninja\"\n found_var = \"Ninja_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Ninja_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Ninja_OPTIONAL\"\n location_var = \"\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Ninja installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"Ninja Build System\")\n print()\n print(\n \"Why: Ninja is a fast build system used by nvFuser for faster compilation.\"\n )\n print()\n print(\"Install Ninja:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":","source_hash":"a2094991e81a8ad3c39055137d2dd2b294f8f2b5da871ed347f0c6d7177ce48d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.ninja.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.ninja.generate_help#L40-L86","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/ninja.py","language":"python","start_line":40,"end_line":86,"context_start_line":20,"context_end_line":86,"code":" \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Ninja requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Ninja\"\n found_var = \"Ninja_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Ninja_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Ninja_OPTIONAL\"\n location_var = \"\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Ninja installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"Ninja Build System\")\n print()\n print(\n \"Why: Ninja is a fast build system used by nvFuser for faster compilation.\"\n )\n print()\n print(\"Install Ninja:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: Ubuntu/Debian:\")\n print()\n print(\" sudo apt update\")\n print(\" sudo apt install ninja-build\")\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(\" # Example for RHEL/CentOS:\")\n print(\" # sudo yum install ninja-build\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" Option 1: Homebrew:\")\n print()\n print(\" brew install ninja\")\n print()\n\n print(\" Option 2: pip:\")\n print()\n print(\" pip install ninja\")\n print()\n print(\" Configuring CMake\")\n print()\n print(\" Pass Ninja as the CMake Generator\")\n print(\" CMake -G Ninja\")\n print()","source_hash":"a2094991e81a8ad3c39055137d2dd2b294f8f2b5da871ed347f0c6d7177ce48d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.torch","uri":"program://Fuser/module/python.tools.prereqs.requirements.torch#L1-L177","kind":"module","name":"python.tools.prereqs.requirements.torch","path":"python/tools/prereqs/requirements/torch.py","language":"python","start_line":1,"end_line":177,"context_start_line":1,"context_end_line":177,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"PyTorch dependency requirement with CUDA constraint validation.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\nfrom ..colors import colorize\n\n\nclass TorchRequirement(VersionRequirement):\n \"\"\"\n PyTorch requirement with CUDA version constraint checking.\n\n CMake variables used:\n - Torch_FOUND: Whether Torch was found\n - Torch_VERSION: Detected PyTorch version\n - Torch_DIR: Path to Torch CMake config\n - NVFUSER_REQUIREMENT_Torch_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Torch_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_Torch_OPTIONAL: Whether Torch is optional\n - Torch_CUDA_constraint_status: CUDA constraint validation result\n - \"match\": Torch CUDA == CUDAToolkit version\n - \"mismatch\": Versions don't match (FAILURE)\n - \"not_available\": Torch built without CUDA\n - Torch_CUDA_constraint_version: CUDA version if match\n - Torch_CUDA_constraint_found: Torch's CUDA version (if mismatch)\n - Torch_CUDA_constraint_required: System's CUDA Toolkit version (if mismatch)\n\n Special: Also validates CUDA version constraint\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Torch requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Torch\"\n found_var = \"Torch_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Torch_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Torch_OPTIONAL\"\n version_found_var = \"Torch_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Torch_VERSION_MIN\"\n location_var = \"Torch_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n # Extract Torch CUDA constraint variables from cmake_vars\n self.constraint_status = cmake_vars.get(f\"{name}_CUDA_constraint_status\")\n self.constraint_version = cmake_vars.get(f\"{name}_CUDA_constraint_version\")\n self.constraint_found = cmake_vars.get(f\"{name}_CUDA_constraint_found\")\n self.constraint_required = cmake_vars.get(f\"{name}_CUDA_constraint_required\")\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format with both Torch version and CUDA constraint.\"\"\"\n # Main Torch version line (base class handles location)\n main_line = super().format_status_line(colors)\n\n # Add CUDA constraint line\n constraint_line = self._format_cuda_constraint(colors)\n\n if constraint_line:\n return main_line + \"\\n\" + constraint_line\n else:\n return main_line\n\n def _format_cuda_constraint(self, colors) -> str:\n \"\"\"Format CUDA constraint validation line.\"\"\"\n if not self.constraint_status:\n return \"\"\n\n # Use same padding as main dependency name\n name_padded = f\"{'Torch_CUDA':<15}\"\n\n if self.constraint_status == \"match\":\n cuda_version = self.constraint_version or \"unknown\"\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓\") + \" \" + name_padded\n # Use cyan for the CUDA version/result, matching location color\n version_part = colorize(\n colors.CYAN, f\"{cuda_version} (Torch.CUDA == CUDAToolkit)\"\n )\n return f\"{status_part} {version_part}\"\n elif self.constraint_status == \"mismatch\":\n torch_cuda = self.constraint_found or \"unknown\"\n toolkit_cuda = self.constraint_required or \"unknown\"\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗\") + \" \" + name_padded\n error_part = colorize(\n colors.BOLD_RED,\n f\"mismatch (Torch: {torch_cuda}, CUDAToolkit: {toolkit_cuda})\",\n )\n return f\"{status_part} {error_part}\"\n elif self.constraint_status == \"not_available\":\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○\") + \" \" + name_padded\n message_part = colorize(colors.YELLOW, \"Torch built without CUDA\")\n return f\"{status_part} {message_part}\"\n else:\n return \"\"\n\n def is_failure(self) -> bool:\n \"\"\"Check for both version failure and CUDA constraint failure.\"\"\"\n # Check base version requirement\n if super().is_failure():\n return True\n\n # Check CUDA constraint\n if self.constraint_status == \"mismatch\":\n return True\n\n return False\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate PyTorch installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"PyTorch {version_min}+ Required\")\n print()\n print(\n \"Why: nvFuser is a PyTorch extension and requires PyTorch with CUDA support.\"\n )\n print()\n print(f\"Install PyTorch {version_min} or higher with CUDA:\")\n print()\n\n # Show common CUDA versions\n print(\" # For CUDA 13.1:\")\n print(\" pip install torch --index-url https://download.pytorch.org/whl/cu131\")\n print(\" # For CUDA 13.0:\")\n print(\" pip install torch --index-url https://download.pytorch.org/whl/cu130\")\n print(\" # For CUDA 12.8:\")\n print(\" pip install torch --index-url https://download.pytorch.org/whl/cu128\")\n print()\n\n # If CUDA constraint mismatch, add additional help\n if self.constraint_status == \"mismatch\":\n print()\n print(\"IMPORTANT: Torch CUDA Version Mismatch Detected\")\n print()\n print(\n \"Why: PyTorch was built with a different CUDA version than your system's\"\n )\n print(\" CUDA Toolkit. This will cause runtime errors.\")\n print()\n print(\"Resolution:\")\n print()\n print(\" You have two options:\")\n print()\n print(\" Option 1: Install matching CUDA Toolkit (recommended)\")\n print()\n print(\n \" Install the CUDA Toolkit version that matches your PyTorch build.\"\n )\n print(\n \" Check PyTorch CUDA version: python -c 'import torch; print(torch.version.cuda)'\"\n )\n print()\n print(\" Option 2: Reinstall PyTorch for your CUDA version\")\n print()\n print(\" Reinstall PyTorch built for your system's CUDA Toolkit version.\")\n print(\" Check system CUDA version: nvcc --version\")\n print()","source_hash":"cb9281b6cd3b1657ed364965c23b5a05f3018549b02b674c22c04d1c0aa3fa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.torch.TorchRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.torch.TorchRequirement#L11-L177","kind":"class","name":"TorchRequirement","path":"python/tools/prereqs/requirements/torch.py","language":"python","start_line":11,"end_line":177,"context_start_line":1,"context_end_line":177,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"PyTorch dependency requirement with CUDA constraint validation.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\nfrom ..colors import colorize\n\n\nclass TorchRequirement(VersionRequirement):\n \"\"\"\n PyTorch requirement with CUDA version constraint checking.\n\n CMake variables used:\n - Torch_FOUND: Whether Torch was found\n - Torch_VERSION: Detected PyTorch version\n - Torch_DIR: Path to Torch CMake config\n - NVFUSER_REQUIREMENT_Torch_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Torch_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_Torch_OPTIONAL: Whether Torch is optional\n - Torch_CUDA_constraint_status: CUDA constraint validation result\n - \"match\": Torch CUDA == CUDAToolkit version\n - \"mismatch\": Versions don't match (FAILURE)\n - \"not_available\": Torch built without CUDA\n - Torch_CUDA_constraint_version: CUDA version if match\n - Torch_CUDA_constraint_found: Torch's CUDA version (if mismatch)\n - Torch_CUDA_constraint_required: System's CUDA Toolkit version (if mismatch)\n\n Special: Also validates CUDA version constraint\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Torch requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Torch\"\n found_var = \"Torch_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Torch_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Torch_OPTIONAL\"\n version_found_var = \"Torch_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Torch_VERSION_MIN\"\n location_var = \"Torch_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n # Extract Torch CUDA constraint variables from cmake_vars\n self.constraint_status = cmake_vars.get(f\"{name}_CUDA_constraint_status\")\n self.constraint_version = cmake_vars.get(f\"{name}_CUDA_constraint_version\")\n self.constraint_found = cmake_vars.get(f\"{name}_CUDA_constraint_found\")\n self.constraint_required = cmake_vars.get(f\"{name}_CUDA_constraint_required\")\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format with both Torch version and CUDA constraint.\"\"\"\n # Main Torch version line (base class handles location)\n main_line = super().format_status_line(colors)\n\n # Add CUDA constraint line\n constraint_line = self._format_cuda_constraint(colors)\n\n if constraint_line:\n return main_line + \"\\n\" + constraint_line\n else:\n return main_line\n\n def _format_cuda_constraint(self, colors) -> str:\n \"\"\"Format CUDA constraint validation line.\"\"\"\n if not self.constraint_status:\n return \"\"\n\n # Use same padding as main dependency name\n name_padded = f\"{'Torch_CUDA':<15}\"\n\n if self.constraint_status == \"match\":\n cuda_version = self.constraint_version or \"unknown\"\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓\") + \" \" + name_padded\n # Use cyan for the CUDA version/result, matching location color\n version_part = colorize(\n colors.CYAN, f\"{cuda_version} (Torch.CUDA == CUDAToolkit)\"\n )\n return f\"{status_part} {version_part}\"\n elif self.constraint_status == \"mismatch\":\n torch_cuda = self.constraint_found or \"unknown\"\n toolkit_cuda = self.constraint_required or \"unknown\"\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗\") + \" \" + name_padded\n error_part = colorize(\n colors.BOLD_RED,\n f\"mismatch (Torch: {torch_cuda}, CUDAToolkit: {toolkit_cuda})\",\n )\n return f\"{status_part} {error_part}\"\n elif self.constraint_status == \"not_available\":\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○\") + \" \" + name_padded\n message_part = colorize(colors.YELLOW, \"Torch built without CUDA\")\n return f\"{status_part} {message_part}\"\n else:\n return \"\"\n\n def is_failure(self) -> bool:\n \"\"\"Check for both version failure and CUDA constraint failure.\"\"\"\n # Check base version requirement\n if super().is_failure():\n return True\n\n # Check CUDA constraint\n if self.constraint_status == \"mismatch\":\n return True\n\n return False\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate PyTorch installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"PyTorch {version_min}+ Required\")\n print()\n print(\n \"Why: nvFuser is a PyTorch extension and requires PyTorch with CUDA support.\"\n )\n print()\n print(f\"Install PyTorch {version_min} or higher with CUDA:\")\n print()\n\n # Show common CUDA versions\n print(\" # For CUDA 13.1:\")\n print(\" pip install torch --index-url https://download.pytorch.org/whl/cu131\")\n print(\" # For CUDA 13.0:\")\n print(\" pip install torch --index-url https://download.pytorch.org/whl/cu130\")\n print(\" # For CUDA 12.8:\")\n print(\" pip install torch --index-url https://download.pytorch.org/whl/cu128\")\n print()\n\n # If CUDA constraint mismatch, add additional help\n if self.constraint_status == \"mismatch\":\n print()\n print(\"IMPORTANT: Torch CUDA Version Mismatch Detected\")\n print()\n print(\n \"Why: PyTorch was built with a different CUDA version than your system's\"\n )\n print(\" CUDA Toolkit. This will cause runtime errors.\")\n print()\n print(\"Resolution:\")\n print()\n print(\" You have two options:\")\n print()\n print(\" Option 1: Install matching CUDA Toolkit (recommended)\")\n print()\n print(\n \" Install the CUDA Toolkit version that matches your PyTorch build.\"\n )\n print(\n \" Check PyTorch CUDA version: python -c 'import torch; print(torch.version.cuda)'\"\n )\n print()\n print(\" Option 2: Reinstall PyTorch for your CUDA version\")\n print()\n print(\" Reinstall PyTorch built for your system's CUDA Toolkit version.\")\n print(\" Check system CUDA version: nvcc --version\")\n print()","source_hash":"cb9281b6cd3b1657ed364965c23b5a05f3018549b02b674c22c04d1c0aa3fa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.torch.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.torch.__init__#L33-L64","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/torch.py","language":"python","start_line":33,"end_line":64,"context_start_line":13,"context_end_line":84,"code":" PyTorch requirement with CUDA version constraint checking.\n\n CMake variables used:\n - Torch_FOUND: Whether Torch was found\n - Torch_VERSION: Detected PyTorch version\n - Torch_DIR: Path to Torch CMake config\n - NVFUSER_REQUIREMENT_Torch_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Torch_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_Torch_OPTIONAL: Whether Torch is optional\n - Torch_CUDA_constraint_status: CUDA constraint validation result\n - \"match\": Torch CUDA == CUDAToolkit version\n - \"mismatch\": Versions don't match (FAILURE)\n - \"not_available\": Torch built without CUDA\n - Torch_CUDA_constraint_version: CUDA version if match\n - Torch_CUDA_constraint_found: Torch's CUDA version (if mismatch)\n - Torch_CUDA_constraint_required: System's CUDA Toolkit version (if mismatch)\n\n Special: Also validates CUDA version constraint\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Torch requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Torch\"\n found_var = \"Torch_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Torch_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Torch_OPTIONAL\"\n version_found_var = \"Torch_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Torch_VERSION_MIN\"\n location_var = \"Torch_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n # Extract Torch CUDA constraint variables from cmake_vars\n self.constraint_status = cmake_vars.get(f\"{name}_CUDA_constraint_status\")\n self.constraint_version = cmake_vars.get(f\"{name}_CUDA_constraint_version\")\n self.constraint_found = cmake_vars.get(f\"{name}_CUDA_constraint_found\")\n self.constraint_required = cmake_vars.get(f\"{name}_CUDA_constraint_required\")\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format with both Torch version and CUDA constraint.\"\"\"\n # Main Torch version line (base class handles location)\n main_line = super().format_status_line(colors)\n\n # Add CUDA constraint line\n constraint_line = self._format_cuda_constraint(colors)\n\n if constraint_line:\n return main_line + \"\\n\" + constraint_line\n else:\n return main_line\n\n def _format_cuda_constraint(self, colors) -> str:\n \"\"\"Format CUDA constraint validation line.\"\"\"\n if not self.constraint_status:\n return \"\"\n\n # Use same padding as main dependency name","source_hash":"cb9281b6cd3b1657ed364965c23b5a05f3018549b02b674c22c04d1c0aa3fa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.torch.format_status_line","uri":"program://Fuser/function/python.tools.prereqs.requirements.torch.format_status_line#L66-L77","kind":"function","name":"format_status_line","path":"python/tools/prereqs/requirements/torch.py","language":"python","start_line":66,"end_line":77,"context_start_line":46,"context_end_line":97,"code":" version_required_var = \"NVFUSER_REQUIREMENT_Torch_VERSION_MIN\"\n location_var = \"Torch_DIR\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n # Extract Torch CUDA constraint variables from cmake_vars\n self.constraint_status = cmake_vars.get(f\"{name}_CUDA_constraint_status\")\n self.constraint_version = cmake_vars.get(f\"{name}_CUDA_constraint_version\")\n self.constraint_found = cmake_vars.get(f\"{name}_CUDA_constraint_found\")\n self.constraint_required = cmake_vars.get(f\"{name}_CUDA_constraint_required\")\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format with both Torch version and CUDA constraint.\"\"\"\n # Main Torch version line (base class handles location)\n main_line = super().format_status_line(colors)\n\n # Add CUDA constraint line\n constraint_line = self._format_cuda_constraint(colors)\n\n if constraint_line:\n return main_line + \"\\n\" + constraint_line\n else:\n return main_line\n\n def _format_cuda_constraint(self, colors) -> str:\n \"\"\"Format CUDA constraint validation line.\"\"\"\n if not self.constraint_status:\n return \"\"\n\n # Use same padding as main dependency name\n name_padded = f\"{'Torch_CUDA':<15}\"\n\n if self.constraint_status == \"match\":\n cuda_version = self.constraint_version or \"unknown\"\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓\") + \" \" + name_padded\n # Use cyan for the CUDA version/result, matching location color\n version_part = colorize(\n colors.CYAN, f\"{cuda_version} (Torch.CUDA == CUDAToolkit)\"\n )\n return f\"{status_part} {version_part}\"\n elif self.constraint_status == \"mismatch\":\n torch_cuda = self.constraint_found or \"unknown\"\n toolkit_cuda = self.constraint_required or \"unknown\"","source_hash":"cb9281b6cd3b1657ed364965c23b5a05f3018549b02b674c22c04d1c0aa3fa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.torch._format_cuda_constraint","uri":"program://Fuser/function/python.tools.prereqs.requirements.torch._format_cuda_constraint#L79-L109","kind":"function","name":"_format_cuda_constraint","path":"python/tools/prereqs/requirements/torch.py","language":"python","start_line":79,"end_line":109,"context_start_line":59,"context_end_line":129,"code":"\n # Extract Torch CUDA constraint variables from cmake_vars\n self.constraint_status = cmake_vars.get(f\"{name}_CUDA_constraint_status\")\n self.constraint_version = cmake_vars.get(f\"{name}_CUDA_constraint_version\")\n self.constraint_found = cmake_vars.get(f\"{name}_CUDA_constraint_found\")\n self.constraint_required = cmake_vars.get(f\"{name}_CUDA_constraint_required\")\n\n def format_status_line(self, colors) -> str:\n \"\"\"Format with both Torch version and CUDA constraint.\"\"\"\n # Main Torch version line (base class handles location)\n main_line = super().format_status_line(colors)\n\n # Add CUDA constraint line\n constraint_line = self._format_cuda_constraint(colors)\n\n if constraint_line:\n return main_line + \"\\n\" + constraint_line\n else:\n return main_line\n\n def _format_cuda_constraint(self, colors) -> str:\n \"\"\"Format CUDA constraint validation line.\"\"\"\n if not self.constraint_status:\n return \"\"\n\n # Use same padding as main dependency name\n name_padded = f\"{'Torch_CUDA':<15}\"\n\n if self.constraint_status == \"match\":\n cuda_version = self.constraint_version or \"unknown\"\n status_part = colorize(colors.GREEN, \"[nvFuser] ✓\") + \" \" + name_padded\n # Use cyan for the CUDA version/result, matching location color\n version_part = colorize(\n colors.CYAN, f\"{cuda_version} (Torch.CUDA == CUDAToolkit)\"\n )\n return f\"{status_part} {version_part}\"\n elif self.constraint_status == \"mismatch\":\n torch_cuda = self.constraint_found or \"unknown\"\n toolkit_cuda = self.constraint_required or \"unknown\"\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗\") + \" \" + name_padded\n error_part = colorize(\n colors.BOLD_RED,\n f\"mismatch (Torch: {torch_cuda}, CUDAToolkit: {toolkit_cuda})\",\n )\n return f\"{status_part} {error_part}\"\n elif self.constraint_status == \"not_available\":\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○\") + \" \" + name_padded\n message_part = colorize(colors.YELLOW, \"Torch built without CUDA\")\n return f\"{status_part} {message_part}\"\n else:\n return \"\"\n\n def is_failure(self) -> bool:\n \"\"\"Check for both version failure and CUDA constraint failure.\"\"\"\n # Check base version requirement\n if super().is_failure():\n return True\n\n # Check CUDA constraint\n if self.constraint_status == \"mismatch\":\n return True\n\n return False\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate PyTorch installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"","source_hash":"cb9281b6cd3b1657ed364965c23b5a05f3018549b02b674c22c04d1c0aa3fa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.torch.is_failure","uri":"program://Fuser/function/python.tools.prereqs.requirements.torch.is_failure#L111-L121","kind":"function","name":"is_failure","path":"python/tools/prereqs/requirements/torch.py","language":"python","start_line":111,"end_line":121,"context_start_line":91,"context_end_line":141,"code":" version_part = colorize(\n colors.CYAN, f\"{cuda_version} (Torch.CUDA == CUDAToolkit)\"\n )\n return f\"{status_part} {version_part}\"\n elif self.constraint_status == \"mismatch\":\n torch_cuda = self.constraint_found or \"unknown\"\n toolkit_cuda = self.constraint_required or \"unknown\"\n status_part = colorize(colors.BOLD_RED, \"[nvFuser] ✗\") + \" \" + name_padded\n error_part = colorize(\n colors.BOLD_RED,\n f\"mismatch (Torch: {torch_cuda}, CUDAToolkit: {toolkit_cuda})\",\n )\n return f\"{status_part} {error_part}\"\n elif self.constraint_status == \"not_available\":\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○\") + \" \" + name_padded\n message_part = colorize(colors.YELLOW, \"Torch built without CUDA\")\n return f\"{status_part} {message_part}\"\n else:\n return \"\"\n\n def is_failure(self) -> bool:\n \"\"\"Check for both version failure and CUDA constraint failure.\"\"\"\n # Check base version requirement\n if super().is_failure():\n return True\n\n # Check CUDA constraint\n if self.constraint_status == \"mismatch\":\n return True\n\n return False\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate PyTorch installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"PyTorch {version_min}+ Required\")\n print()\n print(\n \"Why: nvFuser is a PyTorch extension and requires PyTorch with CUDA support.\"\n )\n print()\n print(f\"Install PyTorch {version_min} or higher with CUDA:\")\n print()\n\n # Show common CUDA versions","source_hash":"cb9281b6cd3b1657ed364965c23b5a05f3018549b02b674c22c04d1c0aa3fa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.torch.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.torch.generate_help#L123-L177","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/torch.py","language":"python","start_line":123,"end_line":177,"context_start_line":103,"context_end_line":177,"code":" return f\"{status_part} {error_part}\"\n elif self.constraint_status == \"not_available\":\n status_part = colorize(colors.YELLOW, \"[nvFuser] ○\") + \" \" + name_padded\n message_part = colorize(colors.YELLOW, \"Torch built without CUDA\")\n return f\"{status_part} {message_part}\"\n else:\n return \"\"\n\n def is_failure(self) -> bool:\n \"\"\"Check for both version failure and CUDA constraint failure.\"\"\"\n # Check base version requirement\n if super().is_failure():\n return True\n\n # Check CUDA constraint\n if self.constraint_status == \"mismatch\":\n return True\n\n return False\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate PyTorch installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"PyTorch {version_min}+ Required\")\n print()\n print(\n \"Why: nvFuser is a PyTorch extension and requires PyTorch with CUDA support.\"\n )\n print()\n print(f\"Install PyTorch {version_min} or higher with CUDA:\")\n print()\n\n # Show common CUDA versions\n print(\" # For CUDA 13.1:\")\n print(\" pip install torch --index-url https://download.pytorch.org/whl/cu131\")\n print(\" # For CUDA 13.0:\")\n print(\" pip install torch --index-url https://download.pytorch.org/whl/cu130\")\n print(\" # For CUDA 12.8:\")\n print(\" pip install torch --index-url https://download.pytorch.org/whl/cu128\")\n print()\n\n # If CUDA constraint mismatch, add additional help\n if self.constraint_status == \"mismatch\":\n print()\n print(\"IMPORTANT: Torch CUDA Version Mismatch Detected\")\n print()\n print(\n \"Why: PyTorch was built with a different CUDA version than your system's\"\n )\n print(\" CUDA Toolkit. This will cause runtime errors.\")\n print()\n print(\"Resolution:\")\n print()\n print(\" You have two options:\")\n print()\n print(\" Option 1: Install matching CUDA Toolkit (recommended)\")\n print()\n print(\n \" Install the CUDA Toolkit version that matches your PyTorch build.\"\n )\n print(\n \" Check PyTorch CUDA version: python -c 'import torch; print(torch.version.cuda)'\"\n )\n print()\n print(\" Option 2: Reinstall PyTorch for your CUDA version\")\n print()\n print(\" Reinstall PyTorch built for your system's CUDA Toolkit version.\")\n print(\" Check system CUDA version: nvcc --version\")\n print()","source_hash":"cb9281b6cd3b1657ed364965c23b5a05f3018549b02b674c22c04d1c0aa3fa0d","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.nvmmh","uri":"program://Fuser/module/python.tools.prereqs.requirements.nvmmh#L1-L63","kind":"module","name":"python.tools.prereqs.requirements.nvmmh","path":"python/tools/prereqs/requirements/nvmmh.py","language":"python","start_line":1,"end_line":63,"context_start_line":1,"context_end_line":63,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"nvidia-matmul-heuristics dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass NVMMHRequirement(BooleanRequirement):\n \"\"\"\n nvidia-matmul-heuristics check.\n\n CMake variables used:\n - NVMMH_FOUND: Whether nvidia-matmul-heuristics is available\n - NVFUSER_REQUIREMENT_NVMMH_STATUS: Validation status\n - NVFUSER_REQUIREMENT_NVMMH_OPTIONAL: Whether NVMMH is optional\n\n No version checking - just verifies nvidia-matmul-heuristics headers are available.\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize nvidia-matmul-heuristics requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"NVMMH\"\n found_var = \"NVMMH_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_NVMMH_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_NVMMH_OPTIONAL\"\n location_var = \"NVMMH_INCLUDE_DIR\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate nvidia-matmul-heuristics installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"nvidia-matmul-heuristics (NVMMH)\")\n print()\n print(\n \"Why: nvidia-matmul-heuristics provides optimized matrix multiplication heuristics for nvFuser.\"\n )\n print()\n print(\"Install nvidia-matmul-heuristics:\")\n print()\n print(\" Recommended: pip installation:\")\n print()\n print(\" pip install nvidia-matmul-heuristics\")\n print()\n print(\" Note: This is an optional dependency. nvFuser will build without it,\")\n print(\n \" but matmul operations may not have access to optimized heuristics.\"\n )\n print()","source_hash":"d46a059c3427a7cbff2f52c8291f5a9fd2f4ceaf74f2fc8225aae5749734197a","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.nvmmh.NVMMHRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.nvmmh.NVMMHRequirement#L10-L63","kind":"class","name":"NVMMHRequirement","path":"python/tools/prereqs/requirements/nvmmh.py","language":"python","start_line":10,"end_line":63,"context_start_line":1,"context_end_line":63,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"nvidia-matmul-heuristics dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass NVMMHRequirement(BooleanRequirement):\n \"\"\"\n nvidia-matmul-heuristics check.\n\n CMake variables used:\n - NVMMH_FOUND: Whether nvidia-matmul-heuristics is available\n - NVFUSER_REQUIREMENT_NVMMH_STATUS: Validation status\n - NVFUSER_REQUIREMENT_NVMMH_OPTIONAL: Whether NVMMH is optional\n\n No version checking - just verifies nvidia-matmul-heuristics headers are available.\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize nvidia-matmul-heuristics requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"NVMMH\"\n found_var = \"NVMMH_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_NVMMH_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_NVMMH_OPTIONAL\"\n location_var = \"NVMMH_INCLUDE_DIR\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate nvidia-matmul-heuristics installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"nvidia-matmul-heuristics (NVMMH)\")\n print()\n print(\n \"Why: nvidia-matmul-heuristics provides optimized matrix multiplication heuristics for nvFuser.\"\n )\n print()\n print(\"Install nvidia-matmul-heuristics:\")\n print()\n print(\" Recommended: pip installation:\")\n print()\n print(\" pip install nvidia-matmul-heuristics\")\n print()\n print(\" Note: This is an optional dependency. nvFuser will build without it,\")\n print(\n \" but matmul operations may not have access to optimized heuristics.\"\n )\n print()","source_hash":"d46a059c3427a7cbff2f52c8291f5a9fd2f4ceaf74f2fc8225aae5749734197a","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.nvmmh.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.nvmmh.__init__#L22-L38","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/nvmmh.py","language":"python","start_line":22,"end_line":38,"context_start_line":2,"context_end_line":58,"code":"# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"nvidia-matmul-heuristics dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass NVMMHRequirement(BooleanRequirement):\n \"\"\"\n nvidia-matmul-heuristics check.\n\n CMake variables used:\n - NVMMH_FOUND: Whether nvidia-matmul-heuristics is available\n - NVFUSER_REQUIREMENT_NVMMH_STATUS: Validation status\n - NVFUSER_REQUIREMENT_NVMMH_OPTIONAL: Whether NVMMH is optional\n\n No version checking - just verifies nvidia-matmul-heuristics headers are available.\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize nvidia-matmul-heuristics requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"NVMMH\"\n found_var = \"NVMMH_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_NVMMH_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_NVMMH_OPTIONAL\"\n location_var = \"NVMMH_INCLUDE_DIR\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate nvidia-matmul-heuristics installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"nvidia-matmul-heuristics (NVMMH)\")\n print()\n print(\n \"Why: nvidia-matmul-heuristics provides optimized matrix multiplication heuristics for nvFuser.\"\n )\n print()\n print(\"Install nvidia-matmul-heuristics:\")\n print()\n print(\" Recommended: pip installation:\")\n print()\n print(\" pip install nvidia-matmul-heuristics\")\n print()","source_hash":"d46a059c3427a7cbff2f52c8291f5a9fd2f4ceaf74f2fc8225aae5749734197a","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.nvmmh.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.nvmmh.generate_help#L40-L63","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/nvmmh.py","language":"python","start_line":40,"end_line":63,"context_start_line":20,"context_end_line":63,"code":" \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize nvidia-matmul-heuristics requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"NVMMH\"\n found_var = \"NVMMH_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_NVMMH_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_NVMMH_OPTIONAL\"\n location_var = \"NVMMH_INCLUDE_DIR\"\n\n super().__init__(\n name, cmake_vars, found_var, status_var, optional_var, location_var\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate nvidia-matmul-heuristics installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n print(\"nvidia-matmul-heuristics (NVMMH)\")\n print()\n print(\n \"Why: nvidia-matmul-heuristics provides optimized matrix multiplication heuristics for nvFuser.\"\n )\n print()\n print(\"Install nvidia-matmul-heuristics:\")\n print()\n print(\" Recommended: pip installation:\")\n print()\n print(\" pip install nvidia-matmul-heuristics\")\n print()\n print(\" Note: This is an optional dependency. nvFuser will build without it,\")\n print(\n \" but matmul operations may not have access to optimized heuristics.\"\n )\n print()","source_hash":"d46a059c3427a7cbff2f52c8291f5a9fd2f4ceaf74f2fc8225aae5749734197a","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.python","uri":"program://Fuser/module/python.tools.prereqs.requirements.python#L1-L94","kind":"module","name":"python.tools.prereqs.requirements.python","path":"python/tools/prereqs/requirements/python.py","language":"python","start_line":1,"end_line":94,"context_start_line":1,"context_end_line":94,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Python dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass PythonRequirement(VersionRequirement):\n \"\"\"\n Python interpreter requirement.\n\n CMake variables used:\n - Python_FOUND: Whether Python was found\n - Python_VERSION: Detected version (e.g., \"3.12.3\")\n - Python_EXECUTABLE: Path to python binary\n - NVFUSER_REQUIREMENT_Python_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Python_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_Python_OPTIONAL: Whether Python is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Python requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Python\"\n found_var = \"Python_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Python_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Python_OPTIONAL\"\n version_found_var = \"Python_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Python_VERSION_MIN\"\n location_var = \"Python_EXECUTABLE\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Python installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"Python {version_min}+ Required\")\n print()\n print(\n \"Why: nvFuser requires modern Python with type hints and language features.\"\n )\n print()\n print(f\"Install Python {version_min} or higher:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: Ubuntu/Debian system package:\")\n print()\n print(\" sudo apt update\")\n print(f\" sudo apt install python{version_min}\")\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(\" # Example for RHEL/CentOS:\")\n print(f\" # sudo yum install python{version_min}\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" Option 1: Homebrew:\")\n print()\n print(f\" brew install python@{version_min}\")\n print()\n\n print(\" Option 2: Conda:\")\n print()\n print(f\" conda create -n nvfuser python={version_min}\")\n print(\" conda activate nvfuser\")\n print()","source_hash":"aaec8121a03dbd540440f34deb289fd581872c597ccfcfd7bfcc9e31ffa34eab","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.python.PythonRequirement","uri":"program://Fuser/class/python.tools.prereqs.requirements.python.PythonRequirement#L10-L94","kind":"class","name":"PythonRequirement","path":"python/tools/prereqs/requirements/python.py","language":"python","start_line":10,"end_line":94,"context_start_line":1,"context_end_line":94,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Python dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass PythonRequirement(VersionRequirement):\n \"\"\"\n Python interpreter requirement.\n\n CMake variables used:\n - Python_FOUND: Whether Python was found\n - Python_VERSION: Detected version (e.g., \"3.12.3\")\n - Python_EXECUTABLE: Path to python binary\n - NVFUSER_REQUIREMENT_Python_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Python_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_Python_OPTIONAL: Whether Python is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Python requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Python\"\n found_var = \"Python_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Python_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Python_OPTIONAL\"\n version_found_var = \"Python_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Python_VERSION_MIN\"\n location_var = \"Python_EXECUTABLE\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Python installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"Python {version_min}+ Required\")\n print()\n print(\n \"Why: nvFuser requires modern Python with type hints and language features.\"\n )\n print()\n print(f\"Install Python {version_min} or higher:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: Ubuntu/Debian system package:\")\n print()\n print(\" sudo apt update\")\n print(f\" sudo apt install python{version_min}\")\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(\" # Example for RHEL/CentOS:\")\n print(f\" # sudo yum install python{version_min}\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" Option 1: Homebrew:\")\n print()\n print(f\" brew install python@{version_min}\")\n print()\n\n print(\" Option 2: Conda:\")\n print()\n print(f\" conda create -n nvfuser python={version_min}\")\n print(\" conda activate nvfuser\")\n print()","source_hash":"aaec8121a03dbd540440f34deb289fd581872c597ccfcfd7bfcc9e31ffa34eab","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.python.__init__","uri":"program://Fuser/function/python.tools.prereqs.requirements.python.__init__#L23-L48","kind":"function","name":"__init__","path":"python/tools/prereqs/requirements/python.py","language":"python","start_line":23,"end_line":48,"context_start_line":3,"context_end_line":68,"code":"# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Python dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass PythonRequirement(VersionRequirement):\n \"\"\"\n Python interpreter requirement.\n\n CMake variables used:\n - Python_FOUND: Whether Python was found\n - Python_VERSION: Detected version (e.g., \"3.12.3\")\n - Python_EXECUTABLE: Path to python binary\n - NVFUSER_REQUIREMENT_Python_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Python_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_Python_OPTIONAL: Whether Python is optional\n \"\"\"\n\n def __init__(self, cmake_vars: Dict):\n \"\"\"\n Initialize Python requirement.\n\n Args:\n cmake_vars: Dictionary of all CMake variables\n \"\"\"\n # Define dependency name and CMake variable names for this requirement\n name = \"Python\"\n found_var = \"Python_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Python_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Python_OPTIONAL\"\n version_found_var = \"Python_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Python_VERSION_MIN\"\n location_var = \"Python_EXECUTABLE\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Python installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"Python {version_min}+ Required\")\n print()\n print(\n \"Why: nvFuser requires modern Python with type hints and language features.\"\n )\n print()\n print(f\"Install Python {version_min} or higher:\")\n print()\n\n os_type = platform_info[\"os\"]","source_hash":"aaec8121a03dbd540440f34deb289fd581872c597ccfcfd7bfcc9e31ffa34eab","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.tools.prereqs.requirements.python.generate_help","uri":"program://Fuser/function/python.tools.prereqs.requirements.python.generate_help#L50-L94","kind":"function","name":"generate_help","path":"python/tools/prereqs/requirements/python.py","language":"python","start_line":50,"end_line":94,"context_start_line":30,"context_end_line":94,"code":" # Define dependency name and CMake variable names for this requirement\n name = \"Python\"\n found_var = \"Python_FOUND\"\n status_var = \"NVFUSER_REQUIREMENT_Python_STATUS\"\n optional_var = \"NVFUSER_REQUIREMENT_Python_OPTIONAL\"\n version_found_var = \"Python_VERSION\"\n version_required_var = \"NVFUSER_REQUIREMENT_Python_VERSION_MIN\"\n location_var = \"Python_EXECUTABLE\"\n\n super().__init__(\n name,\n cmake_vars,\n found_var,\n status_var,\n optional_var,\n version_found_var,\n version_required_var,\n location_var,\n )\n\n def generate_help(self, platform_info):\n \"\"\"\n Generate Python installation help.\n\n Args:\n platform_info: Platform detection dict from detect_platform()\n \"\"\"\n version_min = self.version_required\n\n print(f\"Python {version_min}+ Required\")\n print()\n print(\n \"Why: nvFuser requires modern Python with type hints and language features.\"\n )\n print()\n print(f\"Install Python {version_min} or higher:\")\n print()\n\n os_type = platform_info[\"os\"]\n\n if os_type == \"Linux\":\n if platform_info.get(\"ubuntu_based\"):\n print(\" Option 1: Ubuntu/Debian system package:\")\n print()\n print(\" sudo apt update\")\n print(f\" sudo apt install python{version_min}\")\n print()\n else:\n print(\" Option 1: System package manager:\")\n print()\n print(\" # Example for RHEL/CentOS:\")\n print(f\" # sudo yum install python{version_min}\")\n print()\n\n elif os_type == \"Darwin\":\n print(\" Option 1: Homebrew:\")\n print()\n print(f\" brew install python@{version_min}\")\n print()\n\n print(\" Option 2: Conda:\")\n print()\n print(f\" conda create -n nvfuser python={version_min}\")\n print(\" conda activate nvfuser\")\n print()","source_hash":"aaec8121a03dbd540440f34deb289fd581872c597ccfcfd7bfcc9e31ffa34eab","truncated":false} {"repo_id":"Fuser","entity_id":"py:python.nvfuser_common.utils","uri":"program://Fuser/module/python.nvfuser_common.utils#L1-L18","kind":"module","name":"python.nvfuser_common.utils","path":"python/nvfuser_common/utils.py","language":"python","start_line":1,"end_line":18,"context_start_line":1,"context_end_line":18,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport os\n\n\n__all__ = [\n \"cmake_prefix_path\",\n]\n\n\ncmake_prefix_path = os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"nvfuser_common\",\n \"share\",\n \"cmake\",\n \"nvfuser\",\n)","source_hash":"193d1b8b1dbe90bf497223354561a160f4366974b36452abb293360a8d19eaf1","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/conftest.py","uri":"program://Fuser/file/tests/python/conftest.py","kind":"file","name":"tests/python/conftest.py","path":"tests/python/conftest.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\n\n\ndef pytest_configure(config):\n \"\"\"\n Hook called after command line options have been parsed and all plugins\n and initial conftest files have been loaded.\n \"\"\"\n # Append to NVFUSER_ENABLE environment variable for all tests in this directory\n # Note: id_model is now enabled by default, so we only need extra validation\n existing = os.environ.get(\"NVFUSER_ENABLE\", \"\")\n new_options = \"id_model_extra_validation\"\n\n if existing:\n os.environ[\"NVFUSER_ENABLE\"] = f\"{existing},{new_options}\"\n else:\n os.environ[\"NVFUSER_ENABLE\"] = new_options","source_hash":"fb6a76db3dcad75f3f199cc3f99d6b9add747b31de3244244b40d07d1ed36a89","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/test_moe.py","uri":"program://Fuser/file/tests/python/test_moe.py","kind":"file","name":"tests/python/test_moe.py","path":"tests/python/test_moe.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport math\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom thunder.dynamo import thunderfx\n\n\n# Sizes used in Llama 4 Maverick\n@dataclass\nclass Config:\n hidden_size: int = 5120\n intermediate_size: int = 8192\n num_routed_experts: int = 128","source_hash":"beaa41123320e7e35be960bd74e909c604077e53da26bef58411dd6d3381f08d","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/__init__.py","uri":"program://Fuser/file/tests/python/__init__.py","kind":"file","name":"tests/python/__init__.py","path":"tests/python/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":3,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause","source_hash":"42ba09bbb339816dd46109a07ebfd999dbf561ebfbe624942f77de0b0aed53da","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/opinfo/opinfo_fusion_definitions.py","uri":"program://Fuser/file/tests/python/opinfo/opinfo_fusion_definitions.py","kind":"file","name":"tests/python/opinfo/opinfo_fusion_definitions.py","path":"tests/python/opinfo/opinfo_fusion_definitions.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\n\nfrom opinfo_core import OpInfo\nfrom opinfo_utils import ArgumentType, is_tensor\n\nimport sys\n\nif \"nvfuser\" in sys.modules:\n from nvfuser import FusionDefinition\n from nvfuser.pytorch_utils import (\n python_scalar_to_nvfuser_dtype,\n torch_dtype_to_nvfuser_dtype,\n )\nelse:\n from nvfuser_direct import FusionDefinition\n from nvfuser_direct.pytorch_utils import (","source_hash":"1d767ab9c58a75685d55748d43ba65fb10de10ccb53f16865deebbc0fa72a2af","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/opinfo/opinfo_core.py","uri":"program://Fuser/file/tests/python/opinfo/opinfo_core.py","kind":"file","name":"tests/python/opinfo/opinfo_core.py","path":"tests/python/opinfo/opinfo_core.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nfrom opinfo_utils import (\n all_dtypes_except_reduced,\n ArgumentType,\n torch_to_python_dtype_map,\n)\nfrom typing import Callable, Optional\nimport torch\nfrom enum import Enum\nfrom dataclasses import dataclass, field\n\n\nclass ReferenceType(Enum):\n Pytorch = 0\n Jax = 1\n Numpy = 2\n Python = 3","source_hash":"c33f7e6088671f2d82806320297d5058a76783e30192134ee20a1e924edf8956","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/opinfo/opinfo_input_generators.py","uri":"program://Fuser/file/tests/python/opinfo/opinfo_input_generators.py","kind":"file","name":"tests/python/opinfo/opinfo_input_generators.py","path":"tests/python/opinfo/opinfo_input_generators.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport itertools\nfrom functools import partial, wraps\n\nimport math\nimport torch\nfrom torch.testing import make_tensor\nimport random\nfrom numbers import Number\n\nfrom opinfo_core import OpInfo, SampleInput, ErrorSample, Domain\nfrom opinfo_utils import (\n make_number,\n find_nonmatching_dtype,\n is_floating_dtype,\n float_complex_dtypes,\n complex_dtypes,","source_hash":"c438e10cf315053acd27e878f6f95e88eded3644b5cddf003265d27237d4d582","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/opinfo/test_direct_ops.py","uri":"program://Fuser/file/tests/python/opinfo/test_direct_ops.py","kind":"file","name":"tests/python/opinfo/test_direct_ops.py","path":"tests/python/opinfo/test_direct_ops.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\n# import nvfuser_direct first to conditionally avoid importing nvfuser\nimport nvfuser_direct # noqa: F401,F403\n\nimport torch\nimport pytest\nimport numpy as np\nfrom copy import deepcopy\nfrom typing import Callable\n\nfrom opinfo_fusion_definitions import default_fd_fn\nfrom opinfo_framework import create_op_test\nfrom opinfo_core import ReferenceType, OpInfo, SampleInput\nfrom opinfos import opinfos\nfrom opinfo_utils import (\n ArgumentType,\n is_tensor,","source_hash":"faa4d27e2a1558270180eccfa54432eb5d5a3ed1a08275d57dce9647ec02cada","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/opinfo/opinfo_framework.py","uri":"program://Fuser/file/tests/python/opinfo/opinfo_framework.py","kind":"file","name":"tests/python/opinfo/opinfo_framework.py","path":"tests/python/opinfo/opinfo_framework.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport inspect\nimport torch\nfrom typing import Callable\nfrom opinfo_utils import map_dtype_to_str\nimport pytest\n\n\ndef _instantiate_opinfo_test_template(\n template: Callable, *, opinfo, dtype: torch.dtype\n) -> Callable:\n \"\"\"Instantiates a test template for an operator.\"\"\"\n\n def test():\n # Ref: https://github.com/pytorch/pytorch/blob/aa8ea1d787a9d21b064b664c5344376265feea6c/torch/testing/_internal/common_utils.py#L2251-L2263\n # > CUDA device side error will cause subsequence test cases to fail.\n # > stop entire test suite if catches RuntimeError during torch.cuda.synchronize().","source_hash":"4f3ed271b48407a66bec01b8baaabfecc481eb0b15f1ff5ded5cc6f25376e13a","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/opinfo/opinfos.py","uri":"program://Fuser/file/tests/python/opinfo/opinfos.py","kind":"file","name":"tests/python/opinfo/opinfos.py","path":"tests/python/opinfo/opinfos.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport math\nimport torch\nfrom looseversion import LooseVersion\nfrom opinfo_core import OpInfo, ReferenceType, Domain\nfrom opinfo_fusion_definitions import (\n api_test_fd_fn,\n tensor_input_fd_fn,\n tensor_api_test_fd_fn,\n vector_api_test_fd_fn,\n)\nfrom opinfo_input_generators import (\n argsort_generator,\n topk_generator,\n topk_error_generator,\n broadcast_error_generator,\n broadcast_in_dim_generator,","source_hash":"9581ab96ba0d4058c283ba5dbda3eb396b5e62750241c12d793a6f47f527d170","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/opinfo/opinfo_utils.py","uri":"program://Fuser/file/tests/python/opinfo/opinfo_utils.py","kind":"file","name":"tests/python/opinfo/opinfo_utils.py","path":"tests/python/opinfo/opinfo_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom torch.testing import make_tensor\nfrom enum import Enum, auto\nfrom typing import Optional\nfrom functools import wraps\n\ntry:\n # flake8: noqa\n import jax\n\n JAX_AVAILABLE = True\nexcept ImportError as e:\n JAX_AVAILABLE = False\n pass\n","source_hash":"7b1a8b141cd1f5b1b9ee2d1be34b7370295fe944b4edfbecdd2278c1778c36af","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/conftest.py","uri":"program://Fuser/file/tests/python/direct/conftest.py","kind":"file","name":"tests/python/direct/conftest.py","path":"tests/python/direct/conftest.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nfrom copy import deepcopy\nimport torch\nfrom torch.testing._internal.common_utils import TestCase\n\nfrom nvfuser_direct import FusionDefinition, LRUCache\nfrom python.direct_utils import is_pre_volta, check_captured_python_definition\n\n\nclass NVFuserTest(TestCase):\n def __init__(self, cache=None):\n super().__init__()\n self.cache = cache\n\n # Helper function to verify the nvfuser output and make sure the string\n # definition based on the FusionDefinition is executable and matches the","source_hash":"a868b522b94ffe66899fc542b20baf53acdf618e326b56af07b7f9f2bf23b795","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_with_id_model_indexer.py","uri":"program://Fuser/file/tests/python/direct/test_with_id_model_indexer.py","kind":"file","name":"tests/python/direct/test_with_id_model_indexer.py","path":"tests/python/direct/test_with_id_model_indexer.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\n\nfrom nvfuser_direct import (\n FusionDefinition,\n DataType,\n)\nfrom python.direct_utils import (\n FLOAT4_E2M1_MAX,\n FLOAT8_E4M3_EPS,\n FLOAT8_E4M3_MAX,\n pytorch_nvfp4_quantize,\n microarchitecture_is,\n linear_to_swizzled_128_4,\n round_up,\n activation_scale_to_nvfp4,\n)","source_hash":"d94a5942e48e7275c52f33258085cb65c5e386e4a07c2aa792c6d202ec025b38","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_import.py","uri":"program://Fuser/file/tests/python/direct/test_import.py","kind":"file","name":"tests/python/direct/test_import.py","path":"tests/python/direct/test_import.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":11,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\n\ndef test_import_correct():\n try:\n import nvfuser_direct # noqa: F401\n except Exception as e:\n raise RuntimeError(\"Failed to import nvfuser_direct.\")","source_hash":"9aeec2b01671c242bc8bd38b191ff5186e32b4d6e295be25954ee94fe37b9dd1","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_cutlass_mxfp8_gemm.py","uri":"program://Fuser/file/tests/python/direct/test_cutlass_mxfp8_gemm.py","kind":"file","name":"tests/python/direct/test_cutlass_mxfp8_gemm.py","path":"tests/python/direct/test_cutlass_mxfp8_gemm.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom nvfuser_direct import nvf_cutlass\nfrom python.direct_utils import microarchitecture_is\n\nif not microarchitecture_is(10, 0):\n pytest.skip(\n reason=\"MxFp8 Requires compute capability 10.\",\n allow_module_level=True,\n )\n\nfrom python.direct_utils import (\n linear_to_swizzled_128_4,\n swizzled_to_linear_128_4,\n)\n","source_hash":"3a28c1acbf10abb1306ae3e47420674aa8ed7be482fdfafde8924b8499b19e2e","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_cutlass_gemm.py","uri":"program://Fuser/file/tests/python/direct/test_cutlass_gemm.py","kind":"file","name":"tests/python/direct/test_cutlass_gemm.py","path":"tests/python/direct/test_cutlass_gemm.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom python.direct_utils import microarchitecture_is\nfrom nvfuser_direct import nvf_cutlass\n\n\n# GPU Compute Capability: https://developer.nvidia.com/cuda/gpus\n# tested on blackwell compute 10.0 (B200 and GB200)\n# doesn't support 12.0 (RTX PRO 6000 and RTX 50XX)\n# Not tested on 10.3 (B300 and GB300)\n# Not tested on 12.1 (DGX Spark)\n@pytest.mark.skipif(\n not microarchitecture_is(10, 0),\n reason=\"Does not support blackwell compute 12.0, other arches are not tested.\",\n)\n@pytest.mark.parametrize(\"config\", [[1024, 128, 256], [267, 128, 256]])","source_hash":"90fc66264118e872a194a187c8d092794c4dd284e5a5bc4745c17d955e6bcb2f","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_stream.py","uri":"program://Fuser/file/tests/python/direct/test_stream.py","kind":"file","name":"tests/python/direct/test_stream.py","path":"tests/python/direct/test_stream.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nfrom nvfuser_direct import FusionDefinition, ParallelType, DataType\n\n\ndef test_matmul():\n c = 3\n\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n w = fd.define_tensor([-1, -1], contiguity=True, dtype=DataType.Float)\n out = fd.ops.matmul(inp, w)\n fd.add_output(out)\n\n out.outer_split(1, c)\n out.axis(1).parallelize(ParallelType.stream)\n # With NVFUSER_DUMP=host_ir, you'll see the host IR container like the","source_hash":"cdc184c555d84abe002bbfc0df03863e1dadcdd4755f0092c3a3e7568d5751af","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_sdpa.py","uri":"program://Fuser/file/tests/python/direct/test_sdpa.py","kind":"file","name":"tests/python/direct/test_sdpa.py","path":"tests/python/direct/test_sdpa.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport itertools\nimport math\nimport pytest\nimport torch\nimport torch.nn.functional as F\nfrom enum import Enum, auto\nfrom functools import partial\n\nfrom nvfuser_direct import (\n FusionDefinition,\n DataType,\n)\nfrom python.direct_utils import (\n is_pre_ampere,\n define_sdpa_rng_state,\n verify_stride_order,","source_hash":"587a5c41942d1189804c29b016e7fadd5af5634c6898654314b71364cdf3c2e6","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_python_frontend.py","uri":"program://Fuser/file/tests/python/direct/test_python_frontend.py","kind":"file","name":"tests/python/direct/test_python_frontend.py","path":"tests/python/direct/test_python_frontend.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport torch._refs as refs\nimport torch._prims as prims\n\nfrom nvfuser_direct import (\n FusionDefinition,\n DataType,\n compute_tensor_descriptor,\n)\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\n\nimport pytest\nimport itertools\nfrom python.direct_utils import (\n is_pre_ampere,\n is_pre_hopper,","source_hash":"d5bec6a2d9e874f91def1c131f99b3d0753e55765d454c6869edcec8ff4652ce","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_narrow_precision.py","uri":"program://Fuser/file/tests/python/direct/test_narrow_precision.py","kind":"file","name":"tests/python/direct/test_narrow_precision.py","path":"tests/python/direct/test_narrow_precision.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\n\nfrom nvfuser_direct import (\n FusionDefinition,\n DataType,\n)\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom python.direct_utils import (\n FLOAT4_E2M1_MAX,\n FLOAT8_E4M3_MAX,\n pytorch_nvfp4_quantize,\n microarchitecture_is,\n is_pre_blackwell,\n microarchitecture_is_pre,\n linear_to_swizzled_128_4,\n round_up,","source_hash":"d50ea4faaad81b04de589a8e0fe65205b832c80dba76fef8c9be2f8703fdb115","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_alphafold3.py","uri":"program://Fuser/file/tests/python/direct/test_alphafold3.py","kind":"file","name":"tests/python/direct/test_alphafold3.py","path":"tests/python/direct/test_alphafold3.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\n# This file contains certain building blocks of the AlphaFold3 model.\n\nimport pytest\nimport torch\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\n\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4\n","source_hash":"6a26821a82d11493f977f992f6869d6772e3eabfbe1ff3c78afc222d6674a7f3","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_repro.py","uri":"program://Fuser/file/tests/python/direct/test_repro.py","kind":"file","name":"tests/python/direct/test_repro.py","path":"tests/python/direct/test_repro.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom python.direct_utils import skip_if_global_memory_below_gb\n\n# Use smaller range for torch.testing.make_tensor for nvfuser_direct.validate\nLOW_VAL = -2\nHIGH_VAL = 2\n\n\ndef test_issue1129(nvfuser_direct_test):\n \"\"\"\n Test for issue 1129 - tests reshape and index_select operations with strided tensors.\n\n This test verifies that reshape and index_select operations work correctly\n with tensors that have non-standard strides, particularly when reshaping","source_hash":"f2f76caf352be044732392bbc0ed8469286f3d052f593f1ef6160751e519d46b","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_tutorial.py","uri":"program://Fuser/file/tests/python/direct/test_tutorial.py","kind":"file","name":"tests/python/direct/test_tutorial.py","path":"tests/python/direct/test_tutorial.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nimport torch.nn.functional as F\nfrom nvfuser_direct import (\n FusionDefinition,\n IdMappingMode,\n ParallelType,\n TensorView,\n Merge,\n Split,\n BroadcastOp,\n SqueezeOp,\n ReshapeOp,\n LoadStoreOpType,\n MemoryType,\n DataType,","source_hash":"496e0e7289064bcc378e5923bfeaf7f6f60a654534acbf356f7eff9304db229e","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_cutlass_nvfp4_gemm.py","uri":"program://Fuser/file/tests/python/direct/test_cutlass_nvfp4_gemm.py","kind":"file","name":"tests/python/direct/test_cutlass_nvfp4_gemm.py","path":"tests/python/direct/test_cutlass_nvfp4_gemm.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport pytest\nimport torch\nfrom nvfuser_direct import nvf_cutlass\nfrom python.direct_utils import microarchitecture_is\n\nif not microarchitecture_is(10, 0):\n pytest.skip(\n reason=\"Nvfp4 Requires compute capability 10.0, other arches are not tested.\",\n allow_module_level=True,\n )\n\nfrom python.direct_utils import (\n FLOAT4_E2M1_MAX,\n FLOAT8_E4M3_MAX,\n dequantize_to_dtype,\n linear_to_swizzled_128_4,","source_hash":"11120d40e8965626932725fad0e2e4222686aa63290220b5f25cce499ae7eb55","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_matmul.py","uri":"program://Fuser/file/tests/python/direct/test_matmul.py","kind":"file","name":"tests/python/direct/test_matmul.py","path":"tests/python/direct/test_matmul.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom python.direct_utils import verify_stride_order\nfrom nvfuser_direct import FusionDefinition\nfrom functools import partial\nimport itertools\nimport torch.nn.functional as F\n\n\ndef test_matmul(nvfuser_direct_test):\n m = 24\n n = 16\n k = 8\n inputs_tt = [\n torch.randn(m, k, device=\"cuda\", dtype=torch.float16),\n torch.randn(k, n, device=\"cuda\", dtype=torch.float16),","source_hash":"f901761adcd90633f2c5cdd182de96fddd387ee6f68b3a2d6c94c1515441bbb2","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_high_complexity.py","uri":"program://Fuser/file/tests/python/direct/test_high_complexity.py","kind":"file","name":"tests/python/direct/test_high_complexity.py","path":"tests/python/direct/test_high_complexity.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport torch._refs as refs\nimport torch._prims as prims\n\nimport io\nfrom contextlib import redirect_stdout, redirect_stderr\nimport pytest\n\nfrom nvfuser_direct import FusionDefinition, DataType\nimport random\nimport itertools\nimport math\nfrom functools import partial\nfrom typing import List\n\n","source_hash":"2170248e66a73f33f502a6e8bffee75aa0372bea057037823864409d29ea2a2a","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_allocation.py","uri":"program://Fuser/file/tests/python/direct/test_allocation.py","kind":"file","name":"tests/python/direct/test_allocation.py","path":"tests/python/direct/test_allocation.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\n\nfrom nvfuser_direct import FusionDefinition, DataType\n\n\ndef test_contiguous():\n with FusionDefinition() as fd:\n inp = fd.define_tensor([-1, -1], dtype=DataType.Float, contiguity=True)\n out = fd.ops.sum(inp, [-1])\n fd.add_output(out)\n\n # It might not be obvious but this tensor is indeed contiguous by\n # definition. inp.size(0) == 1 so inp.stride(0) shouldn't matter.\n #\n # I ran into such a tensor when I shard a reference tensor for a particular\n # device using slicing:\n # ```","source_hash":"61df72b81f5ba524e14ae7665fb7002f071878f58c1cf6ee523b11594c814e42","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct/test_python_direct.py","uri":"program://Fuser/file/tests/python/direct/test_python_direct.py","kind":"file","name":"tests/python/direct/test_python_direct.py","path":"tests/python/direct/test_python_direct.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nfrom nvfuser_direct import (\n FusionDefinition,\n PythonProfiler,\n DataType,\n version,\n LruFusionCache,\n LRUCache,\n)\nimport torch\nimport pytest\nimport io\nimport re\nfrom contextlib import redirect_stdout, redirect_stderr\nfrom typing import Callable\n\n","source_hash":"ef0a225d1239408b895276dfb2f610ea29aac8b345a9dec953618283127cf670","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_transformer_engine.py","uri":"program://Fuser/file/tests/python/multidevice/test_transformer_engine.py","kind":"file","name":"tests/python/multidevice/test_transformer_engine.py","path":"tests/python/multidevice/test_transformer_engine.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\nimport torch.distributed as dist\n\nimport transformer_engine.pytorch as te\n\nfrom . import Parallelism\nfrom .benchmark_utils import get_benchmark_fns\nfrom enum import auto, Enum\n\ncompute_cap = torch.cuda.get_device_capability()\n\n\nclass ComputeType(Enum):\n FORWARD = auto()\n BACKWARD = auto()","source_hash":"baf4662712370a08ab2860526c8d7afa900f8c786166f9672547d388ed4cb7c2","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/fusion_definition_wrapper.py","uri":"program://Fuser/file/tests/python/multidevice/fusion_definition_wrapper.py","kind":"file","name":"tests/python/multidevice/fusion_definition_wrapper.py","path":"tests/python/multidevice/fusion_definition_wrapper.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition\nfrom collections.abc import Iterable\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement, Shard\nfrom typing import Callable, cast, TypeAlias\n\n\nDTensorsKey: TypeAlias = tuple[tuple[str, str], ...]\n\n\ndef make_key_from_dtensors(dtensors: Iterable[DTensor]) -> DTensorsKey:\n key = tuple((repr(dt.device_mesh), repr(dt.placements)) for dt in dtensors)\n return key\n\n\nclass FusionDefinitionWrapper:","source_hash":"61b827a798d6b0cf667f2c05d9d6e6be3722edd48ed5056cb6c7a3ed1ef68718","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_dtensor.py","uri":"program://Fuser/file/tests/python/multidevice/test_dtensor.py","kind":"file","name":"tests/python/multidevice/test_dtensor.py","path":"tests/python/multidevice/test_dtensor.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\nimport torch.distributed as dist\n\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Shard, Replicate\nfrom .fusion_definition_wrapper import FusionDefinitionWrapper\nfrom .linear import LinearFunction\nfrom nvfuser_direct import FusionDefinition, DataType\n\n\n@pytest.mark.mpi\ndef test_plus_one(setup_default_process_group, multidevice_test):\n def define_fusion(fd: FusionDefinition):\n inp = fd.define_tensor((-1, -1), contiguity=False, dtype=DataType.Float)\n one = fd.define_scalar(1.0, dtype=DataType.Float)","source_hash":"77cb69829bfffaac4c646fcf958581e665e5cdcc48efe90791f4ba20d43efa0d","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/conftest.py","uri":"program://Fuser/file/tests/python/multidevice/conftest.py","kind":"file","name":"tests/python/multidevice/conftest.py","path":"tests/python/multidevice/conftest.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n# Run command:\n# mpirun -np [num_devices] pytest tests/python/multidevice/[test_name].py --only-mpi -s\n\nimport os\nimport pytest\nfrom typing import Iterable\n\nimport torch\nimport torch.distributed as dist\n\nimport nvfuser_direct as nvfuser\n\n\nclass MultideviceTest:\n def __init__(self):\n os.environ[\"NVIDIA_TF32_OVERRIDE\"] = \"0\"\n","source_hash":"fc1642fc86458349c953870d208a141b5a966cb76dfe62594c7d270cb5aa50c9","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_sharding.py","uri":"program://Fuser/file/tests/python/multidevice/test_sharding.py","kind":"file","name":"tests/python/multidevice/test_sharding.py","path":"tests/python/multidevice/test_sharding.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\n\nimport torch\n\nimport nvfuser_direct as nvfuser\n\n\n# Unit tests for multidevice_test.shard_tensor.\nclass TestShardTensor:\n @pytest.mark.mpi\n def test_inner_split(self, multidevice_test):\n d = multidevice_test.size\n\n with nvfuser.FusionDefinition() as fd:\n tv = fd.define_tensor([-1])\n fd.add_output(tv)\n","source_hash":"be6a15bb6463bafec7f6b521413393b97094aa8421e056a708198bb538b349b9","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_overlap.py","uri":"program://Fuser/file/tests/python/multidevice/test_overlap.py","kind":"file","name":"tests/python/multidevice/test_overlap.py","path":"tests/python/multidevice/test_overlap.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport os\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import distribute_tensor, Shard\n\nimport nvfuser_direct as nvfuser\nfrom .benchmark_utils import get_benchmark_fns\nfrom nvfuser_direct import DataType, FusionDefinition, CommunicatorBackend, TensorView\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\n\n\ndef row_parallel_linear_forward(\n h: int, num_devices: int, num_chunks: int\n) -> FusionDefinition:\n with FusionDefinition() as fd:","source_hash":"3225d084cc06e29fe2a0f525c332201cdef789b45b265e0e0769453586131c03","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/linear.py","uri":"program://Fuser/file/tests/python/multidevice/linear.py","kind":"file","name":"tests/python/multidevice/linear.py","path":"tests/python/multidevice/linear.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom dataclasses import dataclass\nfrom enum import auto, Enum\nfrom functools import lru_cache\nfrom typing import Iterable\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement\n\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom .fusion_definition_wrapper import FusionDefinitionWrapper\n\n\n@dataclass(frozen=True)\nclass LinearConfig:\n in_features: int","source_hash":"a3aba7f510e517b38c3bf0d4329e8fa09dc88025d2e7ccad477815bdbcde722e","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_deepseek_v3.py","uri":"program://Fuser/file/tests/python/multidevice/test_deepseek_v3.py","kind":"file","name":"tests/python/multidevice/test_deepseek_v3.py","path":"tests/python/multidevice/test_deepseek_v3.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\n# Run command:\n# mpirun -np 1 pytest tests/python/multidevice/test_deepseek_v3.py --only-mpi -s\n\nfrom contextlib import contextmanager\nfrom enum import Enum, auto\nfrom functools import wraps\nfrom typing import Optional\n\nimport pytest\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.parallel import (\n parallelize_module,\n ParallelStyle,","source_hash":"d068e317e5f63dcd02bfe4a81f35edad4e7ca2296d6f15507f332d46c453ad8c","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/__init__.py","uri":"program://Fuser/file/tests/python/multidevice/__init__.py","kind":"file","name":"tests/python/multidevice/__init__.py","path":"tests/python/multidevice/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":12,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom enum import auto, Enum\n\n\nclass Parallelism(Enum):\n # https://docs.nvidia.com/nemo-framework/user-guide/latest/nemotoolkit/features/parallelisms.html#tensor-parallelism\n TENSOR_PARALLEL = auto()\n # https://docs.nvidia.com/nemo-framework/user-guide/latest/nemotoolkit/features/parallelisms.html#sequence-parallelism\n SEQUENCE_PARALLEL = auto()","source_hash":"1ac365519a6ac463cb3fcd449bd7ef4e1b443583c8cc93baab5a5becca323e80","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_alphafold3.py","uri":"program://Fuser/file/tests/python/multidevice/test_alphafold3.py","kind":"file","name":"tests/python/multidevice/test_alphafold3.py","path":"tests/python/multidevice/test_alphafold3.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\n# This file contains certain building blocks of the AlphaFold3 model.\n\nimport pytest\nimport torch\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\n\n\n@dataclass\nclass ModelConfig:\n c_z: int = 128\n c_hidden: int = 32\n n_heads: int = 4","source_hash":"ce359eedb34ce2b0e73089cc2973e947c6fa1738111d19de95521144e7fbff16","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_communication.py","uri":"program://Fuser/file/tests/python/multidevice/test_communication.py","kind":"file","name":"tests/python/multidevice/test_communication.py","path":"tests/python/multidevice/test_communication.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition\n\n\n@pytest.mark.mpi\ndef test_allgather(multidevice_test):\n d = multidevice_test.size\n mesh = nvfuser.multidevice.DeviceMesh(torch.arange(d))\n\n with FusionDefinition() as fd:\n inp_tv = fd.define_tensor((d * 4,), contiguity=True, dtype=DataType.Float)\n out = fd.ops.set(inp_tv)\n fd.add_output(out)\n","source_hash":"10c383202c5fd2724914155f92a73bd6d631a0f73db87432b5dcaddc4abb6db3","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_expert_parallel.py","uri":"program://Fuser/file/tests/python/multidevice/test_expert_parallel.py","kind":"file","name":"tests/python/multidevice/test_expert_parallel.py","path":"tests/python/multidevice/test_expert_parallel.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\nimport torch.distributed as dist\n\n\n# Partitions n into k integers whose sum is n.\ndef random_partition(n: int, k: int) -> torch.Tensor:\n offsets = torch.randint(0, n + 1, [k - 1]).tolist()\n # The last partition ends at index n.\n offsets.append(n)\n offsets.sort()\n\n sizes = []\n prev = 0\n for offset in offsets:\n sizes.append(offset - prev)\n prev = offset","source_hash":"97fd6e8149ba6a16db8522d1d90eb3c483930251d4a36cc20625e750e97f82ff","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_transformer.py","uri":"program://Fuser/file/tests/python/multidevice/test_transformer.py","kind":"file","name":"tests/python/multidevice/test_transformer.py","path":"tests/python/multidevice/test_transformer.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\n\nimport torch\nimport torch.nn.functional as F\n\nimport nvfuser_direct as nvfuser\nfrom . import Parallelism\nfrom .benchmark_utils import get_benchmark_fns\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom python.direct_utils import (\n create_sdpa_rng_tensors,\n is_pre_ampere,\n)\n\n\n@pytest.mark.mpi\ndef test_grouped_mlp(multidevice_test):\n d = multidevice_test.size","source_hash":"883b974df7db254285dbce138b652387ceabc97df88c88b546fdae69ab5a90ff","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_matmul.py","uri":"program://Fuser/file/tests/python/multidevice/test_matmul.py","kind":"file","name":"tests/python/multidevice/test_matmul.py","path":"tests/python/multidevice/test_matmul.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition, PythonProfiler\n\n\n# Avoid doing this when possible. This test started to exist before nvFuser\n# supports DID loop split. As a result of that, the weight in this test has to be\n# 3D, different from a normal linear.\n@pytest.mark.mpi\ndef test_linear_logical_split(multidevice_test):\n d = multidevice_test.size\n\n b, s, e = 2, 1024, 768\n\n with FusionDefinition() as fd:","source_hash":"91c1ff0eec1dc37feeeb76dd356bd071ec47e5dfc10461ffd45053b95abd4fbf","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/benchmark_utils.py","uri":"program://Fuser/file/tests/python/multidevice/benchmark_utils.py","kind":"file","name":"tests/python/multidevice/benchmark_utils.py","path":"tests/python/multidevice/benchmark_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\n\n\ndef get_benchmark_fn(func, /, profile: bool):\n def wrapper(*args, **kwargs):\n if profile:\n torch.cuda.cudart().cudaProfilerStart()\n result = func(*args, **kwargs)\n torch.cuda.synchronize()\n if profile:\n torch.cuda.cudart().cudaProfilerStop()\n return result\n\n return wrapper\n\n\n# Returns two functors, the first with profiler off and the second with profiler","source_hash":"00d4c27aaf09229131f2f2e054be25637ebb5cac813a489a9051c1b8d743a2dd","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/multidevice/test_multidevice.py","uri":"program://Fuser/file/tests/python/multidevice/test_multidevice.py","kind":"file","name":"tests/python/multidevice/test_multidevice.py","path":"tests/python/multidevice/test_multidevice.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nimport torch\nfrom enum import Enum, auto\nfrom torch.nn.attention import SDPBackend\n\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import DataType, FusionDefinition\nfrom python.direct_utils import is_pre_ampere\n\n\n@pytest.mark.mpi\ndef test_sizes_and_ranks(multidevice_test):\n size, rank, local_size, local_rank = (\n multidevice_test.size,\n multidevice_test.rank,\n multidevice_test.local_size,\n multidevice_test.local_rank,","source_hash":"3fe9cf8da4d4d9451d39fc1077ffe2e103e74f9313be33d2de5e9886e0de50c4","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct_utils/narrow_precision.py","uri":"program://Fuser/file/tests/python/direct_utils/narrow_precision.py","kind":"file","name":"tests/python/direct_utils/narrow_precision.py","path":"tests/python/direct_utils/narrow_precision.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\n\nFLOAT4_E2M1_MAX = 6.0\nFLOAT8_E4M3_EPS = torch.finfo(torch.float8_e4m3fn).tiny\nFLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max\n\n\n# restore swizzled on block scaling factor:\n# 1. restore swizzle\n# 2. removes padding via slicing to [:mn, :k]\ndef swizzled_to_linear_128_4(a_sf_swizzled: torch.Tensor, mn, k):\n mn_padded, sf_k_padded = a_sf_swizzled.shape\n m_tiles = mn_padded // 128\n k_tiles = sf_k_padded // 4\n tmp = torch.reshape(a_sf_swizzled, (m_tiles, k_tiles, 32, 4, 4))\n return tmp.transpose(1, 3).reshape(mn_padded, sf_k_padded)[:mn, :k]","source_hash":"4a121a59c74d4c7573fdecb9e134160b8fc58e7aa3341509aeef68b797f7d6dc","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct_utils/__init__.py","uri":"program://Fuser/file/tests/python/direct_utils/__init__.py","kind":"file","name":"tests/python/direct_utils/__init__.py","path":"tests/python/direct_utils/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":7,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom . import utils, narrow_precision # noqa: F401,F403\nfrom .utils import * # noqa: F401,F403\nfrom .narrow_precision import * # noqa: F401,F403","source_hash":"fbc0882d0acb31aadb64535e4fa80b337831e6f87942a12f21c119e3d31f7d09","truncated":false} {"repo_id":"Fuser","entity_id":"file:tests/python/direct_utils/utils.py","uri":"program://Fuser/file/tests/python/direct_utils/utils.py","kind":"file","name":"tests/python/direct_utils/utils.py","path":"tests/python/direct_utils/utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType, TensorView\nfrom looseversion import LooseVersion\n\n\ndef microarchitecture_is(major, minor):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major == major and prop.minor == minor\n\n\ndef microarchitecture_is_pre(major):\n prop = torch.cuda.get_device_properties(torch.cuda.current_device())\n return prop.major < major\n\n","source_hash":"cbc2f43b80c529d37976aa19a8fcf3f8eb515b5e7d244e384c6e4c294b1e2125","truncated":false} {"repo_id":"Fuser","entity_id":"file:examples/sinh_extension/setup.py","uri":"program://Fuser/file/examples/sinh_extension/setup.py","kind":"file","name":"examples/sinh_extension/setup.py","path":"examples/sinh_extension/setup.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport os\nimport pathlib\nimport importlib.util\nfrom setuptools import setup\n\ntry:\n from torch.utils.cpp_extension import BuildExtension, CUDAExtension\nexcept ImportError:\n raise RuntimeError(\"PyTorch cpp_extension is required for building this package.\")\n\nnvfuser_csrc_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"..\", \"..\", \"csrc\"\n)\ndynamic_type_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"..\", \"..\", \"lib\", \"dynamic_type\", \"src\"\n)\nflatbuffers_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),","source_hash":"0e8be3e7fda8cd103652cb76b5f82bb9d5f16ac1f15fcfcd6dd3910569dbe7ca","truncated":false} {"repo_id":"Fuser","entity_id":"file:examples/sinh_extension/test.py","uri":"program://Fuser/file/examples/sinh_extension/test.py","kind":"file","name":"examples/sinh_extension/test.py","path":"examples/sinh_extension/test.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":16,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\nimport nvfuser_extension # noqa: F401\n\ntorch.manual_seed(0)\nt = torch.randn((5, 5), device=\"cuda\")\nexpected = torch.sinh(t)\noutput = torch.ops.myop.sinh_nvfuser(t)\n\nprint(\"Expected:\", expected)\nprint(\"Output:\", output)\n\nassert torch.allclose(output, expected)\nprint(\"They match!\")","source_hash":"41650d83aa89d625e16066824aa0630b11d8572662a8451655ab14c4e4fc924b","truncated":false} {"repo_id":"Fuser","entity_id":"file:examples/sinh_extension/nvfuser_extension/__init__.py","uri":"program://Fuser/file/examples/sinh_extension/nvfuser_extension/__init__.py","kind":"file","name":"examples/sinh_extension/nvfuser_extension/__init__.py","path":"examples/sinh_extension/nvfuser_extension/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":6,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom . import nvfuser_extension # noqa: F401\nfrom nvfuser_extension import * # noqa: F401,F403","source_hash":"9c45901011880fbd25aba2e1aec958b9bb0590fb875971652eb63dca084d582e","truncated":false} {"repo_id":"Fuser","entity_id":"file:doc/dev/python_scheduling/profile_matmul.py","uri":"program://Fuser/file/doc/dev/python_scheduling/profile_matmul.py","kind":"file","name":"doc/dev/python_scheduling/profile_matmul.py","path":"doc/dev/python_scheduling/profile_matmul.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import (\n FusionDefinition,\n SchedulerType,\n ClusterDims,\n MatMulTileOptions,\n GemmTile,\n MmaMacroEncode,\n MmaMacroArch,\n MatmulTileRasterizationOrder,\n MatmulCircularBufferingStrategy,\n)\nimport torch\nfrom torch.autograd import DeviceType\nfrom torch.profiler import profile, record_function, ProfilerActivity\nimport math\nimport itertools\nfrom enum import IntEnum","source_hash":"3dcb8d32bf9a4046ecc0bb81096dd7b437bef7f4a640b4b363733e4d803d96d9","truncated":false} {"repo_id":"Fuser","entity_id":"file:doc/dev/python_scheduling/autotune_utils.py","uri":"program://Fuser/file/doc/dev/python_scheduling/autotune_utils.py","kind":"file","name":"doc/dev/python_scheduling/autotune_utils.py","path":"doc/dev/python_scheduling/autotune_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport math\nimport itertools\nfrom nvfuser import FusionCache, FusionDefinition\nfrom dataclasses import dataclass, astuple\n\n# ================================ Description ================================\n# This file contains the utility function for autotuning scripts.\n# =============================================================================\n\n\n# Returns the result of a/b rounded to the nearest integer in the direction of\n# positive infinity.\ndef ceil_div(a, b):\n return int(math.ceil(a / b))\n","source_hash":"f9d35c4afa2023bb013c46fb7c4ab55d9b9522713d87e3e26d096fb1604e0458","truncated":false} {"repo_id":"Fuser","entity_id":"file:doc/dev/python_scheduling/autotune_persistent.py","uri":"program://Fuser/file/doc/dev/python_scheduling/autotune_persistent.py","kind":"file","name":"doc/dev/python_scheduling/autotune_persistent.py","path":"doc/dev/python_scheduling/autotune_persistent.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport itertools\nimport random\nfrom nvfuser import FusionCache, FusionDefinition, SchedulerType, DataType\nfrom nvfuser.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom copy import deepcopy\n\n# ============================ Description ============================\n\n# 1. Define a nvfuser fusion and its pytorch eager mode reference.\n#\n# 2. Profile the CUDA kernel performance by iterating over a set of input\n# arguments and scheduler configurations.\n#\n# 3. Train a regression model to predict the desired performance metric given\n# some input arguments and a scheduler configuration.","source_hash":"3deaac8d135d52dff58aad8d7d0e5af72849aba42ec3a992b79b5a862c95ec2f","truncated":false} {"repo_id":"Fuser","entity_id":"file:doc/dev/python_scheduling/autotune_pointwise.py","uri":"program://Fuser/file/doc/dev/python_scheduling/autotune_pointwise.py","kind":"file","name":"doc/dev/python_scheduling/autotune_pointwise.py","path":"doc/dev/python_scheduling/autotune_pointwise.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport itertools\nimport math\n\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import FusionDefinition, SchedulerType, DataType\nfrom dataclasses import dataclass\nfrom enum import Enum\n\nfrom autotune_utils import (\n ScriptConfiguration,\n collect_data,\n separate_data,\n test_model_rmse,\n test_model,\n)","source_hash":"9fa66a6eac84beff525a32163998e7e67b2d0d9d004621fc62f7391b6fbe359b","truncated":false} {"repo_id":"Fuser","entity_id":"file:doc/dev/python_scheduling/autotune_matmul.py","uri":"program://Fuser/file/doc/dev/python_scheduling/autotune_matmul.py","kind":"file","name":"doc/dev/python_scheduling/autotune_matmul.py","path":"doc/dev/python_scheduling/autotune_matmul.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport itertools\n\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import FusionDefinition, SchedulerType\n\n# Description of the problem\nM = 512\nN = 512\nK = 4096\ndtype = torch.bfloat16\n# TODO: layout\n\n# These are the parameters we'll optimize\nparameter_configurations = [\n splitk_factors := list(range(1, 8)),","source_hash":"731e4216a6cfaac03c8a5743a40137e6c028b32c7929d63fec21b30408fbb057","truncated":false} {"repo_id":"Fuser","entity_id":"file:doc/dev/python_scheduling/autotune_inner_reduction.py","uri":"program://Fuser/file/doc/dev/python_scheduling/autotune_inner_reduction.py","kind":"file","name":"doc/dev/python_scheduling/autotune_inner_reduction.py","path":"doc/dev/python_scheduling/autotune_inner_reduction.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport torch\nimport itertools\n\n# TODO Update script to use nvfuser_direct module\nfrom nvfuser import FusionDefinition, SchedulerType, DataType, ParallelType\nfrom enum import Enum\nfrom dataclasses import dataclass\n\nfrom autotune_utils import (\n ScriptConfiguration,\n collect_data,\n separate_data,\n test_model_rmse,\n test_model,\n ceil_div,\n floor_div,","source_hash":"e9dded29fa32e27acaca840578a72d09d7fa21af82c571e0acf27ac8886b261e","truncated":false} {"repo_id":"Fuser","entity_id":"file:doc/sphinx/source/conf.py","uri":"program://Fuser/file/doc/sphinx/source/conf.py","kind":"file","name":"doc/sphinx/source/conf.py","path":"doc/sphinx/source/conf.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# Owner(s): [\"module: nvfuser\"]\n\nimport os\nimport sys\nimport datetime\nimport pathlib\n\nsys.path.insert(0, os.path.abspath(\"../..\"))\n\nproject = \"nvFuser\"\nauthor = \"NVIDIA CORPORATION & AFFILIATES\"\n\n# Copyright statement\nrelease_year = 2023\ncurrent_year = datetime.date.today().year\nif current_year == release_year:\n copyright_year = release_year\nelse:","source_hash":"9cfc483ba59e266a4b5b5d59f6e5ab56d7c95889af7e0155823a0a2ce66ee6c8","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/benchmark_thunder.py","uri":"program://Fuser/file/tools/benchmark_thunder.py","kind":"file","name":"tools/benchmark_thunder.py","path":"tools/benchmark_thunder.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n# \"python benchmark_thunder.py -h\" for help.\n\nimport argparse\nimport os\nimport subprocess\nfrom typing import Iterable\n\n\n# Switches to the given branch, syncs to head, and returns the short hash of\n# the head.\ndef switch_to(branch: str, sync: bool) -> str:\n subprocess.check_call(f\"git fetch origin {branch}\", shell=True)\n\n # `advice.detachedHead=false` silences the detached HEAD warning.\n subprocess.check_call(\n f\"git -c advice.detachedHead=false checkout {branch}\", shell=True\n )","source_hash":"9864e6294b690faa29a234eadd14ba50e9c24115d7060b207e18a44cabf60bd7","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/compare_benchmark.py","uri":"program://Fuser/file/tools/compare_benchmark.py","kind":"file","name":"tools/compare_benchmark.py","path":"tools/compare_benchmark.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# \"compare_benchmark.py -h\" for help.\n\nimport argparse\nfrom dataclasses import dataclass\nimport json\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport subprocess\nfrom typing import Iterable\n\n\n# If `arg` uses a forbidden option, returns that forbidden option; otherwise,\n# returns an empty string.\ndef uses_forbidden_option(arg: str) -> str:\n for forbidden_option in (\n \"--benchmark_out\",","source_hash":"fc1361c8a0f09cd70b949c481e2d70a07b35f4ed3c4cf663d9541e1616cd922c","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/memory.py","uri":"program://Fuser/file/tools/memory.py","kind":"file","name":"tools/memory.py","path":"python/tools/memory.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\ndef get_available_memory_gb():\n \"\"\"Returns the available memory in GB.\"\"\"\n try:\n import psutil\n\n return psutil.virtual_memory().available / 1024 / 1024 / 1024\n except: # noqa: E722\n pass\n\n try:\n with open(\"/proc/meminfo\", \"r\") as f:\n while True:\n line = f.readline()\n if line.startswith(\"MemAvailable:\"):\n mem = line.split()[1]\n assert line.split()[2] == \"kB\"","source_hash":"29abf2a174c9e2b85c35c42603262a8157251a100571e5525577f4fff6e00105","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/cpp-repro-gen.py","uri":"program://Fuser/file/tools/cpp-repro-gen.py","kind":"file","name":"tools/cpp-repro-gen.py","path":"tools/cpp-repro-gen.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport ast\nimport typing\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--symbolic_sizes\", nargs=\"+\", type=int)\ncmd_args = parser.parse_args()\nsymbolic_sizes_index = 0\n\ninput = sys.stdin.read()\n\nlines = input.strip().splitlines()\n\nis_aten = False\n\n\ndef parse(l: str):","source_hash":"83e86d88435c8764f25a0322df76892dc9a5019c8cc7b9b1f739b8c1ecee78e5","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/update_copyright.py","uri":"program://Fuser/file/tools/update_copyright.py","kind":"file","name":"tools/update_copyright.py","path":"tools/update_copyright.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import os\n\next_map = {\n \"cpp\": (\"c\", \"cpp\", \"cu\", \"cc\", \"cuh\", \"h\"),\n \"py\": (\"py\",),\n \"txt\": (\"txt\",),\n}\n\nlicence_style_0 = \"\"\"\\\n// clang-format off\n/*\n * SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n * All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n */\n// clang-format on\n\"\"\"\n\nlicence_style_1 = \"\"\"\\\n# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.","source_hash":"5c7c23caad57961775158ad10d8c49f08455a70399c887c69fb63d1006c9f4d1","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/__init__.py","uri":"program://Fuser/file/tools/__init__.py","kind":"file","name":"tools/__init__.py","path":"tools/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":3,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause","source_hash":"228b8897cd383257646bf9e71e3f314eb5c0f4606e62926359adf565b2e9664d","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/stringify_file.py","uri":"program://Fuser/file/tools/stringify_file.py","kind":"file","name":"tools/stringify_file.py","path":"tools/stringify_file.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n# Generates a C++ header files embedding the original input as a string literal\n\nimport argparse\nimport pathlib\nfrom datetime import datetime\n\narg_parser = argparse.ArgumentParser(\n description=\"Converts source files to C++ string literals\", allow_abbrev=False\n)\n\narg_parser.add_argument(\"-i\", \"--input\", required=True, help=\"Input source file\")\n\narg_parser.add_argument(\n \"-o\", \"--output\", required=True, help=\"Name of the generated header file\"\n)\n\nargs = arg_parser.parse_args()","source_hash":"0d1e992a976633f5108638a9c35a8895ff48c626e43dd7b9f82da24d4a513981","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/run_nvfuser_tests.py","uri":"program://Fuser/file/tools/run_nvfuser_tests.py","kind":"file","name":"tools/run_nvfuser_tests.py","path":"tools/run_nvfuser_tests.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport subprocess\nimport os\nimport glob\nimport datetime\nfrom pathlib import Path\nimport time\nimport argparse\n\n\ndef setup_logging_dir():\n \"\"\"Create a timestamped directory for test logs and update latest symlink\"\"\"\n timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n log_dir = Path(f\"test_log_{timestamp}\")\n log_dir.mkdir(exist_ok=True)\n\n # Check and handle the 'latest' symlink\n latest_link = Path(\"test_log_latest\")\n if latest_link.exists():","source_hash":"986456095f7e0285aaefab1b148ab4abe061d8d7be148acb197891fd6fa0d07f","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/gen_nvfuser_version.py","uri":"program://Fuser/file/tools/gen_nvfuser_version.py","kind":"file","name":"tools/gen_nvfuser_version.py","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nUNKNOWN = \"Unknown\"\nnvfuser_root = Path(__file__).parent.parent\n\n\n# note that this root currently is still part of pytorch.\ndef get_sha() -> str:\n try:\n return (\n subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=nvfuser_root)\n .decode(\"ascii\")\n .strip()\n )\n except Exception:\n import os","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/generate_validation_tolerances.py","uri":"program://Fuser/file/tools/generate_validation_tolerances.py","kind":"file","name":"tools/generate_validation_tolerances.py","path":"tools/generate_validation_tolerances.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nThis script reproduces the computation used for generating the validation tolerances in csrc/validator_utils.h:\nhttps://github.com/NVIDIA/Fuser/blob/892b7ac5646b3b873f13f2b2ea1db15fa9b9effb/csrc/validator_utils.h#L25-L46\n\nThe computation (randn + mul + sum) is repeated a large number of times.\nThe base tolerance is the max error seen when comparing the desired precision type with the next higher precision.\nThe final tolerances are computed by adding a safety factor of 3/4 to this base tolerance.\n\nThe output of this file is a .npy file corresponding to each dtype, containing a {size: safety_factor * base_tolerances} dict.\n\nNote: The script may take a long time for a high number of num_iters, so it may be useful to only run the script for one dtype at a time. Modify `dtype_to_ref_dtypes` accordingly.\n\nTo run: python tools/generate_validation_tolerances.py\nTo load the files:\n ```\n import numpy as np\n tol_dict = np.load(file_name.npy, allow_pickle=True).item()","source_hash":"e11585f0ec672f95b20b5c0f544f1ab470a89899391aff47b61ed684e120b193","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/codediff/codediff.py","uri":"program://Fuser/file/tools/codediff/codediff.py","kind":"file","name":"tools/codediff/codediff.py","path":"tools/codediff/codediff.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nFind corresponding .cu files for matching tests, even when new tests are\nintroduced between two commits. Diffs are displayed and the return value is the\nnumber of mismatched corresponding tests.\n\nTests are skipped if they produce different numbers of .cu files, or if they\nexist in only one of the given runs.\n\nExample usage:\n python tools/diff_codegen_nvfuser_tests.py \\\n codegen_comparison/{$commit1,$commit2}/binary_tests\n\"\"\"\n\nfrom dataclasses import asdict, dataclass, field, InitVar\nimport difflib\nfrom enum import Enum\nimport os\nimport re","source_hash":"4f6082cbbdb88190f7597c5dceb9095f066eed1899358bbe39e72f8021ca2ad1","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/codediff/diff_report.py","uri":"program://Fuser/file/tools/codediff/diff_report.py","kind":"file","name":"tools/codediff/diff_report.py","path":"tools/codediff/diff_report.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nFind corresponding .cu files for matching tests, even when new tests are\nintroduced between two commits. Diffs are displayed and the return value is the\nnumber of mismatched corresponding tests.\n\nTests are skipped if they produce different numbers of .cu files, or if they\nexist in only one of the given runs.\n\nExample usage:\n python tools/diff_codegen_nvfuser_tests.py \\\n codegen_comparison/{$commit1,$commit2}/binary_tests\n\"\"\"\n\nimport os\n\nfrom codediff import TestRun, TestDifferences\n\nif __name__ == \"__main__\":","source_hash":"19c985eb63ab33ec27d5c174ee2fd026718a04edd76beeed386c2465946602c0","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/examples/repro.py","uri":"program://Fuser/file/tools/examples/repro.py","kind":"file","name":"tools/examples/repro.py","path":"tools/examples/repro.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nT0 = fd.define_tensor(symbolic_sizes=[-1], contiguous=[True], dtype=DataType.Float)\nT1 = fd.define_tensor(symbolic_sizes=[-1], contiguous=[True], dtype=DataType.Float)\nT2 = fd.define_tensor(symbolic_sizes=[-1, -1], contiguous=[True, True], dtype=DataType.Half)\nT3 = fd.ops.broadcast_in_dim(T0, output_shape=[1, 1024, 768], broadcast_dims=[2])\nT4 = fd.ops.broadcast_in_dim(T1, output_shape=[1, 1024, 768], broadcast_dims=[2])\nT5 = fd.ops.view(T2, original_shape=[1024, 768], new_shape=[1, 1024, 768])\nT6 = fd.ops.cast(T5, dtype=DataType.Float)\nS7 = fd.define_scalar(0.500000)\nT8 = fd.ops.mul(T6, S7)\nS9 = fd.define_scalar(0.707107)\nT10 = fd.ops.mul(T6, S9)\nT11 = fd.ops.erf(T10)\nS12 = fd.define_scalar(1.00000)\nT13 = fd.ops.add(T11, S12)\nT14 = fd.ops.mul(T8, T13)\nT15 = fd.ops.cast(T14, dtype=DataType.Half)\nT16 = fd.ops.cast(T15, dtype=DataType.Float)\nT17, T18 = fd.ops.var_mean(T16, dims=[2], correction=0, keepdim=False)","source_hash":"e009233f02e76811949c562c899650eea890682c90a6d39743ad629e546b8031","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/examples/repro.cpp","uri":"program://Fuser/file/tools/examples/repro.cpp","kind":"file","name":"tools/examples/repro.cpp","path":"tools/examples/repro.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nT0 = fd.define_tensor(symbolic_sizes=[-1], contiguous=[True], dtype=DataType.Float)\nT1 = fd.define_tensor(symbolic_sizes=[-1], contiguous=[True], dtype=DataType.Float)\nT2 = fd.define_tensor(symbolic_sizes=[-1, -1], contiguous=[True, True], dtype=DataType.Half)\nT3 = fd.ops.broadcast_in_dim(T0, output_shape=[1, 1024, 768], broadcast_dims=[2])\nT4 = fd.ops.broadcast_in_dim(T1, output_shape=[1, 1024, 768], broadcast_dims=[2])\nT5 = fd.ops.view(T2, original_shape=[1024, 768], new_shape=[1, 1024, 768])\nT6 = fd.ops.cast(T5, dtype=DataType.Float)\nS7 = fd.define_scalar(0.500000)\nT8 = fd.ops.mul(T6, S7)\nS9 = fd.define_scalar(0.707107)\nT10 = fd.ops.mul(T6, S9)\nT11 = fd.ops.erf(T10)\nS12 = fd.define_scalar(1.00000)\nT13 = fd.ops.add(T11, S12)\nT14 = fd.ops.mul(T8, T13)\nT15 = fd.ops.cast(T14, dtype=DataType.Half)\nT16 = fd.ops.cast(T15, dtype=DataType.Float)\nT17, T18 = fd.ops.var_mean(T16, dims=[2], correction=0, keepdim=False)","source_hash":"e009233f02e76811949c562c899650eea890682c90a6d39743ad629e546b8031","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/env-config/options_loader.py","uri":"program://Fuser/file/tools/env-config/options_loader.py","kind":"file","name":"tools/env-config/options_loader.py","path":"tools/env-config/options_loader.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#!/usr/bin/env python3\n# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nLoad environment options from YAML configuration.\n\nThis module provides a loader for env_options.yaml that replaces the\nhardcoded Python definitions in configure_env.py.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport yaml\nfrom pathlib import Path\nfrom dataclasses import dataclass, field\nfrom typing import Literal\n\n\n@dataclass","source_hash":"03b87b953d9828c1cecf8f91d4058a0e9b4f9da9403eea83b5c484589c3cbd9c","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/env-config/curses_ui.py","uri":"program://Fuser/file/tools/env-config/curses_ui.py","kind":"file","name":"tools/env-config/curses_ui.py","path":"tools/env-config/curses_ui.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#!/usr/bin/env python3\n# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nCurses-based TUI for nvFuser environment configuration.\nProvides a ccmake-like interface for navigating and configuring options.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport curses\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from configure_env import EnvVarConfig\n\nfrom configure_env import CATEGORY_NAMES\n\n","source_hash":"694f28b0f51df4f53a502365ea52e8d88cb4657915355e73e3dbc5afe1b60a57","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/env-config/configure_env.py","uri":"program://Fuser/file/tools/env-config/configure_env.py","kind":"file","name":"tools/env-config/configure_env.py","path":"tools/env-config/configure_env.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#!/usr/bin/env python3\n# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"\nInteractive nvFuser Environment Configuration Tool\n\nThis tool provides an interactive interface (similar to ccmake) for configuring\nnvFuser environment variables. It helps users set up debug flags, feature toggles,\nand runtime options without needing to remember complex NVFUSER_* variable names.\n\nUsage:\n python tools/configure_env.py # Interactive TUI mode\n python tools/configure_env.py --simple # Simple prompt mode\n python tools/configure_env.py --generate-script # Generate shell script\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse","source_hash":"ae8f01c7980f09e16cf6b8efabbd5577b3a1a2ca22118696553e7c685642de07","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/linter/adapters/clangtidy_linter.py","uri":"program://Fuser/file/tools/linter/adapters/clangtidy_linter.py","kind":"file","name":"tools/linter/adapters/clangtidy_linter.py","path":"tools/linter/adapters/clangtidy_linter.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport sysconfig\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, List, NamedTuple, Optional, Pattern\n\n# Nvfuser directory root\nresult = subprocess.run(\n [\"git\", \"rev-parse\", \"--show-toplevel\"],\n stdout=subprocess.PIPE,\n check=True,\n)","source_hash":"9dc2215881ef48f00a9225fae77de3a9fa7fd193e5cd271fb43102ddf3572368","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/linter/adapters/clangformat_linter.py","uri":"program://Fuser/file/tools/linter/adapters/clangformat_linter.py","kind":"file","name":"tools/linter/adapters/clangformat_linter.py","path":"tools/linter/adapters/clangformat_linter.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, List, NamedTuple, Optional\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"","source_hash":"ab7a752d0c1a1bbc7c9d82a565f3e7d162264f94767eaf61c434b7b41372ea7c","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/linter/adapters/mypy_linter.py","uri":"program://Fuser/file/tools/linter/adapters/mypy_linter.py","kind":"file","name":"tools/linter/adapters/mypy_linter.py","path":"tools/linter/adapters/mypy_linter.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import argparse\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, Dict, List, NamedTuple, Optional, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):","source_hash":"949699ebe60f63f110fdf4c2e95477b56344b65788b1f121d9d6ab2de29e95da","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/linter/adapters/black_linter.py","uri":"program://Fuser/file/tools/linter/adapters/black_linter.py","kind":"file","name":"tools/linter/adapters/black_linter.py","path":"tools/linter/adapters/black_linter.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import argparse\nimport concurrent.futures\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional, BinaryIO\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"","source_hash":"4cee2a9f99e26e412bcba844381c1eebf4a81fde53180c46adf8320e2b546eea","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/linter/adapters/grep_linter.py","uri":"program://Fuser/file/tools/linter/adapters/grep_linter.py","kind":"file","name":"tools/linter/adapters/grep_linter.py","path":"tools/linter/adapters/grep_linter.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\nGeneric linter that greps for a pattern and optionally suggests replacements.\n\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, List, NamedTuple, Optional\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n","source_hash":"b3f127c19e71d2af5a0daeb196969f74280a12ff7a669b425d92640865d1fc54","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/linter/adapters/exec_linter.py","uri":"program://Fuser/file/tools/linter/adapters/exec_linter.py","kind":"file","name":"tools/linter/adapters/exec_linter.py","path":"tools/linter/adapters/exec_linter.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\nEXEC: Ensure that source files are not executable.\n\"\"\"\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\n\nfrom enum import Enum\nfrom typing import NamedTuple, Optional\n\nLINTER_CODE = \"EXEC\"\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"\n","source_hash":"5907352556cf51f7acca69c1855941ed922cedd510e7bc5021f5d937b3b56de7","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/linter/adapters/pip_init.py","uri":"program://Fuser/file/tools/linter/adapters/pip_init.py","kind":"file","name":"tools/linter/adapters/pip_init.py","path":"tools/linter/adapters/pip_init.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\nInitializer script that installs stuff to pip.\n\"\"\"\nimport os\nimport argparse\nimport logging\nimport subprocess\nimport sys\nimport time\n\nfrom typing import List\n\n\ndef run_command(args: List[str]) -> \"subprocess.CompletedProcess[bytes]\":\n logging.debug(\"$ %s\", \" \".join(args))\n start_time = time.monotonic()\n try:\n return subprocess.run(args, check=True)\n finally:\n end_time = time.monotonic()\n logging.debug(\"took %dms\", (end_time - start_time) * 1000)","source_hash":"3c98724f8b55f84bb7c05e2b64aa8bc8a00a0c2a65b25540406421ec3a85138a","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/linter/adapters/flake8_linter.py","uri":"program://Fuser/file/tools/linter/adapters/flake8_linter.py","kind":"file","name":"tools/linter/adapters/flake8_linter.py","path":"tools/linter/adapters/flake8_linter.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import argparse\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport time\nfrom enum import Enum\nfrom typing import Any, Dict, List, NamedTuple, Optional, Set, Pattern\n\n\nIS_WINDOWS: bool = os.name == \"nt\"\n\n\ndef eprint(*args: Any, **kwargs: Any) -> None:\n print(*args, file=sys.stderr, flush=True, **kwargs)\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"","source_hash":"3bbe0a0fc27ef5e42d7f736027735adc794b00cf5532d29a8fb342c8d87d46ad","truncated":false} {"repo_id":"Fuser","entity_id":"file:tools/linter/adapters/newlines_linter.py","uri":"program://Fuser/file/tools/linter/adapters/newlines_linter.py","kind":"file","name":"tools/linter/adapters/newlines_linter.py","path":"tools/linter/adapters/newlines_linter.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\nNEWLINE: Checks files to make sure there are no trailing newlines.\n\"\"\"\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\n\nfrom enum import Enum\nfrom typing import NamedTuple, Optional\n\nNEWLINE = 10 # ASCII \"\\n\"\nLINTER_CODE = \"NEWLINE\"\n\n\nclass LintSeverity(str, Enum):\n ERROR = \"error\"\n WARNING = \"warning\"\n ADVICE = \"advice\"\n DISABLED = \"disabled\"","source_hash":"2c6de3301ceaf1dffb02fff6d4d6dc4a0ed4ff8b1bba82953886cf9d2be0ba0e","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_batchnorm_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_batchnorm_bwd.py","kind":"file","name":"benchmarks/python/test_batchnorm_bwd.py","path":"benchmarks/python/test_batchnorm_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_bwd_nvf_benchmark, norm_bwd_baseline_benchmark\nfrom .core import DEFAULT_EXECUTORS\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_bwd_nvf_benchmark(\n benchmark,","source_hash":"a3f518d903c06c1fe97bcc8a340d77be788797383d9a369f320b3df4d66e0704","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_silu_mul_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_silu_mul_fwd.py","kind":"file","name":"benchmarks/python/test_silu_mul_fwd.py","path":"benchmarks/python/test_silu_mul_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import silu_mul\n\n\ndef silu_mul_fwd_fusion(fd: FusionDefinition, dtype: DataType):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n T1 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)","source_hash":"4d8f0e634311a56821d7b545bc707c063f1e11b06b48a12b84f6e24e62075358","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_gelu_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_gelu_fwd.py","kind":"file","name":"benchmarks/python/test_gelu_fwd.py","path":"benchmarks/python/test_gelu_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import gelu\n\n\ndef gelu_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n input = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n bias = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n if dtype in PROMOTE_DTYPES:","source_hash":"75b06dbb6abc59d14857581dec18deb385ce5d94f5c77f3f32e107dc272480b1","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_dropout_layernorm_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_dropout_layernorm_bwd.py","kind":"file","name":"benchmarks/python/test_dropout_layernorm_bwd.py","path":"benchmarks/python/test_dropout_layernorm_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_layernorm\n\n\ndef dropout_layernorm_bwd_fusion(\n fd: FusionDefinition, dtype: DataType, dropout_p: float","source_hash":"3788276db1818e20d07d3b6d0685aa9f2bad06cec01af931b61b76bf3be5c7fd","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_benchmarking_setupy.py","uri":"program://Fuser/file/benchmarks/python/test_benchmarking_setupy.py","kind":"file","name":"benchmarks/python/test_benchmarking_setupy.py","path":"benchmarks/python/test_benchmarking_setupy.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":13,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\n\n\ndef test_env_vars_are_set():\n for var in [\n \"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\",\n \"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\",\n ]:\n assert os.environ[var] == \"1\"","source_hash":"0a8a6a5f852d5c0a6fd56a4e513606c8a9970bcc0e94c9e0977eb8bc74718a75","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_rmsnorm_add_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_rmsnorm_add_fwd.py","kind":"file","name":"benchmarks/python/test_rmsnorm_add_fwd.py","path":"benchmarks/python/test_rmsnorm_add_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n with_executor,\n DEFAULT_EXECUTORS,\n check_module_available,\n)\nimport torch\nfrom .global_params import FLOAT_DTYPES, BENCHMARK_CONFIG\nfrom .torch_ops import rmsnorm_add\nimport itertools\nfrom random import sample\nfrom typing import List, Tuple\n\nif check_module_available(\"flashinfer\"):\n from flashinfer import fused_add_rmsnorm\n","source_hash":"97d2303f237539385d3a74041f54c0537965f0686e792c5d35b9ae83cff8613c","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/conftest.py","uri":"program://Fuser/file/benchmarks/python/conftest.py","kind":"file","name":"benchmarks/python/conftest.py","path":"benchmarks/python/conftest.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .core import BENCHMARK_CONFIG\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\nimport os\n\nORIGINAL_ENV_VARS = {}\n\n\ndef pytest_sessionstart(session):\n for var, value in [\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_TUNING\", \"1\"),\n (\"TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS\", \"1\"),\n ]:\n ORIGINAL_ENV_VARS[var] = os.environ.get(var)\n os.environ[var] = value\n\n\ndef pytest_sessionfinish(session):","source_hash":"5cf742bdc3fd803279f8891179bbb415b2809c8cb01cbdb2fa82770ef6afce53","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_scatter_reduce.py","uri":"program://Fuser/file/benchmarks/python/test_scatter_reduce.py","kind":"file","name":"benchmarks/python/test_scatter_reduce.py","path":"benchmarks/python/test_scatter_reduce.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\n\nimport torch\n\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nfrom .global_params import FLOAT_DTYPES\nfrom .torch_ops import scatter_reduce\n\n# (top_k, hidden) configurations seen in models.\nTEST_CONFIGS = [\n (8, 7168), # deepseek r1\n]","source_hash":"36771f2fe91ff8589f613c8cabb7d8f5e444e852f5cd76f1fbe0344cebaecc55","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_cat.py","uri":"program://Fuser/file/benchmarks/python/test_cat.py","kind":"file","name":"benchmarks/python/test_cat.py","path":"benchmarks/python/test_cat.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom .core import run_benchmark, with_executor\n\n# These tests are sourced from automation added into thunder.\n#\n# To recreate:\n# * Use the tfogal/benchmarking-dumps branch in thunder.\n# * Pass nv_store_fusion_inputs=True to your thunderfx call\n# * Disable the torch.compile executor in the thunderfx call, which ensures\n# that all fusions go to nvFuser.\n# * After running the network of interest, invoke thunder.tests.dump.traces()\n# This particular file is aimed at concatenation operations, so it is an\n# agglomeration of cases that included `torch.cat` in the fusion.\n\n\ndef cat_qwen2_fwd_11(t17353, t17351, cos_2, sin_2, query_states_1, key_states_1):","source_hash":"c93e696da76188df281791334df5846a7940fd4ba712aaa60f58ec4f6109ff90","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/rope_ops.py","uri":"program://Fuser/file/benchmarks/python/rope_ops.py","kind":"file","name":"benchmarks/python/rope_ops.py","path":"benchmarks/python/rope_ops.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\n\nfrom torch import nn\n\nfrom typing import Tuple\nfrom functools import partial\n\nfrom .model_configs import configs\n\nSEQ_LENGTHS = (\n 1024,\n 2048,\n 4096,\n 8192,\n 12288,\n 16384,\n 20480,\n 24576,","source_hash":"6b777be033bbf4f6108f2bfe3354709f13458204b9276ef176ab6a95750df64b","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_broadcast_add_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_broadcast_add_fwd.py","kind":"file","name":"benchmarks/python/test_broadcast_add_fwd.py","path":"benchmarks/python/test_broadcast_add_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef bcast_add_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n bcast_axis: int,\n contiguous: bool,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False, stride_order=[0]\n )\n stride_order = [0, 1] if not contiguous else [1, 0]","source_hash":"024d8923c046ef2468d1c9c6e1937abf3816fb2874e5542f303bed3345fb670d","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/layers_for_inference_benchmark.py","uri":"program://Fuser/file/benchmarks/python/layers_for_inference_benchmark.py","kind":"file","name":"benchmarks/python/layers_for_inference_benchmark.py","path":"benchmarks/python/layers_for_inference_benchmark.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD 3-Clause license found in the\n# LICENSE file in the root directory of this source tree.\n#\n# NOTE: `down_size`, and `pack_uint4` are copied from PyTorch's test code.\n#\n# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# NOTE: `pytorch_nvfp4_quantize` and `linear_to_swizzled_128_4` are copied from NVIDIA's Fuser's test code.\n#\n# Pulled from the lightning-thunder repo. Reference:\n# https://github.com/Lightning-AI/lightning-thunder/blob/4d3a3c3a7481efdc6a23cdeea99c3ffd31af5e78/thunder/benchmarks/layers_for_inference_benchmark.py\n\n# fmt: off\n\nfrom __future__ import annotations\nfrom typing import TYPE_CHECKING","source_hash":"8024f91f4623a11fa7d6c6fd2cf882d742fb706390af48ec3b6e3ff991313b19","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/cross_entropy_loss.py","uri":"program://Fuser/file/benchmarks/python/cross_entropy_loss.py","kind":"file","name":"benchmarks/python/cross_entropy_loss.py","path":"benchmarks/python/cross_entropy_loss.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\n\nfrom .model_configs import configs\n\n\nclass CrossEntropyLossBase:\n def __init__(self, model_name, dtype):\n self.config = configs[model_name]()\n self.dtype = dtype\n\n def model(self):\n raise NotImplementedError\n\n def inputs(self):\n hidden_states = torch.randn(\n self.config.batch_size,\n self.config.seq_len,\n self.config.hidden_size,","source_hash":"d2e4cc8df1e83e0d6cff95355d02b17edd433d4f22b7298f6a1dc88949541546","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_instancenorm_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_instancenorm_bwd.py","kind":"file","name":"benchmarks/python/test_instancenorm_bwd.py","path":"benchmarks/python/test_instancenorm_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_bwd_nvf_benchmark, norm_bwd_baseline_benchmark\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_bwd_nvf_benchmark(\n benchmark,\n size: tuple,","source_hash":"e633a66f3167934af57e920646a245098f36e5e5d81b16ab9445ff957bdac4bb","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/benchmark_inference.py","uri":"program://Fuser/file/benchmarks/python/benchmark_inference.py","kind":"file","name":"benchmarks/python/benchmark_inference.py","path":"benchmarks/python/benchmark_inference.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\"\"\"Inference benchmark focusing on throughput and latency metrics of prefill and decode phases.\n\nAutoModelForCausalLM from Hugging Face transformers is used for model implementation.\n\nKey metrics:\n- Throughput (tokens/second)\n- Latency (ms/token)\n- Time to First Token (TTFT)\n- Time Between Output Tokens (TBOT)\n\nPulled from the lightning-thunder repo. Reference:\nhttps://github.com/Lightning-AI/lightning-thunder/blob/4d3a3c3a7481efdc6a23cdeea99c3ffd31af5e78/thunder/benchmarks/benchmark_inference.py\n\"\"\"\n\n# fmt: off\n\nfrom __future__ import annotations","source_hash":"580e46e85c5aea50adafd938dcd0bb182a805b821ba4fe02e71460f95e1a5acd","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_embedding.py","uri":"program://Fuser/file/benchmarks/python/test_embedding.py","kind":"file","name":"benchmarks/python/test_embedding.py","path":"benchmarks/python/test_embedding.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\n\nimport torch\n\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nfrom .global_params import FLOAT_DTYPES\nfrom .torch_ops import embedding\n\n\n# (vocab, hidden) configurations seen in models.\nEMBEDDING_CONFIGS = [\n (152064, 3584), # hf_qwen2","source_hash":"fbfd7b4fa120c45ccab591156c2e35833f004911bb880a7f7b4377362640c058","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_nanogpt_attn_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_nanogpt_attn_fwd.py","kind":"file","name":"benchmarks/python/test_nanogpt_attn_fwd.py","path":"benchmarks/python/test_nanogpt_attn_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import nanogpt_attn\n\n\n# Fusion from nanogpt attention module\n# The nvFuser defintion only includes the non-matmul computation (masked_fill + softmax + dropout)\ndef nanogpt_attn_fwd_fusion(\n fd: FusionDefinition, dtype: DataType, head_size: int, dropout_p: float\n):\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],\n contiguity=[True, True, True, True],\n dtype=dtype,","source_hash":"470558566fe4a4618b42aa671de8b565da8e0fd83d22c8d950e3c966112e799a","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_huggingface_attn_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_huggingface_attn_fwd.py","kind":"file","name":"benchmarks/python/test_huggingface_attn_fwd.py","path":"benchmarks/python/test_huggingface_attn_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import huggingface_attn\n\n\n# Fusion from huggingface attention implementation.\n# The nvFuser defintion only includes the non-matmul computation (add + reshape + softmax + dropout)\ndef huggingface_attn_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n dropout_p: float,\n):\n T0 = fd.define_tensor(\n shape=[-1, -1, -1, -1],","source_hash":"0d01be5f53aac64f021291ead4360f3bdf6168c867851746817444639c36284d","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_reduction_epilogue.py","uri":"program://Fuser/file/benchmarks/python/test_reduction_epilogue.py","kind":"file","name":"benchmarks/python/test_reduction_epilogue.py","path":"benchmarks/python/test_reduction_epilogue.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n# test the influence of epilogue on the performance of reduction.\n# current reduction scheduler only allows epilogue to be fused with outer reduction without post reduction broadcast.\n# So, in this test, only outer reduction is tested. [reduction_axis] is kept to allow the extension to inner reduction.\n\n\ndef reduction_epilogue_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n reduction_axis: int,\n) -> None:","source_hash":"c32c13e741d9ce12b3389ad13cb452c3059307cfd179e47c8dfdcaade4eaaa96","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_rmsnorm_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_rmsnorm_fwd.py","kind":"file","name":"benchmarks/python/test_rmsnorm_fwd.py","path":"benchmarks/python/test_rmsnorm_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import rmsnorm\n\n\ndef rmsnorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n eps: float = 1e-5,\n):\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )","source_hash":"49c1adfee1ea3f57d1f67febcf2445c2eadb21648bf20267e6565d40d6961910","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/torch_ops.py","uri":"program://Fuser/file/benchmarks/python/torch_ops.py","kind":"file","name":"benchmarks/python/torch_ops.py","path":"benchmarks/python/torch_ops.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\nimport torch.nn.functional as F\n\n\ndef dropout_layernorm(inputs: list):\n inp1, inp2, weights, bias, dropout_p = inputs\n return F.layer_norm(\n inp2 + torch.nn.functional.dropout(inp1, p=dropout_p),\n normalized_shape=inp1.shape[1:],\n weight=weights,\n bias=bias,\n )\n\n\ndef dropout_rmsnorm(inputs: list):\n inp1, inp2, weights, dropout_p = inputs\n x = inp2 + F.dropout(inp1, p=dropout_p)","source_hash":"8a926c7ff1e6c94c87165d7cbf6150be580d89d780c23db07d5d4a3ba1d25298","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_rope.py","uri":"program://Fuser/file/benchmarks/python/test_rope.py","kind":"file","name":"benchmarks/python/test_rope.py","path":"benchmarks/python/test_rope.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .core import run_benchmark, with_executor, unary_bwd_torch, clear_dynamo_cache\n\nfrom .rope_ops import rope_setup, SEQ_LENGTHS\n\n\n@pytest.mark.parametrize(\n \"variation\",\n [\n \"llama_2_7b_hf\",\n \"llama_3_8B\",\n \"hf_qwen2\",\n \"hf_phi3\",\n \"hf_mistral_nemo\",\n \"litgpt-gemma-2-9b\",\n \"litgpt-mistral-7b\",\n \"litgpt-meta-llama-3-8B\",\n \"litgpt-phi3.5-mini\",","source_hash":"635d88ff25e8a065f4d4efd219afbbfa00bc3439f2ce81001eea217e59f6e502","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_scale_bias_relu_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_scale_bias_relu_bwd.py","kind":"file","name":"benchmarks/python/test_scale_bias_relu_bwd.py","path":"benchmarks/python/test_scale_bias_relu_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import scale_bias_relu\n\n\ndef sbr_bwd_fusion(\n fd: FusionDefinition,","source_hash":"396d0a23fa9dd6a57e7f20b6e7a2799ceb94ebb6a6392502ada22e3338c60657","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_silu_mul_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_silu_mul_bwd.py","kind":"file","name":"benchmarks/python/test_silu_mul_bwd.py","path":"benchmarks/python/test_silu_mul_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import silu_mul\n\n\ndef silu_mul_bwd_fusion(fd: FusionDefinition, dtype: DataType):\n T0 = fd.define_tensor(","source_hash":"ae56be6ded2c9ee256475b1ad8f6bc2934524add3313616fab9eeb1fb7da5109","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/core.py","uri":"program://Fuser/file/benchmarks/python/core.py","kind":"file","name":"benchmarks/python/core.py","path":"benchmarks/python/core.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom collections.abc import Iterable\nimport pytest_benchmark\nimport torch\nfrom typing import List, Callable, Union\nimport numpy as np\nfrom nvfuser_direct import FusionDefinition, PythonProfiler\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\nfrom nvfuser_direct.benchmark_utils import FusionProfileTimer, CuptiTimer\nimport warnings\nimport thunder\nfrom thunder.executors.nvfuserex import nvfuserex\nimport importlib.util\n\n# These variables can be overwritten through CLI commands\n# --benchmark-rounds=rounds --benchmark-warmup-rounds=warmup_rounds\n# --benchmark-num-inputs=num_inputs\nBENCHMARK_CONFIG = {\n \"rounds\": 10,","source_hash":"e96004206f31a5e8d94b04e311a17e3f0bfb3f4c5c17ea7ad5952c0f299feea9","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_softmax_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_softmax_bwd.py","kind":"file","name":"benchmarks/python/test_softmax_bwd.py","path":"benchmarks/python/test_softmax_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nimport numpy as np\nfrom .torch_ops import softmax\n\n\ndef softmax_bwd_fusion(\n fd: FusionDefinition, dtype: DataType, reduction_axis: int","source_hash":"e1c6c85334ae83b4451a8ece69991d26b0fc42a3243aeb6477c4c06eeaca957d","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_cross_entropy_loss.py","uri":"program://Fuser/file/benchmarks/python/test_cross_entropy_loss.py","kind":"file","name":"benchmarks/python/test_cross_entropy_loss.py","path":"benchmarks/python/test_cross_entropy_loss.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\n\nimport torch\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom .core import (\n run_benchmark,\n with_executor,\n unary_bwd_torch,\n clear_dynamo_cache,\n check_module_available,\n)\nfrom .cross_entropy_loss import (\n cross_entropy_loss_setup,\n SyntheticMiniModel,\n)\nfrom .torch_ops import cross_entropy as torch_cross_entropy_fwd\n\n","source_hash":"615532b5d3e84de8f3270502f2377cebfccde9427c057aa88222ba15c13216d9","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/normalization.py","uri":"program://Fuser/file/benchmarks/python/normalization.py","kind":"file","name":"benchmarks/python/normalization.py","path":"benchmarks/python/normalization.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom .global_params import PROMOTE_DTYPES\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nimport torch\nfrom .core import run_benchmark, unary_bwd_torch, clear_dynamo_cache, with_executor\nimport numpy as np\nfrom functools import reduce\n\n\ndef norm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n norm: str,\n num_dims: int,\n channels_last: bool,\n eps: float = 1e-5,\n momentum: float = 0.01,\n) -> None:","source_hash":"948013f92935b64a717a0f9a1050520a46f2cfbdcb676d62680fc5fa20365e25","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/__init__.py","uri":"program://Fuser/file/benchmarks/python/__init__.py","kind":"file","name":"benchmarks/python/__init__.py","path":"benchmarks/python/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":3,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause","source_hash":"228b8897cd383257646bf9e71e3f314eb5c0f4606e62926359adf565b2e9664d","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_pointwise_mul.py","uri":"program://Fuser/file/benchmarks/python/test_pointwise_mul.py","kind":"file","name":"benchmarks/python/test_pointwise_mul.py","path":"benchmarks/python/test_pointwise_mul.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef pointwise_mul_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)\n T2 = fd.ops.mul(T0, T0)","source_hash":"9ec21ff076e00259c54ca25e589cfe059cd0014e8a9039244ef6cdcdce74df0f","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_batchnorm_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_batchnorm_fwd.py","kind":"file","name":"benchmarks/python/test_batchnorm_fwd.py","path":"benchmarks/python/test_batchnorm_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_fwd_nvf_benchmark, norm_fwd_baseline_benchmark\nfrom .core import DEFAULT_EXECUTORS\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_batchnorm_fwd_nvf_benchmark(\n benchmark,","source_hash":"302421ae331c310ceac218ecf265478a7ee883d909def27d7bfd8225a65a60ce","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_reduction.py","uri":"program://Fuser/file/benchmarks/python/test_reduction.py","kind":"file","name":"benchmarks/python/test_reduction.py","path":"benchmarks/python/test_reduction.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef reduction_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n reduction_axis: int,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n if dtype in PROMOTE_DTYPES:\n T0 = fd.ops.cast(T0, dtype=DataType.Float)","source_hash":"eeb2a64c3468f47f8c4e79a991ac442cbc4ffbb2679101386f2e26ac26e22d35","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_groupnorm_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_groupnorm_fwd.py","kind":"file","name":"benchmarks/python/test_groupnorm_fwd.py","path":"benchmarks/python/test_groupnorm_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef get_n_groups(C):\n # start num_groups from 1 and increase to 32 at max\n # 32 is a widely used value for num_groups\n # it doesn't make sense to use num_groups > C\n num_groups = 1\n while num_groups * 2 <= 32 and C % (num_groups * 2) == 0:\n num_groups *= 2\n return num_groups\n\n","source_hash":"3cfdff05b8f25e6094b238a67f13967849f0de39cfdabd2973aedbeddc55c54e","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_dropout_rmsnorm_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_dropout_rmsnorm_bwd.py","kind":"file","name":"benchmarks/python/test_dropout_rmsnorm_bwd.py","path":"benchmarks/python/test_dropout_rmsnorm_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_rmsnorm\n\n\ndef dropout_rmsnorm_bwd_fusion(\n fd: FusionDefinition,","source_hash":"0501d66d223eaf8dfc5914be20df775bab9a4c191a3d1ebc2494dd38df7b3877","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/benchmark_overlap.py","uri":"program://Fuser/file/benchmarks/python/benchmark_overlap.py","kind":"file","name":"benchmarks/python/benchmark_overlap.py","path":"benchmarks/python/benchmark_overlap.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\nimport pytest\nimport torch\nimport nvfuser_direct as nvfuser\nfrom nvfuser_direct import FusionDefinition, CommunicatorBackend\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import BENCHMARK_CONFIG, clear_l2_cache\n\n# Run command:\n# export NVFUSER_BUILD_WITH_UCC=1\n# pip install --no-build-isolation -e python -v\n# mpirun -np 1 pytest benchmarks/python/benchmark_overlap.py --with-mpi\n\n\nclass CUDAEventTimer:\n \"\"\"Custom CUDA event-based timer for accurate GPU timing.\n","source_hash":"0a087c82760b6b87a4b5a93ef71330645e9f2f20c5c4056ea764ed127601fcb3","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_gelu_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_gelu_bwd.py","kind":"file","name":"benchmarks/python/test_gelu_bwd.py","path":"benchmarks/python/test_gelu_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import gelu\n\n\ndef gelu_bwd_fusion(\n fd: FusionDefinition,","source_hash":"9aa1462b3c712f8a9e9d5a8362b374eb4e4ccaa3b8061f1b8869c727146cabea","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_softmax_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_softmax_fwd.py","kind":"file","name":"benchmarks/python/test_softmax_fwd.py","path":"benchmarks/python/test_softmax_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import softmax\n\n\ndef softmax_fwd_fusion(\n fd: FusionDefinition, dtype: DataType, reduction_axis: int\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=dtype,\n is_cpu=False,","source_hash":"dfc3976fff2c9bcdfe20715bc99b1799f2af2c9e0b3faf23626ba2d2dbaeca00","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_gelu_bwd_reduction.py","uri":"program://Fuser/file/benchmarks/python/test_gelu_bwd_reduction.py","kind":"file","name":"benchmarks/python/test_gelu_bwd_reduction.py","path":"benchmarks/python/test_gelu_bwd_reduction.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\n\n\ndef gelu_bwd_reduction_fusion(\n fd: FusionDefinition, dtype: DataType, reduction_axis: int\n) -> None:\n input = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )\n grad = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )","source_hash":"f1327b681871f3a2db047a001da7f8d65f76828ee6cc04056da447f13a143864","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/model_configs.py","uri":"program://Fuser/file/benchmarks/python/model_configs.py","kind":"file","name":"benchmarks/python/model_configs.py","path":"benchmarks/python/model_configs.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom functools import partial\n\n\ndef llama_hf_cfg(config_str):\n class Config:\n def __init__(\n self, n_head, head_size, n_query_groups, rope_n_elem, batches, seq_length\n ):\n self.n_head = n_head\n self.head_size = head_size\n self.n_query_groups = n_query_groups\n self.rope_n_elem = rope_n_elem\n self.batches = batches\n self.seq_length = seq_length\n\n configs = {}\n configs[\"llama_2_7b_hf\"] = Config(\n n_head=32,","source_hash":"96e626b940e9570ed599803b9e58b8902ffe3aff3db9ee799233657068c5dfd9","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_layernorm_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_layernorm_bwd.py","kind":"file","name":"benchmarks/python/test_layernorm_bwd.py","path":"benchmarks/python/test_layernorm_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import layernorm\n\n\ndef layernorm_bwd_fusion(\n fd: FusionDefinition,","source_hash":"390e673a86f9c1d90d4d64edab5d9932810f308af04deeb06833854db8832b05","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_llama4_inference.py","uri":"program://Fuser/file/benchmarks/python/test_llama4_inference.py","kind":"file","name":"benchmarks/python/test_llama4_inference.py","path":"benchmarks/python/test_llama4_inference.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2026-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom .benchmark_inference import (\n InferenceBenchmarkConfig,\n InferenceBenchmark,\n _register_nvfp4_ops,\n)\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\n\n\n# NOTE: for some reason, changing the order of nvfp4 and cudagraph parameter breaks thunder benchmark. I suspect there's something with thunder's cache.\n@pytest.mark.parametrize(\"input_length\", [4096])\n@pytest.mark.parametrize(\"output_length\", [4])\n@pytest.mark.parametrize(\"mode\", [\"thunder\", \"inductor\"])\n@pytest.mark.parametrize(\"enable_nvfp4\", [True, False])\n@pytest.mark.parametrize(\"enable_cudagraph\", [False, True])\ndef test_llama4_inference_benchmark(\n benchmark,\n input_length: int,","source_hash":"eddb0808b172e6a198747f249147731453c027dea6ad0c568f8d34f6a1b2195c","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_scale_bias_relu_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_scale_bias_relu_fwd.py","kind":"file","name":"benchmarks/python/test_scale_bias_relu_fwd.py","path":"benchmarks/python/test_scale_bias_relu_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import scale_bias_relu\n\n\ndef sbr_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n):\n T0 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T1 = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n T2 = fd.define_tensor(\n shape=[-1, -1],","source_hash":"d23b9f1c9eb5c42ddf2b7b27f9a6bce6da8e63e5c1285e9fe4184b814b9a4ca6","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_matmul.py","uri":"program://Fuser/file/benchmarks/python/test_matmul.py","kind":"file","name":"benchmarks/python/test_matmul.py","path":"benchmarks/python/test_matmul.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition\nfrom .core import run_benchmark\nimport torch\n\nimport csv\nimport functools\nimport os\n\n\ndef matmul_fusion(fd: FusionDefinition, inputs: list[torch.Tensor]) -> None:\n a = fd.from_pytorch(inputs[0])\n b = fd.from_pytorch(inputs[1])\n out = fd.ops.matmul(a, b)\n fd.add_output(out)\n\n\ndef load_matmul_problems():","source_hash":"d453190d703c026148724a19c57f99c7bc73653bef110f50e35de9820fe786dd","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_layernorm_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_layernorm_fwd.py","kind":"file","name":"benchmarks/python/test_layernorm_fwd.py","path":"benchmarks/python/test_layernorm_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import layernorm\n\n\ndef layernorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,\n eps: float = 1e-5,\n) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=dtype, is_cpu=False\n )","source_hash":"16d98d2281151902ad2704739084722367a7b999208795433b6063b23ca567bb","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_rmsnorm_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_rmsnorm_bwd.py","kind":"file","name":"benchmarks/python/test_rmsnorm_bwd.py","path":"benchmarks/python/test_rmsnorm_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nimport numpy as np\nfrom .torch_ops import rmsnorm\n\n\ndef rmsnorm_bwd_fusion(\n fd: FusionDefinition,","source_hash":"9b5b9f03f4538fac447609a4e1852e9fe34c5ec2bbc65a10cbeb7d396c839110","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_instancenorm_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_instancenorm_fwd.py","kind":"file","name":"benchmarks/python/test_instancenorm_fwd.py","path":"benchmarks/python/test_instancenorm_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES\nfrom .normalization import norm_fwd_nvf_benchmark, norm_fwd_baseline_benchmark\n\n\n@pytest.mark.parametrize(\"size\", generate_input_sizes(dims=4))\n@pytest.mark.parametrize(\"dtype\", FLOAT_DTYPES)\n@pytest.mark.parametrize(\n \"channels_last\",\n [\n pytest.param(True, marks=pytest.mark.outer_persistent),\n pytest.param(False, marks=pytest.mark.inner_persistent),\n ],\n)\ndef test_instancenorm_fwd_nvf_benchmark(\n benchmark,\n size: tuple,","source_hash":"1c1e8df938b7bfc631d76cdbcec5a4e1a62ae43a53faae1e605ae84c9264ad17","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_dropout_layernorm_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_dropout_layernorm_fwd.py","kind":"file","name":"benchmarks/python/test_dropout_layernorm_fwd.py","path":"benchmarks/python/test_dropout_layernorm_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_layernorm\n\n\ndef dropout_layernorm_fwd_fusion(\n fd: FusionDefinition, dtype: DataType, dropout_p: float, eps: float = 1e-5\n) -> None:","source_hash":"27232ca209c015e59ba429b1a6426cf464c9a9435d8cc855416eba424d08f1db","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_nanogpt_attn_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_nanogpt_attn_bwd.py","kind":"file","name":"benchmarks/python/test_nanogpt_attn_bwd.py","path":"benchmarks/python/test_nanogpt_attn_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import nanogpt_attn\n\n\n# Fusion from nanogpt attention module\n# The nvFuser defintion only includes the non-matmul computation (masked_fill + softmax + dropout)\ndef nanogpt_attn_bwd_fusion(","source_hash":"a882e8f9374530c6adba1bb7d73c5a932ff4b7de456f4eb28872674910a50f7f","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_dropout_rmsnorm_fwd.py","uri":"program://Fuser/file/benchmarks/python/test_dropout_rmsnorm_fwd.py","kind":"file","name":"benchmarks/python/test_dropout_rmsnorm_fwd.py","path":"benchmarks/python/test_dropout_rmsnorm_fwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n compute_total_iobytes,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import dropout_rmsnorm\n\n\ndef dropout_rmsnorm_fwd_fusion(\n fd: FusionDefinition,\n dtype: DataType,","source_hash":"671759bef18d966ba1bbc6d355e3a522d9ea81b4997247f667bccee8109ba51d","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_huggingface_attn_bwd.py","uri":"program://Fuser/file/benchmarks/python/test_huggingface_attn_bwd.py","kind":"file","name":"benchmarks/python/test_huggingface_attn_bwd.py","path":"benchmarks/python/test_huggingface_attn_bwd.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import (\n run_benchmark,\n clear_dynamo_cache,\n unary_bwd_torch,\n with_executor,\n DEFAULT_EXECUTORS,\n)\nimport torch\nfrom .global_params import generate_attn_inputs, FLOAT_DTYPES, PROMOTE_DTYPES\nfrom .torch_ops import huggingface_attn\n\n\n# Fusion from huggingface attention implementation\n# The nvFuser defintion only includes the non-matmul computation (add + reshape + softmax + dropout)\ndef huggingface_attn_bwd_fusion(","source_hash":"5516f3ce1b05a579d326b3c6979964b0c82231fcd94ca798f99fd2a5be824846","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/test_transpose.py","uri":"program://Fuser/file/benchmarks/python/test_transpose.py","kind":"file","name":"benchmarks/python/test_transpose.py","path":"benchmarks/python/test_transpose.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom .core import run_benchmark, clear_dynamo_cache, with_executor, DEFAULT_EXECUTORS\nimport torch\nfrom .global_params import generate_input_sizes, FLOAT_DTYPES, PROMOTE_DTYPES\n\n\ndef transpose_fusion_input_smem(\n fd: FusionDefinition,\n dtype: DataType,\n is_copy_transpose: bool,\n axes: list,\n rank: int,\n):\n \"\"\"Single input: the transposed input is read through shared memory.\"\"\"\n shape = [-1] * rank\n contiguity = [True] * rank","source_hash":"d7150c9ccd07a4ad71d87d54c314afa7e698a4ab133bd267c9363c11854f1cf6","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/global_params.py","uri":"program://Fuser/file/benchmarks/python/global_params.py","kind":"file","name":"benchmarks/python/global_params.py","path":"benchmarks/python/global_params.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\nfrom typing import Union, List, Tuple\nfrom nvfuser_direct import DataType\nfrom .core import BENCHMARK_CONFIG\nfrom nvfuser_direct.pytorch_utils import DEVICE_PROPERTIES\nimport itertools\nimport os\nfrom random import sample\n\n# BENCHMARK_MODE = weekly/nightly.\nBENCHMARK_MODE = os.getenv(\"BENCHMARK_MODE\")\nif not BENCHMARK_MODE:\n BENCHMARK_MODE = \"nightly\"\n\n# Datatypes to benchmark\nFLOAT_DTYPES = [torch.float32]\n# Run only one of float16 / bfloat16.\nif DEVICE_PROPERTIES[\"gpu_compute_capability_major\"] >= 8:","source_hash":"b0a8d35825929a496b67479c5542c225820ce696ff5d76d67e5d89042b90bc17","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/host/test_many_segments_host.py","uri":"program://Fuser/file/benchmarks/python/host/test_many_segments_host.py","kind":"file","name":"benchmarks/python/host/test_many_segments_host.py","path":"benchmarks/python/host/test_many_segments_host.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType, PythonProfiler\nfrom ..core import run_benchmark\nimport torch\n\n\ndef many_matmul_fusion(fd: FusionDefinition) -> None:\n x = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n y = fd.define_tensor(\n shape=[-1, -1], contiguity=[True, True], dtype=DataType.Float, is_cpu=False\n )\n a = fd.ops.add(x, y)\n for _ in range(5):\n a_transpose = fd.ops.permute(a, [1, 0])\n matmul_out = fd.ops.matmul(a_transpose, y)\n add_out = fd.ops.add(a_transpose, y)","source_hash":"061026a239f0bc234390fc0fbab846af4af674d7e3191f3678ccb7a9510e4366","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/host/__init__.py","uri":"program://Fuser/file/benchmarks/python/host/__init__.py","kind":"file","name":"benchmarks/python/host/__init__.py","path":"benchmarks/python/host/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":3,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause","source_hash":"42ba09bbb339816dd46109a07ebfd999dbf561ebfbe624942f77de0b0aed53da","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/host/test_many_pointwise_ops_host.py","uri":"program://Fuser/file/benchmarks/python/host/test_many_pointwise_ops_host.py","kind":"file","name":"benchmarks/python/host/test_many_pointwise_ops_host.py","path":"benchmarks/python/host/test_many_pointwise_ops_host.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom nvfuser_direct.pytorch_utils import torch_dtype_to_nvfuser_dtype\nfrom ..core import run_benchmark\nimport torch\nfrom ..global_params import PROMOTE_DTYPES\nfrom functools import partial\n\n\ndef pointwise_ops_fusion(fd: FusionDefinition, dtype: DataType, num_iters: int):\n x = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n y = fd.define_tensor(shape=[-1], contiguity=[True], dtype=dtype, is_cpu=False)\n\n if dtype in PROMOTE_DTYPES:\n x = fd.ops.cast(x, dtype=DataType.Float)\n y = fd.ops.cast(y, dtype=DataType.Float)\n\n a = fd.ops.add(x, y)","source_hash":"ad55953e2a586d1e39a5eb787cef142707a697376c9cfcb4631e9dd86524a702","truncated":false} {"repo_id":"Fuser","entity_id":"file:benchmarks/python/host/test_adaptive_layernorm_host.py","uri":"program://Fuser/file/benchmarks/python/host/test_adaptive_layernorm_host.py","kind":"file","name":"benchmarks/python/host/test_adaptive_layernorm_host.py","path":"benchmarks/python/host/test_adaptive_layernorm_host.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport pytest\nfrom nvfuser_direct import FusionDefinition, DataType\nfrom ..core import run_benchmark\nimport torch\n\n\ndef adaptive_layernorm_fwd_fusion(fd: FusionDefinition, eps: float = 1e-6) -> None:\n T0 = fd.define_tensor(\n shape=[-1, -1, -1],\n contiguity=[True, True, True],\n dtype=DataType.Half,\n is_cpu=False,\n stride_order=[2, 1, 0],\n )\n T1 = fd.define_tensor(\n shape=[-1, -1],\n contiguity=[True, True],\n dtype=DataType.Half,","source_hash":"b6c00e8f4d19d442976e6f3463c40f689f4325596bb2fda1a801eb54f8cc0481","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/setup.py","uri":"program://Fuser/file/python/setup.py","kind":"file","name":"python/setup.py","path":"python/setup.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# Usage:\n# pip install --no-build-isolation -e python -v\n# This build command is equivalent to: python setup.py develop\n# Options:\n# -v: verbose output\n# --no-build-isolation: don't build in a temporary directory\n# -e: install in development mode\n#\n# Environment variables used during build:\n# MAX_JOBS\n# maximum number of compile jobs we should use to compile your code\n#\n# NVFUSER_BUILD_CMAKE_ONLY\n# Only generate ./build directory with cmake setup\n#\n# NVFUSER_BUILD_NO_PYTHON\n# Skips python API target `libnvfuser.so`, i.e. `_C.cpython-xxx.so`","source_hash":"75afc77fdf9b893659087ed15cd2a8a5a2e77b914643223a73a8090abeec09c3","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/utils.py","uri":"program://Fuser/file/python/utils.py","kind":"file","name":"python/utils.py","path":"python/utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport os\nimport multiprocessing\nimport subprocess\nimport sys\nimport shutil\nfrom dataclasses import dataclass, field\nimport setuptools.command.build_ext\n\n\n@dataclass\nclass BuildConfig:\n cmake_only: bool = False\n build_setup: bool = True\n no_python: bool = False\n no_cutlass: bool = False\n no_test: bool = False\n no_benchmark: bool = False","source_hash":"e98e030f31b9d465cd9dcaf354bf4939de34b279c1c3e2b255e700648d2e187f","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/nvfuser_direct/pytorch_utils.py","uri":"program://Fuser/file/python/nvfuser_direct/pytorch_utils.py","kind":"file","name":"python/nvfuser_direct/pytorch_utils.py","path":"python/nvfuser_direct/pytorch_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport torch\n\nfrom ._C_DIRECT import DataType\n\nimport ctypes\nfrom typing import Type, Union, Tuple\nimport functools\n\nNumberTypeType = Union[Type[bool], Type[int], Type[float], Type[complex]]\n\n_torch_dtype_to_nvfuser_dtype_map = {\n torch.cdouble: DataType.ComplexDouble,\n torch.cfloat: DataType.ComplexFloat,\n torch.double: DataType.Double,\n torch.float: DataType.Float,\n torch.half: DataType.Half,\n torch.bfloat16: DataType.BFloat16,\n torch.float8_e4m3fn: DataType.Float8_e4m3fn,","source_hash":"8e20a062cb51a307028201b57302577fe3a6dd739145003dc3b3e352197e65e3","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/nvfuser_direct/nvfuser_direct_version.py","uri":"program://Fuser/file/python/nvfuser_direct/nvfuser_direct_version.py","kind":"file","name":"python/nvfuser_direct/nvfuser_direct_version.py","path":"python/nvfuser_direct/nvfuser_direct_version.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nfrom typing import Any\nfrom .version import _version_str\n\n__all__ = [\"NvfuserVersion\", \"Version\"]\n\n\nclass _LazyImport:\n \"\"\"Wraps around classes lazy imported from packaging.version\n Output of the function v in following snippets are identical:\n from packaging.version import Version\n def v():\n return Version('1.2.3')\n and\n Version = _LazyImport('Version')\n def v():\n return Version('1.2.3')\n The difference here is that in later example imports\n do not happen until v is called","source_hash":"838f7fc32fa11fa4b8c6c2e0928b70c48415a262a9c6e2e96a512c3bda0360b9","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/nvfuser_direct/__init__.py","uri":"program://Fuser/file/python/nvfuser_direct/__init__.py","kind":"file","name":"python/nvfuser_direct/__init__.py","path":"python/nvfuser_direct/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport sys\nimport traceback\nimport warnings\nfrom typing import Iterable, Optional\nimport functools\n\nif \"nvfuser\" in sys.modules:\n warnings.warn(\n \"Be careful! You've imported nvfuser_direct when the nvfuser module is already imported.\",\n UserWarning,\n )\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed.tensor import DTensor\nfrom torch.distributed.tensor.placement_types import Placement, Shard, Replicate\n","source_hash":"1620246a6e3888bf34c0a9212e508d20761a147a978f10717ef0498627b83d13","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/nvfuser_direct/benchmark_utils.py","uri":"program://Fuser/file/python/nvfuser_direct/benchmark_utils.py","kind":"file","name":"python/nvfuser_direct/benchmark_utils.py","path":"python/nvfuser_direct/benchmark_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport torch\nfrom cupti import cupti\nimport cxxfilt\nimport pytest\nfrom ._C_DIRECT import get_fusion_profile\n\n\n# Base class for all timers used by pytest-benchmark.\nclass Timer:\n def __init__(self):\n self.current_time = 0.0\n\n def _increment_global_time(self, elapsed_time: float) -> None:\n self.current_time += elapsed_time\n\n def __call__(self):\n raise NotImplementedError(\"Subclass must implement this method\")","source_hash":"c0db033d642f3589a7846848aec7f7b500bb9626b10f3522c0aa795e7497cd52","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/memory.py","uri":"program://Fuser/file/python/tools/memory.py","kind":"file","name":"python/tools/memory.py","path":"python/tools/memory.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\ndef get_available_memory_gb():\n \"\"\"Returns the available memory in GB.\"\"\"\n try:\n import psutil\n\n return psutil.virtual_memory().available / 1024 / 1024 / 1024\n except: # noqa: E722\n pass\n\n try:\n with open(\"/proc/meminfo\", \"r\") as f:\n while True:\n line = f.readline()\n if line.startswith(\"MemAvailable:\"):\n mem = line.split()[1]\n assert line.split()[2] == \"kB\"","source_hash":"29abf2a174c9e2b85c35c42603262a8157251a100571e5525577f4fff6e00105","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/__init__.py","uri":"program://Fuser/file/python/tools/__init__.py","kind":"file","name":"python/tools/__init__.py","path":"python/tools/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":3,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause","source_hash":"42ba09bbb339816dd46109a07ebfd999dbf561ebfbe624942f77de0b0aed53da","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/check_dependencies.py","uri":"program://Fuser/file/python/tools/check_dependencies.py","kind":"file","name":"python/tools/check_dependencies.py","path":"python/tools/check_dependencies.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"#!/usr/bin/env python3\n# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nnvFuser Dependency Report Generator\n\nReads dependency data from JSON (generated by CMake) and prints\na comprehensive, user-friendly report with colored output and\nactionable installation instructions for missing dependencies.\n\nIMPORTANT: CMake is the source of truth for all dependency requirements.\nThis script only formats output and provides help text.\n\"\"\"\n\nimport json\nimport sys\nfrom pathlib import Path\nfrom typing import Dict\n\nfrom prereqs import detect_platform, format_platform_info","source_hash":"cc4d2d5624215a30b5706fc2fd4bc3c0d2dc874336677e7102b267d4a3f06a1e","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/gen_nvfuser_version.py","uri":"program://Fuser/file/python/tools/gen_nvfuser_version.py","kind":"file","name":"python/tools/gen_nvfuser_version.py","path":"python/tools/gen_nvfuser_version.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nUNKNOWN = \"Unknown\"\nnvfuser_root = Path(__file__).parent.parent\n\n\n# note that this root currently is still part of pytorch.\ndef get_sha() -> str:\n try:\n return (\n subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=nvfuser_root)\n .decode(\"ascii\")\n .strip()\n )\n except Exception:\n import os","source_hash":"2aa7d649910dbd0dffed6e85fe05f5dff9a95f7f082e187d6f5442262ad1202a","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/colors.py","uri":"program://Fuser/file/python/tools/prereqs/colors.py","kind":"file","name":"python/tools/prereqs/colors.py","path":"python/tools/prereqs/colors.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nColor utilities for terminal output.\n\"\"\"\n\nimport os\n\n\nclass Colors:\n \"\"\"ANSI color codes for terminal output\"\"\"\n\n _codes = {\n \"RESET\": \"\\033[m\",\n \"BOLD\": \"\\033[1m\",\n # Regular colors\n \"GREEN\": \"\\033[32m\",\n \"YELLOW\": \"\\033[33m\",\n \"CYAN\": \"\\033[36m\",\n \"WHITE\": \"\\033[37m\",","source_hash":"286e88472c79fd888dc46e4424aff33d19a3c7e604ab9b747ed08ccdbded6ffc","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/exceptions.py","uri":"program://Fuser/file/python/tools/prereqs/exceptions.py","kind":"file","name":"python/tools/prereqs/exceptions.py","path":"python/tools/prereqs/exceptions.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nCustom exceptions for nvFuser prerequisite validation.\n\nThese exceptions provide structured error handling for build prerequisite\nchecks, enabling clear and actionable error messages.\n\"\"\"\n\n\nclass PrerequisiteMissingError(Exception):\n \"\"\"\n Raised when a prerequisite for building nvFuser is missing or has an incorrect version.\n\n This exception should include:\n - What prerequisite is missing or incorrect\n - Why it's required\n - Exact commands to install or fix it\n - Platform-specific guidance when applicable\n \"\"\"","source_hash":"49836a66031691ac0e5c084856917aac6929932a4f6f497db05609e3b23bd474","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/platform.py","uri":"program://Fuser/file/python/tools/prereqs/platform.py","kind":"file","name":"python/tools/prereqs/platform.py","path":"python/tools/prereqs/platform.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nPlatform detection utilities for nvFuser build system.\n\nDetects OS, architecture, and Linux distribution to provide platform-specific\nerror messages and installation guidance.\n\"\"\"\n\nimport platform\nfrom typing import Dict, Optional\n\n\ndef detect_platform() -> Dict[str, Optional[str]]:\n \"\"\"\n Detect the current platform and return structured information.\n\n Returns:\n dict: Platform information with keys:\n - 'os': Operating system (Linux, Darwin, Windows, etc.)","source_hash":"0cc4908454ea1420ec0a0158c8ccfd93b0d300c26cdbb26196856eb9184f7271","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirement_utils.py","uri":"program://Fuser/file/python/tools/prereqs/requirement_utils.py","kind":"file","name":"python/tools/prereqs/requirement_utils.py","path":"python/tools/prereqs/requirement_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nUtility functions for nvFuser dependency reporting.\n\nIMPORTANT: This module provides ONLY utility functions for formatting and URL generation.\nVersion requirements and dependency validation are handled by CMake.\n\nCMake defines requirements in: cmake/DependencyRequirements.cmake\nCMake exports status to: build/nvfuser_dependencies.json\nPython reads JSON and uses these utilities to format help text.\n\"\"\"\n\nimport platform\nimport re\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple\n\n\n# =============================================================================","source_hash":"75f4a5d16c24010f4079e99a83b936a6308dab8520c17e0a46a2cb8085679586","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/__init__.py","uri":"program://Fuser/file/python/tools/prereqs/__init__.py","kind":"file","name":"python/tools/prereqs/__init__.py","path":"python/tools/prereqs/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nnvFuser prerequisite utilities package.\n\nIMPORTANT DESIGN PRINCIPLE:\n===========================\nCMake is the source of truth for ALL dependency requirements and validation.\n\n- CMake defines version requirements in: cmake/DependencyRequirements.cmake\n- CMake finds dependencies and validates versions\n- CMake exports all data to JSON: build/nvfuser_dependencies.json\n- Python reads JSON and formats output with helpful instructions\n\nThis package provides ONLY:\n- Platform detection utilities\n- Version parsing/formatting utilities\n- URL generators for downloads\n- Utilities for formatting help text\n","source_hash":"889b9d1925136b2fed6c5a71138a50a09c4bfcedeb5d474716e511c26d3e1f42","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/git_submodules.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/git_submodules.py","kind":"file","name":"python/tools/prereqs/requirements/git_submodules.py","path":"python/tools/prereqs/requirements/git_submodules.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Git submodules dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass GitSubmodulesRequirement(BooleanRequirement):\n \"\"\"\n Git submodules initialization check.\n\n CMake variables used:\n - GitSubmodules_FOUND: Whether submodules are initialized\n - NVFUSER_REQUIREMENT_GitSubmodules_STATUS: Validation status\n - NVFUSER_REQUIREMENT_GitSubmodules_OPTIONAL: Whether submodules are optional\n\n No version checking - simple pass/fail.\n \"\"\"\n","source_hash":"7407cc39e96d519067a1f528baa9be6e22ef552d0b6cdbb499962fef39853afd","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/base.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/base.py","kind":"file","name":"python/tools/prereqs/requirements/base.py","path":"python/tools/prereqs/requirements/base.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\nBase classes for requirement types.\n\nThis module provides the foundational classes for all dependency requirements.\nEach requirement knows how to format its status and determine if it represents a failure.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import Optional, Dict\nfrom dataclasses import dataclass\n\nfrom ..colors import colorize\n\n\n@dataclass\nclass RequirementStatus:\n \"\"\"Validation status constants.\"\"\"\n","source_hash":"151051d7881f08d258c466d68b626dd8d1b673d6c78a7ceb7637b9b3e4c81728","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/pybind11.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/pybind11.py","kind":"file","name":"python/tools/prereqs/requirements/pybind11.py","path":"python/tools/prereqs/requirements/pybind11.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"pybind11 dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass Pybind11Requirement(VersionRequirement):\n \"\"\"\n pybind11 requirement for Python bindings.\n\n CMake variables used:\n - pybind11_FOUND: Whether pybind11 was found\n - pybind11_VERSION: Detected version (e.g., \"3.0.1\")\n - pybind11_DIR: Path to pybind11 CMake config\n - NVFUSER_REQUIREMENT_pybind11_STATUS: Validation status\n - NVFUSER_REQUIREMENT_pybind11_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_pybind11_OPTIONAL: Whether pybind11 is optional\n \"\"\"","source_hash":"b055e2338897dd76460b99d43961101e68f5ca2e45213e45b71a7ffea3ffc2d5","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/cuda_toolkit.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/cuda_toolkit.py","kind":"file","name":"python/tools/prereqs/requirements/cuda_toolkit.py","path":"python/tools/prereqs/requirements/cuda_toolkit.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"CUDA Toolkit dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass CUDAToolkitRequirement(VersionRequirement):\n \"\"\"\n NVIDIA CUDA Toolkit requirement.\n\n CMake variables used:\n - CUDAToolkit_FOUND: Whether CUDA was found\n - CUDAToolkit_VERSION: Detected version (e.g., \"13.1.80\")\n - CUDAToolkit_ROOT: Path to CUDA installation\n - NVFUSER_REQUIREMENT_CUDAToolkit_STATUS: Validation status\n - NVFUSER_REQUIREMENT_CUDAToolkit_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_CUDAToolkit_OPTIONAL: Whether CUDA is optional\n \"\"\"","source_hash":"93fadc51b743e38bdc6ddc54e2f61a8b05ecccc6ea6ed4104452e0dde39c47a6","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/llvm.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/llvm.py","kind":"file","name":"python/tools/prereqs/requirements/llvm.py","path":"python/tools/prereqs/requirements/llvm.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"LLVM dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass LLVMRequirement(VersionRequirement):\n \"\"\"\n LLVM requirement for Host IR JIT compilation.\n\n CMake variables used:\n - LLVM_FOUND: Whether LLVM was found\n - LLVM_VERSION: Detected version (e.g., \"18.1.3\")\n - LLVM_DIR: Path to LLVM CMake config\n - NVFUSER_REQUIREMENT_LLVM_STATUS: Validation status\n - NVFUSER_REQUIREMENT_LLVM_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_LLVM_OPTIONAL: Whether LLVM is optional\n \"\"\"","source_hash":"e011976ebb5656717c00005ef4f6564589df2f99b35b0ac06b7543c6fad2279d","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/compiler.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/compiler.py","kind":"file","name":"python/tools/prereqs/requirements/compiler.py","path":"python/tools/prereqs/requirements/compiler.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Compiler dependency requirement (GNU/Clang).\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass CompilerRequirement(VersionRequirement):\n \"\"\"\n C++ compiler requirement with name mapping.\n\n CMake variables used:\n - CMAKE_CXX_COMPILER_ID: Compiler name (GNU or Clang)\n - Compiler_FOUND: Whether compiler is available (always TRUE)\n - CMAKE_CXX_COMPILER_VERSION: Detected compiler version\n - CMAKE_CXX_COMPILER: Path to compiler executable\n - NVFUSER_REQUIREMENT_Compiler_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Compiler_VERSION_MIN: Minimum required version (set based on compiler ID)\n - NVFUSER_REQUIREMENT_Compiler_OPTIONAL: Whether compiler is optional","source_hash":"a1df35850a37ef58743d1b4419541a76766ba229aecbe8cd85b30f4e3d6355eb","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/ninja.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/ninja.py","kind":"file","name":"python/tools/prereqs/requirements/ninja.py","path":"python/tools/prereqs/requirements/ninja.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Ninja build system dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass NinjaRequirement(BooleanRequirement):\n \"\"\"\n Ninja build system check.\n\n CMake variables used:\n - Ninja_FOUND: Whether Ninja is available\n - NVFUSER_REQUIREMENT_Ninja_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Ninja_OPTIONAL: Whether Ninja is optional\n\n No version checking - just verifies Ninja is available.\n \"\"\"\n","source_hash":"a2094991e81a8ad3c39055137d2dd2b294f8f2b5da871ed347f0c6d7177ce48d","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/__init__.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/__init__.py","kind":"file","name":"python/tools/prereqs/requirements/__init__.py","path":"python/tools/prereqs/requirements/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Requirement class registry and factory.\"\"\"\n\nfrom .base import Requirement, VersionRequirement, BooleanRequirement, RequirementStatus\nfrom .python import PythonRequirement\nfrom .torch import TorchRequirement\nfrom .llvm import LLVMRequirement\nfrom .cuda_toolkit import CUDAToolkitRequirement\nfrom .pybind11 import Pybind11Requirement\nfrom .compiler import CompilerRequirement\nfrom .git_submodules import GitSubmodulesRequirement\nfrom .ninja import NinjaRequirement\nfrom .nvmmh import NVMMHRequirement\n\n__all__ = [\n # Base classes\n \"Requirement\",\n \"VersionRequirement\",\n \"BooleanRequirement\",","source_hash":"cb358af731000db1ed2490daea1a944ed83d90aa94cec8dab287ee66d9e07720","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/torch.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/torch.py","kind":"file","name":"python/tools/prereqs/requirements/torch.py","path":"python/tools/prereqs/requirements/torch.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"PyTorch dependency requirement with CUDA constraint validation.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\nfrom ..colors import colorize\n\n\nclass TorchRequirement(VersionRequirement):\n \"\"\"\n PyTorch requirement with CUDA version constraint checking.\n\n CMake variables used:\n - Torch_FOUND: Whether Torch was found\n - Torch_VERSION: Detected PyTorch version\n - Torch_DIR: Path to Torch CMake config\n - NVFUSER_REQUIREMENT_Torch_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Torch_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_Torch_OPTIONAL: Whether Torch is optional","source_hash":"cb9281b6cd3b1657ed364965c23b5a05f3018549b02b674c22c04d1c0aa3fa0d","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/nvmmh.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/nvmmh.py","kind":"file","name":"python/tools/prereqs/requirements/nvmmh.py","path":"python/tools/prereqs/requirements/nvmmh.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"nvidia-matmul-heuristics dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import BooleanRequirement\n\n\nclass NVMMHRequirement(BooleanRequirement):\n \"\"\"\n nvidia-matmul-heuristics check.\n\n CMake variables used:\n - NVMMH_FOUND: Whether nvidia-matmul-heuristics is available\n - NVFUSER_REQUIREMENT_NVMMH_STATUS: Validation status\n - NVFUSER_REQUIREMENT_NVMMH_OPTIONAL: Whether NVMMH is optional\n\n No version checking - just verifies nvidia-matmul-heuristics headers are available.\n \"\"\"\n","source_hash":"d46a059c3427a7cbff2f52c8291f5a9fd2f4ceaf74f2fc8225aae5749734197a","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/tools/prereqs/requirements/python.py","uri":"program://Fuser/file/python/tools/prereqs/requirements/python.py","kind":"file","name":"python/tools/prereqs/requirements/python.py","path":"python/tools/prereqs/requirements/python.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Python dependency requirement.\"\"\"\n\nfrom typing import Dict\nfrom .base import VersionRequirement\n\n\nclass PythonRequirement(VersionRequirement):\n \"\"\"\n Python interpreter requirement.\n\n CMake variables used:\n - Python_FOUND: Whether Python was found\n - Python_VERSION: Detected version (e.g., \"3.12.3\")\n - Python_EXECUTABLE: Path to python binary\n - NVFUSER_REQUIREMENT_Python_STATUS: Validation status\n - NVFUSER_REQUIREMENT_Python_VERSION_MIN: Minimum required version\n - NVFUSER_REQUIREMENT_Python_OPTIONAL: Whether Python is optional\n \"\"\"","source_hash":"aaec8121a03dbd540440f34deb289fd581872c597ccfcfd7bfcc9e31ffa34eab","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/nvfuser_common/__init__.py","uri":"program://Fuser/file/python/nvfuser_common/__init__.py","kind":"file","name":"python/nvfuser_common/__init__.py","path":"python/nvfuser_common/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":3,"code":"# SPDX-FileCopyrightText: Copyright (c) 2025-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause","source_hash":"42ba09bbb339816dd46109a07ebfd999dbf561ebfbe624942f77de0b0aed53da","truncated":false} {"repo_id":"Fuser","entity_id":"file:python/nvfuser_common/utils.py","uri":"program://Fuser/file/python/nvfuser_common/utils.py","kind":"file","name":"python/nvfuser_common/utils.py","path":"python/nvfuser_common/utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":18,"code":"# SPDX-FileCopyrightText: Copyright (c) 2024-present NVIDIA CORPORATION & AFFILIATES.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\nimport os\n\n\n__all__ = [\n \"cmake_prefix_path\",\n]\n\n\ncmake_prefix_path = os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"nvfuser_common\",\n \"share\",\n \"cmake\",\n \"nvfuser\",\n)","source_hash":"193d1b8b1dbe90bf497223354561a160f4366974b36452abb293360a8d19eaf1","truncated":false}