1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
|
"""
Functionality for tracing through an autoray.lazy computation and estimating
the cost and scaling.
In the following there are ``cost_*`` functions that estimate the total cost
of a given operation, including sub-leading factors. There are also
`cost_scaling_*` functions that only consider the leading factor of the cost,
so that we can prime number decompose it and extract the scaling.
"""
import math
def cost_tensordot(x):
x1, x2, axes = x.args
shape1, shape2 = x1.shape, x2.shape
cost = math.prod(shape1) * math.prod(shape2)
for d in axes[0]:
cost //= shape1[d]
return cost
cost_scaling_tensordot = cost_tensordot
def cost_qr(x):
(A,) = x.deps
shape = A.shape
m = max(shape)
n = min(shape)
return 2 * m * n**2 - (2 / 3) * n**3
def cost_svd(x):
(A,) = x.deps
shape = A.shape
m = max(shape)
n = min(shape)
return 4 * m * n**2 - (4 / 3) * n**3
def cost_eigh(x):
(A,) = x.deps
m = A.shape[0]
return 8 / 3 * m**3
def cost_scaling_linalg(x):
"""Here we only care about the leading factor of the cost, which we need to
preserve so that we can prime number decompose it.
"""
(A,) = x.deps
shape = A.shape
m = max(shape)
n = min(shape)
return m * n**2
cost_scaling_qr = cost_scaling_svd = cost_scaling_linalg
def cost_matmul(x):
A, B = x.deps
return A.shape[0] * A.shape[1] * B.shape[1]
cost_scaling_matmul = cost_matmul
def cost_einsum(x):
eq, *operands = x.args
lhs = eq.split("->")[0]
terms = lhs.split(",")
size_dict = {
ix: d
for term, x in zip(terms, operands)
for ix, d in zip(term, x.shape)
}
return math.prod(size_dict.values())
cost_scaling_einsum = cost_einsum
def cost_linear(x):
return math.prod(x.shape)
def cost_nothing(x):
return 0
COSTS = {
"qr": cost_qr,
"qr_stabilized": cost_qr,
"qr_stabilized_numba": cost_qr,
"svd": cost_svd,
"svd_truncated": cost_svd,
"svd_truncated_numba": cost_svd,
"svd_truncated_numpy": cost_svd,
"eigh": cost_eigh,
"linalg_eigh": cost_eigh,
"tensordot": cost_tensordot,
"matmul": cost_matmul,
"einsum": cost_einsum,
# other cheap ops
"mul": cost_linear,
"sum": cost_linear,
"add": cost_linear,
"neg": cost_linear,
"sqrt": cost_linear,
"cupy_sqrt": cost_linear,
"pow": cost_linear,
"truediv": cost_linear,
"log10": cost_linear,
"cupy_log10": cost_linear,
"norm": cost_linear,
"linalg_norm": cost_linear,
"reshape": cost_linear,
"conj": cost_linear,
"conjugate": cost_linear,
"cupy_conjugate": cost_linear,
"clip": cost_linear,
"transpose": cost_linear,
"absolute": cost_linear,
"trace": cost_linear,
"torch_transpose": cost_linear,
"clamp": cost_linear,
"getitem": cost_nothing,
"None": cost_nothing,
}
def cost_node(x, allow_missed=True):
f = x.fn_name
if f in COSTS:
return COSTS[f](x)
elif allow_missed:
return 0
else:
raise ValueError(f"Cost for {f} not implemented.")
def compute_cost(z, print_missed=True):
C = 0
missed = {}
for node in z.descend():
f = node.fn_name
if f in COSTS:
C += COSTS[f](node)
else:
missed[f] = missed.get(f, 0) + 1
if missed and print_missed:
import warnings
warnings.warn(f"Missed {missed} in cost computation.")
return C
COST_SCALINGS = {
"qr": cost_scaling_qr,
"qr_stabilized": cost_scaling_qr,
"qr_stabilized_numba": cost_scaling_qr,
"svd": cost_scaling_svd,
"svd_truncated": cost_scaling_svd,
"svd_truncated_numba": cost_scaling_svd,
"svd_truncated_numpy": cost_scaling_svd,
"eigh": cost_scaling_linalg,
"tensordot": cost_scaling_tensordot,
"matmul": cost_scaling_matmul,
"einsum": cost_scaling_einsum,
# other cheap ops
"mul": cost_linear,
"sum": cost_linear,
"add": cost_linear,
"neg": cost_linear,
"sqrt": cost_linear,
"pow": cost_linear,
"truediv": cost_linear,
"log10": cost_linear,
"norm": cost_linear,
"reshape": cost_linear,
"conj": cost_linear,
"conjugate": cost_linear,
"clip": cost_linear,
"transpose": cost_linear,
"absolute": cost_linear,
"trace": cost_linear,
"getitem": cost_nothing,
"None": cost_nothing,
}
def prime_factors(n) -> list[int]:
fs = []
if n <= 1:
return fs
while n % 2 == 0:
fs.append(2)
n = n // 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
fs.append(i)
n = n / i
if n > 2:
fs.append(n)
return fs
def is_prime(n: int) -> bool:
for i in range(int(n**0.5), 1, -2 if int(n**0.5) % 2 == 0 else -1):
if n % i == 0:
return False
return False if n in (0, 1) else True
def closest_prime(nt: int) -> int:
if is_prime(nt):
return nt
lower = None
higher = None
for i in range(nt if nt % 2 != 0 else nt - 1, 1, -2):
if is_prime(i):
lower = i
break
c = nt + 1
while higher is None:
if is_prime(c):
higher = c
else:
c += 2 if c % 2 != 0 else 1
return higher if lower is None or higher - nt < nt - lower else lower
def frequencies(it):
c = {}
for i in it:
c[i] = c.get(i, 0) + 1
return c
def compute_cost_scalings(z, factor_map, print_missed=True):
from autoray.lazy import descend
counts = {}
missed = {}
for node in descend(z):
f = node.fn_name
if f in COST_SCALINGS:
CS = COST_SCALINGS[f](node)
else:
missed[f] = missed.get(f, 0) + 1
continue
# group operations
key = (CS, f)
counts[key] = counts.get(key, 0) + 1
if missed and print_missed:
import warnings
warnings.warn(f"Missed {missed} in cost scaling computation.")
scalings = []
for key, freq in counts.items():
op = {
"cost": key[0],
"name": key[1],
"freq": freq,
}
pf = frequencies(prime_factors(op["cost"]))
for name, factor in factor_map.items():
op[name] = pf.pop(factor, 0)
if pf and print_missed:
import warnings
warnings.warn(
f"Missed prime factor(s) {pf} in cost scaling computation, "
f" for operation {op}."
)
scalings.append(op)
scalings.sort(key=lambda x: x["cost"], reverse=True)
return scalings
|