|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | +# All rights reserved. |
| 4 | +# |
| 5 | +# This source code is licensed under the BSD-style license found in the |
| 6 | +# LICENSE file in the root directory of this source tree. |
| 7 | + |
| 8 | +"""Generate runtime/ops/<op>/<stem>_wgsl.h from each <stem>.wgsl. |
| 9 | +
|
| 10 | +Each header embeds the shader verbatim as `inline constexpr const char* |
| 11 | +k<Pascal>WGSL` plus `k<Pascal>WorkgroupSize` (parsed from @workgroup_size). |
| 12 | +
|
| 13 | +Usage: |
| 14 | + gen_wgsl_headers.py # (re)write all <stem>_wgsl.h |
| 15 | + gen_wgsl_headers.py --check # exit 1 if any committed header is stale |
| 16 | +
|
| 17 | +Stdlib only (the devserver has no third-party pip). |
| 18 | +""" |
| 19 | + |
| 20 | +import argparse |
| 21 | +import hashlib |
| 22 | +import re |
| 23 | +import sys |
| 24 | +from pathlib import Path |
| 25 | + |
| 26 | +BACKEND_ROOT = Path(__file__).resolve().parents[1] |
| 27 | + |
| 28 | +_SHA_RE = re.compile(r"// wgsl-sha256: ([0-9a-f]{64})") |
| 29 | + |
| 30 | +_BSD_HEADER = """\ |
| 31 | +/* |
| 32 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 33 | + * All rights reserved. |
| 34 | + * |
| 35 | + * This source code is licensed under the BSD-style license found in the |
| 36 | + * LICENSE file in the root directory of this source tree. |
| 37 | + */""" |
| 38 | + |
| 39 | + |
| 40 | +def symbol_base(stem: str) -> str: |
| 41 | + """snake_case shader stem -> PascalCase symbol base (binary_add -> BinaryAdd).""" |
| 42 | + return "".join(part.capitalize() for part in stem.split("_")) |
| 43 | + |
| 44 | + |
| 45 | +_INT_LITERAL_RE = re.compile(r"^(\d+)[uUiI]?$") |
| 46 | + |
| 47 | + |
| 48 | +def _resolve_dim(tok: str, src: str) -> int: |
| 49 | + """Resolve one @workgroup_size dim token: a literal or an override/const ident. |
| 50 | +
|
| 51 | + Accepts WGSL suffix-typed integer literals (e.g. `64u`, `64i`) both as the |
| 52 | + token and on the right-hand side of an `override`/`const` (type optional). |
| 53 | + """ |
| 54 | + lit = _INT_LITERAL_RE.match(tok) |
| 55 | + if lit: |
| 56 | + return int(lit.group(1)) |
| 57 | + m = re.search( |
| 58 | + r"(?:override|const)\s+" |
| 59 | + + re.escape(tok) |
| 60 | + + r"\s*(?::\s*u32\s*)?=\s*(\d+)[uUiI]?", |
| 61 | + src, |
| 62 | + ) |
| 63 | + if not m: |
| 64 | + raise ValueError(f"cannot resolve @workgroup_size identifier '{tok}'") |
| 65 | + return int(m.group(1)) |
| 66 | + |
| 67 | + |
| 68 | +def parse_workgroup_size(src: str) -> tuple[int, int, int]: |
| 69 | + """Resolve the (x, y, z) dims of @workgroup_size; y and z default to 1.""" |
| 70 | + m = re.search(r"@workgroup_size\s*\(([^)]*)\)", src) |
| 71 | + if not m: |
| 72 | + raise ValueError("no @workgroup_size found") |
| 73 | + toks = [t.strip() for t in m.group(1).split(",") if t.strip()] |
| 74 | + if not toks or len(toks) > 3: |
| 75 | + raise ValueError(f"@workgroup_size takes 1-3 dims, got {len(toks)}") |
| 76 | + dims = [_resolve_dim(t, src) for t in toks] |
| 77 | + while len(dims) < 3: |
| 78 | + dims.append(1) |
| 79 | + return (dims[0], dims[1], dims[2]) |
| 80 | + |
| 81 | + |
| 82 | +def wgsl_sha256(wgsl_text: str) -> str: |
| 83 | + return hashlib.sha256(wgsl_text.encode("utf-8")).hexdigest() |
| 84 | + |
| 85 | + |
| 86 | +def embedded_sha256(header_text: str) -> str: |
| 87 | + m = _SHA_RE.search(header_text) |
| 88 | + return m.group(1) if m else "" |
| 89 | + |
| 90 | + |
| 91 | +def render_header(wgsl_path, wgsl_text: str) -> str: |
| 92 | + """Render the full <stem>_wgsl.h text for a shader (shader embedded verbatim).""" |
| 93 | + if ')"' in wgsl_text: |
| 94 | + raise ValueError('shader contains )" which would close the R"( literal') |
| 95 | + stem = Path(wgsl_path).stem |
| 96 | + base = symbol_base(stem) |
| 97 | + x, y, z = parse_workgroup_size(wgsl_text) |
| 98 | + |
| 99 | + head = [ |
| 100 | + _BSD_HEADER, |
| 101 | + "", |
| 102 | + "#pragma once", |
| 103 | + "", |
| 104 | + "#include <cstdint>", |
| 105 | + "", |
| 106 | + "namespace executorch::backends::webgpu {", |
| 107 | + "", |
| 108 | + f"// @generated from {stem}.wgsl - DO NOT EDIT.", |
| 109 | + f"// wgsl-sha256: {wgsl_sha256(wgsl_text)}", |
| 110 | + f'inline constexpr const char* k{base}WGSL = R"(', |
| 111 | + ] |
| 112 | + return ( |
| 113 | + "\n".join(head) |
| 114 | + + "\n" |
| 115 | + + wgsl_text |
| 116 | + + ')";' |
| 117 | + + "\n\n" |
| 118 | + + f"inline constexpr uint32_t k{base}WorkgroupSizeX = {x};\n" |
| 119 | + + f"inline constexpr uint32_t k{base}WorkgroupSizeY = {y};\n" |
| 120 | + + f"inline constexpr uint32_t k{base}WorkgroupSizeZ = {z};\n\n" |
| 121 | + + "} // namespace executorch::backends::webgpu\n" |
| 122 | + ) |
| 123 | + |
| 124 | + |
| 125 | +def discover(): |
| 126 | + """All shader sources under runtime/ops, sorted.""" |
| 127 | + return sorted((BACKEND_ROOT / "runtime/ops").glob("**/*.wgsl")) |
| 128 | + |
| 129 | + |
| 130 | +def _report_drift(missing, stale) -> None: |
| 131 | + """Print the --check report for missing/stale committed headers.""" |
| 132 | + if missing: |
| 133 | + print("Missing embedded WGSL headers (run scripts/gen_wgsl_headers.py):") |
| 134 | + for h in missing: |
| 135 | + print(f" {h.relative_to(BACKEND_ROOT)}") |
| 136 | + if stale: |
| 137 | + print("Stale embedded WGSL headers (run scripts/gen_wgsl_headers.py):") |
| 138 | + for h in stale: |
| 139 | + print(f" {h.relative_to(BACKEND_ROOT)}") |
| 140 | + |
| 141 | + |
| 142 | +def main(argv=None) -> int: |
| 143 | + parser = argparse.ArgumentParser(description=__doc__) |
| 144 | + parser.add_argument( |
| 145 | + "--check", |
| 146 | + action="store_true", |
| 147 | + help="verify committed headers match (exit 1 on drift)", |
| 148 | + ) |
| 149 | + args = parser.parse_args(argv) |
| 150 | + |
| 151 | + stale = [] |
| 152 | + missing = [] |
| 153 | + errors = [] |
| 154 | + for wgsl in discover(): |
| 155 | + wgsl_text = wgsl.read_text() |
| 156 | + try: |
| 157 | + want = render_header(wgsl, wgsl_text) |
| 158 | + except ValueError as e: |
| 159 | + errors.append(f"{wgsl.relative_to(BACKEND_ROOT)}: {e}") |
| 160 | + continue |
| 161 | + header = wgsl.with_name(wgsl.stem + "_wgsl.h") |
| 162 | + # Full-content compare (not just the sha) catches generator-logic drift too. |
| 163 | + if header.exists() and header.read_text() == want: |
| 164 | + continue |
| 165 | + if args.check: |
| 166 | + (missing if not header.exists() else stale).append(header) |
| 167 | + else: |
| 168 | + header.write_text(want) |
| 169 | + |
| 170 | + if errors: |
| 171 | + print("Cannot generate header (malformed shader):") |
| 172 | + for e in errors: |
| 173 | + print(f" {e}") |
| 174 | + return 1 |
| 175 | + if args.check and (stale or missing): |
| 176 | + _report_drift(missing, stale) |
| 177 | + return 1 |
| 178 | + return 0 |
| 179 | + |
| 180 | + |
| 181 | +if __name__ == "__main__": |
| 182 | + sys.exit(main()) |
0 commit comments