|
| 1 | +"""Generated Metal kernels for batches of real spherical harmonics.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from collections.abc import Callable, Sequence |
| 6 | +from math import sqrt |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +from e3nn_core.cg import wigner_3j |
| 10 | + |
| 11 | +from .compat import require_mlx |
| 12 | + |
| 13 | + |
| 14 | +_KERNEL_CACHE: dict[tuple[tuple[int, ...], bool, tuple[float, ...]], tuple[Any, Any]] = {} |
| 15 | + |
| 16 | + |
| 17 | +def _literal(value: float) -> str: |
| 18 | + literal = f"{value:.17g}" |
| 19 | + if "." not in literal and "e" not in literal: |
| 20 | + literal += ".0" |
| 21 | + return literal + "f" |
| 22 | + |
| 23 | + |
| 24 | +def _program( |
| 25 | + degrees: tuple[int, ...], normalize: bool, scales: tuple[float, ...], *, backward: bool |
| 26 | +) -> str: |
| 27 | + lmax = max(degrees) |
| 28 | + lines = [ |
| 29 | + "uint item = thread_position_in_grid.x;", |
| 30 | + "uint input_base = item * 3;", |
| 31 | + "float x0 = float(vectors[input_base]);", |
| 32 | + "float x1 = float(vectors[input_base + 1]);", |
| 33 | + "float x2 = float(vectors[input_base + 2]);", |
| 34 | + ] |
| 35 | + if normalize: |
| 36 | + lines += [ |
| 37 | + "float radius = sqrt(x0*x0 + x1*x1 + x2*x2);", |
| 38 | + "float inverse_radius = radius > 0.0f ? 1.0f / max(radius, 1.0e-12f) : 0.0f;", |
| 39 | + "float n0 = x0 * inverse_radius;", |
| 40 | + "float n1 = x1 * inverse_radius;", |
| 41 | + "float n2 = x2 * inverse_radius;", |
| 42 | + ] |
| 43 | + else: |
| 44 | + lines += ["float n0 = x0;", "float n1 = x1;", "float n2 = x2;"] |
| 45 | + lines.append("float y0_0 = 1.0f;") |
| 46 | + if backward: |
| 47 | + lines += [f"float dy0_0_{k} = 0.0f;" for k in range(3)] |
| 48 | + if lmax: |
| 49 | + root3 = sqrt(3.0) |
| 50 | + for component in range(3): |
| 51 | + lines.append(f"float y1_{component} = {_literal(root3)} * n{component};") |
| 52 | + if backward: |
| 53 | + for k in range(3): |
| 54 | + if normalize: |
| 55 | + derivative = ( |
| 56 | + f"inverse_radius * ({'1.0f' if component == k else '0.0f'} " |
| 57 | + f"- n{component} * n{k})" |
| 58 | + ) |
| 59 | + else: |
| 60 | + derivative = "1.0f" if component == k else "0.0f" |
| 61 | + lines.append( |
| 62 | + f"float dy1_{component}_{k} = {_literal(root3)} * ({derivative});" |
| 63 | + ) |
| 64 | + |
| 65 | + for l in range(1, lmax): |
| 66 | + coefficients = wigner_3j(l, 1, l + 1) |
| 67 | + factor = (2 * l + 3) / sqrt(3.0 * (l + 1)) |
| 68 | + for c in range(2 * (l + 1) + 1): |
| 69 | + terms: list[tuple[int, int, float]] = [] |
| 70 | + for a in range(2 * l + 1): |
| 71 | + for b in range(3): |
| 72 | + coefficient = float(coefficients[a][b][c]) * factor |
| 73 | + if coefficient != 0.0: |
| 74 | + terms.append((a, b, coefficient)) |
| 75 | + expression = " + ".join( |
| 76 | + f"{_literal(coefficient)} * y{l}_{a} * y1_{b}" |
| 77 | + for a, b, coefficient in terms |
| 78 | + ) or "0.0f" |
| 79 | + lines.append(f"float y{l + 1}_{c} = {expression};") |
| 80 | + if backward: |
| 81 | + for k in range(3): |
| 82 | + derivative = " + ".join( |
| 83 | + f"{_literal(coefficient)} * (dy{l}_{a}_{k} * y1_{b} + y{l}_{a} * dy1_{b}_{k})" |
| 84 | + for a, b, coefficient in terms |
| 85 | + ) or "0.0f" |
| 86 | + lines.append(f"float dy{l + 1}_{c}_{k} = {derivative};") |
| 87 | + |
| 88 | + output_offset = 0 |
| 89 | + if backward: |
| 90 | + for k in range(3): |
| 91 | + lines.append(f"float gradient{k} = 0.0f;") |
| 92 | + for degree, scale in zip(degrees, scales, strict=True): |
| 93 | + for component in range(2 * degree + 1): |
| 94 | + for k in range(3): |
| 95 | + lines.append( |
| 96 | + f"gradient{k} += float(cotangent[item * {sum(2*d+1 for d in degrees)} + {output_offset}]) " |
| 97 | + f"* {_literal(scale)} * dy{degree}_{component}_{k};" |
| 98 | + ) |
| 99 | + output_offset += 1 |
| 100 | + lines += [f"vector_gradient[input_base + {k}] = T(gradient{k});" for k in range(3)] |
| 101 | + else: |
| 102 | + output_dim = sum(2 * degree + 1 for degree in degrees) |
| 103 | + for degree, scale in zip(degrees, scales, strict=True): |
| 104 | + for component in range(2 * degree + 1): |
| 105 | + lines.append( |
| 106 | + f"output[item * {output_dim} + {output_offset}] = " |
| 107 | + f"T({_literal(scale)} * y{degree}_{component});" |
| 108 | + ) |
| 109 | + output_offset += 1 |
| 110 | + return "\n".join(lines) |
| 111 | + |
| 112 | + |
| 113 | +def _kernels(degrees: tuple[int, ...], normalize: bool, scales: tuple[float, ...]): |
| 114 | + mx, _ = require_mlx() |
| 115 | + key = (degrees, normalize, scales) |
| 116 | + if key in _KERNEL_CACHE: |
| 117 | + return _KERNEL_CACHE[key] |
| 118 | + suffix = "_".join(map(str, degrees)) |
| 119 | + forward = mx.fast.metal_kernel( |
| 120 | + name=f"e3nn_sh_forward_{suffix}_{int(normalize)}", |
| 121 | + input_names=["vectors"], |
| 122 | + output_names=["output"], |
| 123 | + source=_program(degrees, normalize, scales, backward=False), |
| 124 | + ) |
| 125 | + backward = mx.fast.metal_kernel( |
| 126 | + name=f"e3nn_sh_backward_{suffix}_{int(normalize)}", |
| 127 | + input_names=["vectors", "cotangent"], |
| 128 | + output_names=["vector_gradient"], |
| 129 | + source=_program(degrees, normalize, scales, backward=True), |
| 130 | + ) |
| 131 | + _KERNEL_CACHE[key] = forward, backward |
| 132 | + return forward, backward |
| 133 | + |
| 134 | + |
| 135 | +def make_operation( |
| 136 | + degrees: Sequence[int], |
| 137 | + normalize: bool, |
| 138 | + scales: Sequence[float], |
| 139 | + general: Callable[[Any], Any], |
| 140 | +): |
| 141 | + """Create a fused per-vector spherical-harmonics operation.""" |
| 142 | + |
| 143 | + mx, _ = require_mlx() |
| 144 | + degrees = tuple(degrees) |
| 145 | + scales = tuple(scales) |
| 146 | + output_dim = sum(2 * degree + 1 for degree in degrees) |
| 147 | + forward_kernel, backward_kernel = _kernels(degrees, normalize, scales) |
| 148 | + |
| 149 | + @mx.custom_function |
| 150 | + def differentiable_backward(vectors, cotangent): |
| 151 | + return backward_kernel( |
| 152 | + inputs=[vectors, cotangent], |
| 153 | + template=[("T", vectors.dtype)], |
| 154 | + output_shapes=[vectors.shape], |
| 155 | + output_dtypes=[vectors.dtype], |
| 156 | + grid=(vectors.shape[0], 1, 1), |
| 157 | + threadgroup=(256, 1, 1), |
| 158 | + )[0] |
| 159 | + |
| 160 | + @differentiable_backward.vjp |
| 161 | + def differentiable_backward_vjp(primals, cotangent, _output): |
| 162 | + vectors, output_cotangent = primals |
| 163 | + |
| 164 | + def general_backward(x, dy): |
| 165 | + _, (gradient,) = mx.vjp(general, (x,), (dy,)) |
| 166 | + return gradient |
| 167 | + |
| 168 | + _, gradients = mx.vjp(general_backward, (vectors, output_cotangent), (cotangent,)) |
| 169 | + return gradients |
| 170 | + |
| 171 | + @mx.custom_function |
| 172 | + def operation(vectors): |
| 173 | + return forward_kernel( |
| 174 | + inputs=[vectors], |
| 175 | + template=[("T", vectors.dtype)], |
| 176 | + output_shapes=[(vectors.shape[0], output_dim)], |
| 177 | + output_dtypes=[vectors.dtype], |
| 178 | + grid=(vectors.shape[0], 1, 1), |
| 179 | + threadgroup=(256, 1, 1), |
| 180 | + )[0] |
| 181 | + |
| 182 | + @operation.vjp |
| 183 | + def operation_vjp(primals, cotangent, _output): |
| 184 | + return differentiable_backward(primals, cotangent) |
| 185 | + |
| 186 | + @operation.jvp |
| 187 | + def operation_jvp(primals, tangents): |
| 188 | + _, tangent = mx.jvp(general, (primals,), (tangents,)) |
| 189 | + return tangent |
| 190 | + |
| 191 | + return operation |
0 commit comments