Download src/hyperneat.py from Moltboss/hyperneat-r8-compress: direct link, hf CLI and curl.
- Browser
- Download file 1.78 kB
-
https://huggingface.co/Moltboss/hyperneat-r8-compress/resolve/main/src/hyperneat.py
- Command line
-
hf download hf://Moltboss/hyperneat-r8-compress/src/hyperneat.py
-
curl -L -o hyperneat.py https://huggingface.co/Moltboss/hyperneat-r8-compress/resolve/main/src/hyperneat.py
1.78 kB
| """Fixed-topology HyperNEAT-style CPPN in JAX.""" | |
| from __future__ import annotations | |
| import math | |
| from typing import Tuple | |
| import jax.numpy as jnp | |
| import numpy as np | |
| IN, H1, H2, OUT = 8, 8, 8, 1 | |
| LAYER_SHAPES = ((IN, H1), (H1,), (H1, H2), (H2,), (H2, OUT), (OUT,)) | |
| N_PARAMS = int(sum(math.prod(s) for s in LAYER_SHAPES)) | |
| def unpack_params(theta: jnp.ndarray): | |
| out = [] | |
| i = 0 | |
| for shape in LAYER_SHAPES: | |
| n = int(math.prod(shape)) | |
| out.append(theta[i : i + n].reshape(shape)) | |
| i += n | |
| return tuple(out) | |
| def cppn_keys(theta: jnp.ndarray, n: int) -> jnp.ndarray: | |
| w1, b1, w2, b2, w3, b3 = unpack_params(theta) | |
| xs = jnp.linspace(-1.0, 1.0, n) | |
| zeros = jnp.zeros_like(xs) | |
| dist = jnp.abs(xs) | |
| ones = jnp.ones_like(xs) | |
| s1 = jnp.sin(2 * jnp.pi * xs) | |
| s2 = jnp.sin(4 * jnp.pi * xs) | |
| s4 = jnp.sin(8 * jnp.pi * xs) | |
| s8 = jnp.sin(16 * jnp.pi * xs) | |
| inp = jnp.stack([xs, zeros, dist, ones, s1, s2, s4, s8], axis=-1) | |
| h = jnp.tanh(inp @ w1 + b1) | |
| h = jnp.tanh(h @ w2 + b2) | |
| return (h @ w3 + b3)[:, 0] | |
| def reorder(payload: jnp.ndarray, theta: jnp.ndarray): | |
| keys = cppn_keys(theta, payload.shape[0]) | |
| order = jnp.argsort(keys, stable=True) | |
| return payload[order], order | |
| def restore(reordered: jnp.ndarray, order: jnp.ndarray) -> jnp.ndarray: | |
| inv = jnp.empty_like(order) | |
| inv = inv.at[order].set(jnp.arange(order.shape[0])) | |
| return reordered[inv] | |
| def theta_bytes(theta: np.ndarray) -> bytes: | |
| return np.asarray(theta, dtype=np.float16).tobytes() | |
| def theta_from_bytes(blob: bytes) -> np.ndarray: | |
| arr = np.frombuffer(blob, dtype=np.float16).astype(np.float32) | |
| if arr.size != N_PARAMS: | |
| raise ValueError(f"expected {N_PARAMS} params, got {arr.size}") | |
| return arr | |