"""Test on a Clebsch--Gordan basis after the two root projectors involving the third letter.""" import importlib import itertools import sys from collections import defaultdict from math import comb, prod from pathlib import Path import numpy as np import torch import triton import triton.language as tl sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) binary = importlib.import_module("ternary-coupled") P = 239 def gpu(x): return torch.from_numpy(np.ascontiguousarray(x)).cuda() def center(x): return ((x.astype(np.int32) + 119) % P - 119).astype(np.int8) def string_layers(mark, copies, maximum, cache): d = 10 - mark limit = min(d * copies, max(maximum, 44) if cache else maximum) file = cache / f"string-{mark}-{copies}-{limit}.npz" if cache else None if file and file.is_file(): with np.load(file) as data: for w in range(limit + 1): yield w, data[f"m{w}"], data[f"l{w}"] return saved = {} for w, rows, mat, labels in binary.binary_string_layers(d, copies, limit): # The string basis uses raw coefficients, the root ladders use divided coefficients. scale = np.array( [prod(comb(10, mark) * comb(d, y) for y in row) % P for row in rows], np.int32 ) matrix = center(scale[:, None] * (mat % P)) labels = np.asarray(labels, dtype=np.int16) if file: saved[f"m{w}"] = matrix saved[f"l{w}"] = labels yield w, matrix, labels if file: cache.mkdir(parents=True, exist_ok=True) import tempfile, os with tempfile.NamedTemporaryFile(dir=cache, delete=False) as tmp: np.savez(tmp, **saved) os.replace(tmp.name, file) class Strings: def __init__(self, mark, copies, m, cache): self.matrices = {} self.positions = {} self.types = [] for w, mat, labels in string_layers(mark, copies, m, cache): if w > m: continue self.matrices[w] = mat for h in np.unique(labels[:, 0]): ids = np.flatnonzero(labels[:, 0] == h) assert np.array_equal(labels[ids, 1], np.arange(len(ids))) self.positions[int(h), w] = ids if h == w: self.types.append(((10 - mark) * copies - 2 * w, len(ids), w)) def top_profiles(monomials): """Group globally indexed monomials by marked degrees and sum of y within tied groups.""" terms = np.array([t * 16 + y for y in range(11) for t in range(11 - y)], np.uint8) n = len(monomials) ts = np.empty(n, np.int64) ys = np.empty(n, np.int64) powers = 16 ** np.arange(9, -1, -1, dtype=np.int64) for lo in range(0, n, 65536): v = np.sort(terms[monomials[lo : lo + 65536]], axis=1) ts[lo : lo + len(v)] = (v >> 4) @ powers ys[lo : lo + len(v)] = (v & 15) @ powers order = np.argsort(ts, kind="stable").astype(np.int32) sv = ts[order] cuts = np.r_[0, np.flatnonzero(sv[1:] != sv[:-1]) + 1, n] for lo, hi in zip(cuts[:-1], cuts[1:]): mark, copies = np.unique((int(sv[lo]) // powers) % 16, return_counts=True) groups = tuple(zip(map(int, mark), map(int, copies))) original = order[lo:hi] y = ys[original] sumkey = np.zeros(len(y), np.int64) slot = 0 for _, r in groups: u = sum((y // powers[i]) % 16 for i in range(slot, slot + r)) sumkey = sumkey * 128 + u slot += r ix = np.lexsort((y, sumkey)) weights = sumkey[ix] boundaries = np.r_[0, np.flatnonzero(weights[1:] != weights[:-1]) + 1, len(y)] block = {} for start, stop in zip(boundaries[:-1], boundaries[1:]): code = int(weights[start]) ww = tuple((code >> (7 * q)) & 127 for q in reversed(range(len(groups)))) block[ww] = original[ix[start:stop]] yield groups, block @triton.jit def _scale(values, scales, n, batch: tl.constexpr, rm: tl.constexpr, bt: tl.constexpr): x = tl.program_id(0) * rm + tl.arange(0, rm) b = tl.program_id(1) * bt + tl.arange(0, bt) addr = x[:, None].to(tl.int64) * batch + b[None, :] mask = (x[:, None] < n) & (b[None, :] < batch) val = tl.load(values + addr, mask=mask, other=0).to(tl.int32) s = tl.load(scales + x, mask=x < n, other=0).to(tl.int32) tl.store(values + addr, (val * s[:, None]) % 239, mask=mask) @triton.jit def _small( dst, src, second, nraw, dual: tl.constexpr, ids, coeff, desc, n, batch: tl.constexpr, k: tl.constexpr, rm: tl.constexpr, bt: tl.constexpr, ): row = tl.program_id(0) * rm + tl.arange(0, rm) b = tl.program_id(1) * bt + tl.arange(0, bt) out = tl.load(desc + row * 3, mask=row < n, other=0).to(tl.int64) pos = tl.load(desc + row * 3 + 1, mask=row < n, other=0) ci = tl.load(desc + row * 3 + 2, mask=row < n, other=0) v = tl.full((rm, bt), 0, tl.int32) for j in tl.static_range(k): ix = tl.load(ids + pos + j, mask=row < n, other=0).to(tl.int64) c = tl.load(coeff + ci + j, mask=row < n, other=0).to(tl.int32) first = src + ix * batch if dual: first = tl.where(ix < nraw, first, second + (ix - nraw) * batch) a = tl.load( first[:, None] + b[None, :], mask=(row[:, None] < n) & (b[None, :] < batch), other=0, ) v += c[:, None] * a.to(tl.int32) v = v % 239 tl.store( dst + out[:, None] * batch + b[None, :], tl.where(v < 0, v + 239, v), mask=(row[:, None] < n) & (b[None, :] < batch), ) @triton.jit def _large( dst, src, second, nraw, dual: tl.constexpr, ids, coeff, desc, batch: tl.constexpr, bm: tl.constexpr, bk: tl.constexpr, bt: tl.constexpr, ): meta = desc + tl.program_id(0) * 6 ib = tl.load(meta) ob = tl.load(meta + 1) co = tl.load(meta + 2) k = tl.load(meta + 3) c = tl.load(meta + 4) x = tl.load(meta + 5) + tl.arange(0, bm) u = tl.arange(0, bk) b = tl.program_id(1) * bt + tl.arange(0, bt) acc = tl.full((bm, bt), 0, tl.int32) for q in range(tl.cdiv(k, bk)): a = tl.load( coeff + co + x[:, None] * k + (q * bk + u[None, :]), mask=(x[:, None] < c) & (q * bk + u[None, :] < k), other=0, ) ix = tl.load(ids + ib + q * bk + u, mask=q * bk + u < k, other=0).to(tl.int64) first = src + ix * batch if dual: first = tl.where(ix < nraw, first, second + (ix - nraw) * batch) vx = tl.load( first[:, None] + b[None, :], mask=(q * bk + u[:, None] < k) & (b[None, :] < batch), other=0, ).to(tl.int32) vx = tl.where(vx > 119, vx - 239, vx).to(tl.int8) acc = tl.dot(a, vx, acc, out_dtype=tl.int32) out = tl.load(ids + ob + x, mask=x < c, other=0).to(tl.int64) acc = acc % 239 tl.store( dst + out[:, None] * batch + b[None, :], tl.where(acc < 0, acc + 239, acc), mask=(x[:, None] < c) & (b[None, :] < batch), ) class Contractions: """Collect independent binary maps, sharing one coefficient array across all their fibres.""" def __init__(self): self.blocks = defaultdict(list) def add(self, key, matrix, indices, targets=None): self.blocks[key].append((matrix, indices, targets)) def finish(self, store): all_ids = [] all_coeff = [] sm = defaultdict(list) bg = [] io = co = 0 for entries in self.blocks.values(): mat = entries[0][0] k, c = mat.shape all_coeff.append(mat.T.copy().reshape(-1)) for _, ix, ox in entries: fibres = ix.shape[1] all_ids.append(np.ascontiguousarray(ix.T).reshape(-1)) ib = io + k * np.arange(fibres, dtype=np.int32) io += ix.size if ox is None: ox = ix ob = ib else: all_ids.append(np.ascontiguousarray(ox.T).reshape(-1)) ob = io + c * np.arange(fibres, dtype=np.int32) io += ox.size if k <= 16: shape = (c, fibres) desc = np.empty(shape + (3,), dtype=np.int32) desc[:, :, 0] = ox desc[:, :, 1] = ib[None, :] desc[:, :, 2] = co + k * np.arange(c, dtype=np.int32)[:, None] sm[k].append(desc.reshape(-1, 3)) else: tiles = (c + 31) // 32 desc = np.empty((tiles, fibres, 6), dtype=np.int32) desc[:, :, 0] = ib desc[:, :, 1] = ob desc[:, :, 2] = co desc[:, :, 3] = k desc[:, :, 4] = c desc[:, :, 5] = 32 * np.arange(tiles)[:, None] bg.append(desc.reshape(-1, 6)) co += k * c self.blocks.clear() self.sizes = {k: store(np.concatenate(v)) for k, v in sm.items()} self.large = store(np.concatenate(bg)) if bg else None self.ids = store(np.concatenate(all_ids)) if all_ids else None self.coeff = store(np.concatenate(all_coeff)) if all_coeff else None def apply(self, dst, src, second=None): b = src.shape[1] tile = min(128, max(32, triton.next_power_of_2(b))) for k, desc in self.sizes.items(): _small[(triton.cdiv(len(desc), 8), triton.cdiv(b, tile))]( dst, src, second if second is not None else src, len(src), second is not None, self.ids, self.coeff, desc, len(desc), b, k, 8, tile, ) if self.large is not None: _large[(len(self.large), triton.cdiv(b, tile))]( dst, src, second if second is not None else src, len(src), second is not None, self.ids, self.coeff, self.large, b, 32, 32, tile, ) class BinaryReadout: def __init__(self, monomials, lam, cache=None, store=gpu, active_rows=None): l, m, k = lam factors = {} passes = defaultdict(Contractions) final = Contractions() scale = np.ones(len(monomials), dtype=np.uint8) coupling_cache = {} nout = 0 for groups, layouts in top_profiles(monomials): for t, r in groups: if (t, r) not in factors: factors[t, r] = Strings(t, r, m, cache) fs = [factors[g] for g in groups] for ww, ids in layouts.items(): mats = [f.matrices[w] for f, w in zip(fs, ww)] dims = [len(a) for a in mats] grid = ids.reshape(dims) depth = 0 scalar = 1 live = None if active_rows is not None: # Only the t=0 factor can contain y^10. All other tensor fibres share this mask. live = grid.reshape(dims[0], -1)[:, 0] < active_rows if not np.any(live): layouts[ww] = grid continue for axis, ((t, r), w, mat) in enumerate(zip(groups, ww, mats)): if len(mat) == 1: scalar = scalar * int(mat[0, 0]) % P else: ix = np.moveaxis(grid, axis, 0).reshape(len(mat), -1) if axis == 0 and live is not None and not np.all(live): passes[depth].add((t, r, w), mat[live], ix[live], ix) else: passes[depth].add((t, r, w), mat, ix) depth += 1 # Each weight fibre alternates banks only when one of its own maps acts. layouts[ww] = grid + (depth % 2) * len(monomials) scale[ids] = scalar for names in itertools.product(*(f.types for f in fs)): spins, ns, base = zip(*names) h = m - sum(base) if h < 0 or 2 * h > sum(spins): continue key = (spins, h) if key not in coupling_cache: cm = binary.coupling(spins, h) coupling_cache[key] = None if cm is None else (cm[0], center(cm[1])) cm = coupling_cache[key] if cm is None: continue sub, mat = cm copies = prod(ns) ix = np.empty((len(sub), copies), np.int32) for i, depth in enumerate(sub): ww = tuple(s + q for s, q in zip(base, depth)) grid = layouts[ww] positions = [f.positions[s, w] for f, s, w in zip(fs, base, ww)] ix[i] = grid[np.ix_(*positions)].reshape(-1) c = mat.shape[1] ox = np.arange(nout, nout + c * copies, dtype=np.int32).reshape(copies, c).T final.add(key, mat, ix, ox) nout += c * copies self.passes = [] for _, op in sorted(passes.items()): if op.blocks: op.finish(store) self.passes.append(op) final.finish(store) self.final = final self.size = nout self.scale = store(scale) def apply(self, raw): b = raw.shape[1] tile = min(128, max(32, triton.next_power_of_2(b))) _scale[(triton.cdiv(len(raw), 8), triton.cdiv(b, tile))]( raw, self.scale, len(raw), b, 8, tile ) tmp = torch.empty_like(raw) banks = (raw, tmp) for i, op in enumerate(self.passes): op.apply(banks[(i + 1) % 2], banks[i % 2]) out = torch.empty((self.size, b), dtype=torch.uint8, device="cuda") self.final.apply(out, raw, tmp) return out def root_order(graphs, parts, total): """Coordinates of the second root in the original monomial order.""" result = [] for part in range(parts): with (graphs / f"root13-{part}.bin").open("rb") as source: count = int(np.fromfile(source, dtype="