# Pentachoron-driven guidance (the Formula node's space: "noise (eps)"). Any latent whose channel count divides by 4:
# SDXL / SD1.5 (4 channels: one pentachoron) and Anima and the other Wan-VAE models (16 channels: four, 16 = 4 x 4).
# The pentachoron is the 4-simplex: 5 vertices in 4 dimensions. Each pixel's plain-CFG push is read on the 5 vertices
# of a regular pentachoron in every group of 4 channels and rebuilt with the aleph weighting
# sum_k sinh(z_k) v_k / sum_j cosh(z_j): signed amplitudes, never a selector. Small pushes come back as plain CFG;
# a pixel's push in a group is capped at 4 tau, and a pixel pushing hard along one vertex damps its other four.
# Flow-matching models: noise space is the noise itself and the shift is already inside sigma; the push
# (w - 1)(c - u) is the same line in every space.
k = 1.0          # temperature: larger = closer to plain CFG (1e6 = plain CFG), smaller = a firmer per-pixel limit
r = 1 / math.sqrt(5)
V = torch.tensor([[1., 1., 1., -r], [1., -1., -1., -r], [-1., 1., -1., -r], [-1., -1., 1., -r],
                  [0., 0., 0., 4 * r]], dtype=c.dtype, device=c.device) * (math.sqrt(5) / 4)   # 5 unit vertices, cos -1/4
g = (w - 1) * (c - u)                                                  # plain CFG's push past the conditional
assert g.shape[1] % 4 == 0, "the pentachoron formula needs a channel count divisible by 4"
G = g.reshape(g.shape[0], g.shape[1] // 4, 4, *g.shape[2:])            # groups of 4 channels, one pentachoron each
a = torch.einsum('kc,bgc...->bgk...', V, G)                            # the push's 5 vertex coordinates per pixel
tau = k * a.pow(2).mean(dim=tuple(range(1, a.ndim)), keepdim=True).sqrt() + 1e-12   # per image
z = a / tau
m = z.abs().amax(dim=2, keepdim=True)                                  # overflow guard; cancels exactly
ep, en = torch.exp(z - m), torch.exp(-z - m)
P = 4 * tau * torch.einsum('kc,bgk...->bgc...', V, ep - en) / (ep + en).sum(dim=2, keepdim=True)
result = c + P.reshape(g.shape)
