lyraaaa's picture
Add lg and variant style spaces
725d217 verified
Raw History Blame Contribute Delete
1.57 kB
"""Style references for Krea 2: an integer code becomes a block of prompt tokens.
from sref import style_block
block = style_block(1234567, strength=6.0) # numpy float32 [108, 6144]
Append the block to the prompt's tokens after text fusion (see README.md).
"""
from pathlib import Path
import numpy as np
SPACES = {"default": "sref_space.npz", "lg": "sref_space_lg.npz", "variant": "sref_space_variant.npz"}
_loaded = {}
def space(name: str = "default"):
"""(basis [64, 108, 6144], sd [64]) of a style space. The same code is a different style in each space."""
if name not in _loaded:
f = np.load(Path(__file__).parent / SPACES[name], allow_pickle=False)
_loaded[name] = (f["basis"].astype(np.float32), f["sd"].astype(np.float32))
return _loaded[name]
def coords(code: int, space_name: str = "default") -> np.ndarray:
"""The 64 style coordinates for a code."""
_, sd = space(space_name)
return np.random.default_rng(code).standard_normal(len(sd)).astype(np.float32) * sd
def style_block(code: int, strength: float = 6.0, space_name: str = "default") -> np.ndarray:
"""The token block for a code: [108, 6144]."""
return block_from_coords(coords(code, space_name), strength, space_name)
def block_from_coords(z: np.ndarray, strength: float = 6.0, space_name: str = "default") -> np.ndarray:
"""The token block for 64 coordinates you supply, for blending or editing styles."""
basis, _ = space(space_name)
return strength * np.tensordot(np.asarray(z, dtype=np.float32), basis, axes=1)