thalismind commited on
Commit ·
40c5ebe
0
Parent(s):
feat: add Solstice 80M preview release bundle
Browse filesAdd first-run Safetensors checkpoints, distilled students, and ONNX exports.
Include embedded model diagrams, loss curves, and sample inference code.
Files changed (31)
- .gitattributesAdded+37
- README.mdAdded+111
- config.jsonAdded+48
- generate.pyAdded+181
- images/architecture.pngAdded
- images/distillation.pngAdded
- images/heldout-loss.pngAdded
- images/training-loss.pngAdded
- model.pyAdded+310
- onnx/72k/student-10-step/bf16.onnxAdded+3
- onnx/72k/student-10-step/bf16w.onnxAdded+3
- onnx/72k/student-10-step/fp32.onnxAdded+3
- onnx/72k/student-10-step/int8_dynamic.onnxAdded+3
- onnx/72k/student-5-step/bf16.onnxAdded+3
- onnx/72k/student-5-step/bf16w.onnxAdded+3
- onnx/72k/student-5-step/fp32.onnxAdded+3
- onnx/72k/student-5-step/int8_dynamic.onnxAdded+3
- onnx/72k/teacher/bf16.onnxAdded+3
- onnx/72k/teacher/bf16w.onnxAdded+3
- onnx/72k/teacher/fp32.onnxAdded+3
- onnx/72k/teacher/int8_dynamic.onnxAdded+3
- pytorch/100k/guidance-40-step.safetensorsAdded+3
- pytorch/100k/student-10-step.safetensorsAdded+3
- pytorch/100k/student-20-step.safetensorsAdded+3
- pytorch/100k/student-5-step.safetensorsAdded+3
- pytorch/100k/teacher.safetensorsAdded+3
- pytorch/72k/guidance-40-step.safetensorsAdded+3
- pytorch/72k/student-10-step.safetensorsAdded+3
- pytorch/72k/student-20-step.safetensorsAdded+3
- pytorch/72k/student-5-step.safetensorsAdded+3
- pytorch/72k/teacher.safetensorsAdded+3
12345678910111213141516171819202122232425262728293031323334353637*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111# Solstice 80M
**Private, invite-only release. Please do not redistribute.**
- **Parent model:** [Bhoidy/nyx-image-36m](https://huggingface.co/Bhoidy/nyx-image-36m)- **Text encoder:** [google/t5gemma-2b-2b-ul2](https://huggingface.co/google/t5gemma-2b-2b-ul2)
Solstice 80M generates 32×32 RGBA pixel-art sprites from text. It uses a rectified-flow hourglass diffusion transformer with a frozen T5Gemma-2b text encoder.
This package contains the completed first run's **72k primary** and **100k reference** checkpoints, their distilled students, and ONNX exports. All PyTorch weights are EMA-only Safetensors; optimizer and training state are omitted. The shared architecture and sampling parameters are in [`config.json`](config.json).
## Usage
The [`generate.py`](generate.py) example supports both Safetensors and ONNX and returns a 32×32 RGBA Pillow image. It loads [`google/t5gemma-2b-2b-ul2`](https://huggingface.co/google/t5gemma-2b-2b-ul2) from Hugging Face on first use. The model definition is in [`model.py`](model.py).
### Safetensors on GPU
```python# pip install torch transformers safetensors numpy pillowfrom generate import generate
image = generate( "a red potion bottle", "pytorch/72k/student-5-step.safetensors", text_encoder="google/t5gemma-2b-2b-ul2", device="cuda", # use "cpu" for CPU inference)image.save("potion.png")```
### ONNX on CPU
```python# pip install torch transformers onnxruntime numpy pillowfrom generate import generate
image = generate( "a red potion bottle", "onnx/72k/student-5-step/fp32.onnx", text_encoder="google/t5gemma-2b-2b-ul2", device="cpu", # use "cuda" with onnxruntime-gpu and a CUDA-compatible export)image.save("potion.png")```
The same examples work from the command line:
```shpython generate.py pytorch/72k/student-5-step.safetensors \ --prompt "a red potion bottle" --output potion.png --device cuda```
Input is a short sprite description. Output is a 32×32 RGBA image with binary transparency; palette quantization is recommended before use.
## Model diagrams


## Safetensors checkpoints
The 72k chain is primary. Its 20-, 10-, and 5-step students use the selected best checkpoints. The 100k chain is retained for reference and uses its end-of-round students.
| Model | Euler steps | Forwards per sprite | 72k primary | 100k reference ||---|---:|---:|---|---|| Teacher | 40 | 70 with CFG 4 | [Safetensors](pytorch/72k/teacher.safetensors) | [Safetensors](pytorch/100k/teacher.safetensors) || Guidance-distilled | 40 | 40 | [Safetensors](pytorch/72k/guidance-40-step.safetensors) | [Safetensors](pytorch/100k/guidance-40-step.safetensors) || Student | 20 | 20 | [Safetensors](pytorch/72k/student-20-step.safetensors) | [Safetensors](pytorch/100k/student-20-step.safetensors) || Student | 10 | 10 | [Safetensors](pytorch/72k/student-10-step.safetensors) | [Safetensors](pytorch/100k/student-10-step.safetensors) || Student | 5 | 5 | [Safetensors](pytorch/72k/student-5-step.safetensors) | [Safetensors](pytorch/100k/student-5-step.safetensors) |
Teacher checkpoints have 76.6M parameters and require external classifier-free guidance. Distilled checkpoints add a guidance embedding and accept guidance scale `w` directly; the usual range is 1–7. When constructing a student, apply `student_constructor` from the shared config to set `guidance=true`.
## ONNX exports
ONNX exports are available for the **72k teacher**, **10-step student**, and **5-step student**. Each file contains one model forward, opset 18, with dynamic batch size. Sampling and prompt encoding are external.
| Variant | Teacher | 10-step student | 5-step student | Execution provider ||---|---|---|---|---|| fp32 | [ONNX](onnx/72k/teacher/fp32.onnx) | [ONNX](onnx/72k/student-10-step/fp32.onnx) | [ONNX](onnx/72k/student-5-step/fp32.onnx) | CPU, CUDA || bf16 | [ONNX](onnx/72k/teacher/bf16.onnx) | [ONNX](onnx/72k/student-10-step/bf16.onnx) | [ONNX](onnx/72k/student-5-step/bf16.onnx) | CUDA only || bf16 weights, fp32 compute | [ONNX](onnx/72k/teacher/bf16w.onnx) | [ONNX](onnx/72k/student-10-step/bf16w.onnx) | [ONNX](onnx/72k/student-5-step/bf16w.onnx) | CPU, CUDA || dynamic int8 | [ONNX](onnx/72k/teacher/int8_dynamic.onnx) | [ONNX](onnx/72k/student-10-step/int8_dynamic.onnx) | [ONNX](onnx/72k/student-5-step/int8_dynamic.onnx) | CPU |
Inputs are `x` `[B,4,32,32]`, `t` `[B]`, `pool` `[B,2304]`, `tokens` `[B,64,2304]`, and `mask` `[B,64]`. Students additionally take `w` `[B]`. Output is velocity `v` `[B,4,32,32]`.
## Loss curves


### First-run evaluation loss
| Checkpoint | Train | Held-out designs | Held-out sprites ||---|---:|---:|---:|| 72k primary | 0.0865 | 0.1208 | 0.0775 || 100k reference | 0.0786 | 0.1253 | 0.0734 |
### Distilled-model held-out flow loss
Measured at guidance scale 1; lower is better.
| Model | 72k primary chain | 100k reference chain ||---|---:|---:|| Teacher | 0.1211 | 0.1253 || Guidance-distilled, 40 steps | 0.1226 | 0.1253 || Student, 20 steps | 0.1225 | 0.1245 || Student, 10 steps | 0.1239 | 0.1252 || Student, 5 steps | 0.1303 | 0.1389 |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "model_type": "solstice", "model_class": "SolsticeGenerator", "image_size": 32, "constructor": { "text_dim": 2304, "pool_dim": 2304, "text_tokens": 64, "text_norm": true, "cond_dim": 384, "outer_blocks": 2, "core_blocks": 20, "outer_dim": 256, "core_dim": 384, "outer_heads": 4, "core_heads": 6, "outer_hidden": 768, "core_hidden": 1024, "stem": 64, "channels": 4, "phase_up": false, "ada_rank": 0, "guidance": false, "pred": "v", "self_cond": false, "pix_blocks": 0 }, "text_encoder": { "name": "google/t5gemma-2b-2b-ul2", "frozen": true, "pooling": "mean", "prompt_template": "pixel art, 32px, <caption>" }, "sampling": { "solver": "euler", "teacher_steps": 40, "teacher_cfg": 4.0, "guidance_interval_end": 0.75, "distilled_guidance_range": [1.0, 7.0] }, "weights": { "format": "safetensors", "selection": "ema" }, "student_constructor": { "guidance": true }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""Generate one 32x32 RGBA sprite from a Safetensors checkpoint or ONNX export.
Dependencies: torch transformers safetensors numpy pillowONNX also needs onnxruntime (CPU) or onnxruntime-gpu (CUDA).The text encoder is downloaded from Hugging Face on first use."""
import argparseimport jsonimport refrom pathlib import Path
import numpy as npimport torchfrom PIL import Image
ROOT = Path(__file__).resolve().parentCONFIG = json.loads((ROOT / "config.json").read_text())TEXT_ENCODER = "google/t5gemma-2b-2b-ul2"
def resolve_device(name="auto"): if name == "auto": name = "cuda" if torch.cuda.is_available() else "cpu" if name == "cuda" and not torch.cuda.is_available(): raise RuntimeError("CUDA was requested but is not available to PyTorch") return torch.device(name)
class TextEncoder: def __init__(self, name, device): from transformers import AutoTokenizer, T5GemmaEncoderModel
self.device = device self.tokenizer = AutoTokenizer.from_pretrained(name) self.tokenizer.padding_side = "right" dtype = torch.bfloat16 if device.type == "cuda" else torch.float32 self.encoder = T5GemmaEncoderModel.from_pretrained( name, dtype=dtype, is_encoder_decoder=False ).to(device).eval().requires_grad_(False)
@torch.inference_mode() def encode(self, prompt): # The empty string is deliberately unprefixed: it is the unconditional prompt. strings = [CONFIG["text_encoder"]["prompt_template"].replace("<caption>", prompt), ""] batch = self.tokenizer( strings, padding="max_length", max_length=64, truncation=True, return_tensors="pt" ).to(self.device) mask = batch.attention_mask.bool() hidden = self.encoder(**batch).last_hidden_state.float() hidden = torch.where(mask[..., None], hidden, 0.0) pool = hidden.sum(1) / mask.sum(1).clamp(min=1)[:, None] condition = (hidden, mask, pool) return tuple(x[0:1] for x in condition), tuple(x[1:2] for x in condition)
class TorchBackend: def __init__(self, checkpoint, device): from safetensors import safe_open from safetensors.torch import load_file from model import SolsticeGenerator
with safe_open(checkpoint, framework="pt", device="cpu") as f: metadata = f.metadata() or {} self.guided = metadata.get("guidance_distilled") == "true" self.steps = int(metadata.get("sampling_steps", 40)) kwargs = dict(CONFIG["constructor"], guidance=self.guided) self.model = SolsticeGenerator(**kwargs) self.model.load_state_dict(load_file(checkpoint), strict=True) self.model = self.model.to(device).eval().requires_grad_(False) self.device = device
def call(self, x, t, condition, guidance): tokens, mask, pool = condition tt = torch.full((1,), t, device=self.device) w = torch.full((1,), guidance, device=self.device) if self.guided else None with torch.autocast("cuda", torch.bfloat16, enabled=self.device.type == "cuda"): return self.model(x, tt, pool, tokens, mask, w).float()
class OnnxBackend: def __init__(self, checkpoint, device): import onnxruntime as ort
requested = "CUDAExecutionProvider" if device.type == "cuda" else "CPUExecutionProvider" if requested not in ort.get_available_providers(): raise RuntimeError(f"{requested} is not available; install the matching ONNX Runtime package") self.session = ort.InferenceSession(str(checkpoint), providers=[requested]) self.inputs = {x.name for x in self.session.get_inputs()} self.guided = "w" in self.inputs self.steps = steps_from_path(checkpoint) self.device = torch.device("cpu")
def call(self, x, t, condition, guidance): tokens, mask, pool = condition feed = { "x": x.numpy().astype(np.float32), "t": np.full((1,), t, np.float32), "pool": pool.cpu().numpy().astype(np.float32), "tokens": tokens.cpu().numpy().astype(np.float32), "mask": mask.cpu().numpy().astype(bool), } if self.guided: feed["w"] = np.full((1,), guidance, np.float32) return torch.from_numpy(self.session.run(None, feed)[0])
def steps_from_path(path): for part in Path(path).parts: match = re.search(r"(?:student|guidance)-(\d+)-step", part) if match: return int(match.group(1)) return 40
@torch.inference_mode()def euler_sample(backend, condition, uncondition, steps, guidance, seed): generator = torch.Generator(device=backend.device).manual_seed(seed) x = torch.randn((1, 4, 32, 32), generator=generator, device=backend.device) schedule = torch.linspace(1, 0, steps + 1).tolist() for t0, t1 in zip(schedule, schedule[1:]): conditional = backend.call(x, t0, condition, guidance) if backend.guided or guidance == 1.0 or t0 > 0.75 + 1e-5: velocity = conditional else: unconditional = backend.call(x, t0, uncondition, guidance) velocity = unconditional + guidance * (conditional - unconditional) x = x + (t1 - t0) * velocity return x
def to_image(x): x = x.float().clamp(-1, 1).cpu() rgb = ((x[:, :3] + 1) * 127.5).round().clamp(0, 255) opaque = x[:, 3] > 0 alpha = opaque.float() * 255 rgba = torch.cat([rgb * opaque[:, None], alpha[:, None]], 1) array = rgba.permute(0, 2, 3, 1).to(torch.uint8).numpy()[0] return Image.fromarray(array, "RGBA")
def generate(prompt, checkpoint, seed=0, steps=None, guidance=4.0, device="auto", text_encoder=None): """Return a 32x32 PIL RGBA image. Checkpoint may be .safetensors or .onnx.""" device = resolve_device(device) checkpoint = Path(checkpoint) if checkpoint.suffix == ".safetensors": backend = TorchBackend(checkpoint, device) elif checkpoint.suffix == ".onnx": backend = OnnxBackend(checkpoint, device) else: raise ValueError("Choose a .safetensors or .onnx model") steps = steps or backend.steps if steps < 1: raise ValueError("steps must be positive") encoder_name = text_encoder or TEXT_ENCODER condition, uncondition = TextEncoder(encoder_name, device).encode(prompt) result = euler_sample(backend, condition, uncondition, steps, guidance, seed) return to_image(result)
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("checkpoint", type=Path, help=".safetensors or .onnx model") parser.add_argument("--prompt", required=True) parser.add_argument("--output", required=True, type=Path) parser.add_argument("--seed", type=int, default=0) parser.add_argument("--steps", type=int, help="default: the checkpoint's distilled step count") parser.add_argument("--guidance", type=float, default=4.0) parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto") parser.add_argument("--text-encoder", default=TEXT_ENCODER) args = parser.parse_args() image = generate( args.prompt, args.checkpoint, args.seed, args.steps, args.guidance, args.device, args.text_encoder, ) image.save(args.output) print(f"Saved {args.output} ({image.width}x{image.height})")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6, affine=True): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) if affine else None
def forward(self, x): y = (x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype) return y * self.weight if self.weight is not None else y
class Rotary2D(nn.Module): def __init__(self, h, w, head_dim, base=10_000.0): super().__init__() pair = head_dim // 4 inv = 1.0 / (base ** (np.arange(pair, dtype=np.float64) / pair)) fr = np.repeat(np.outer(np.arange(h), inv), w, axis=0) fc = np.tile(np.outer(np.arange(w), inv), (h, 1)) for name, val in (("cos_row", np.cos(fr)), ("sin_row", np.sin(fr)), ("cos_col", np.cos(fc)), ("sin_col", np.sin(fc))): self.register_buffer(name, torch.from_numpy(val).float(), persistent=False)
@staticmethod def _rot(v, cos, sin): a, b = v.chunk(2, -1) return torch.cat([a * cos - b * sin, a * sin + b * cos], -1)
def forward(self, q, k): cr, sr, cc, sc = (getattr(self, n).to(q.dtype) for n in ("cos_row", "sin_row", "cos_col", "sin_col"))
def rot(x): r, c = x.chunk(2, -1) return torch.cat([self._rot(r, cr, sr), self._rot(c, cc, sc)], -1) return rot(q), rot(k)
class SelfAttention(nn.Module): def __init__(self, dim, heads): super().__init__() self.heads, self.hd = heads, dim // heads self.qkv = nn.Linear(dim, 3 * dim, bias=False) self.proj = nn.Linear(dim, dim, bias=False) self.q_norm, self.k_norm = RMSNorm(self.hd), RMSNorm(self.hd)
def forward(self, x, rope): b, n, d = x.shape q, k, v = self.qkv(x).view(b, n, 3, self.heads, self.hd).permute(2, 0, 3, 1, 4).unbind(0) q, k = rope(self.q_norm(q), self.k_norm(k)) return self.proj(F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(b, n, d))
class CrossAttention(nn.Module): def __init__(self, dim, heads): super().__init__() self.heads, self.hd = heads, dim // heads self.q, self.k, self.v, self.proj = (nn.Linear(dim, dim, bias=False) for _ in range(4)) self.q_norm, self.k_norm = RMSNorm(self.hd), RMSNorm(self.hd)
def forward(self, x, ctx, mask): b, n, d = x.shape m = ctx.shape[1] q = self.q_norm(self.q(x).view(b, n, self.heads, self.hd).transpose(1, 2)) k = self.k_norm(self.k(ctx).view(b, m, self.heads, self.hd).transpose(1, 2)) v = self.v(ctx).view(b, m, self.heads, self.hd).transpose(1, 2) out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask[:, None, None, :]) return self.proj(out.transpose(1, 2).reshape(b, n, d))
class SwiGLU(nn.Module): def __init__(self, dim, hidden): super().__init__() self.w12 = nn.Linear(dim, 2 * hidden) self.w3 = nn.Linear(hidden, dim)
def forward(self, x): a, b = self.w12(x).chunk(2, -1) return self.w3(F.silu(a) * b)
class DiTBlock(nn.Module): """ada_rank 0: Nyx's per-block AdaLN Linear(cond, 6d). ada_rank r > 0: adaLN-single with a per-block low-rank residual (nyx-efficiency.md section 1): ada_i(cond) = g_i * shared_d(cond) + B_i(A_i(cond)) + E_i shared_d is one Linear per width (owned by the model); g_i is a per-block gain (6d) so a new block can start as exact identity (g = B = E = 0)."""
def __init__(self, dim, heads, hidden, cond_dim, ada_rank=0): super().__init__() self.ada_rank = ada_rank if ada_rank: self.ada_A = nn.Linear(cond_dim, ada_rank, bias=False) self.ada_B = nn.Linear(ada_rank, 6 * dim, bias=False) self.ada_E = nn.Parameter(torch.zeros(6 * dim)) self.ada_g = nn.Parameter(torch.ones(6 * dim)) else: self.ada = nn.Linear(cond_dim, 6 * dim) self.norm_in = RMSNorm(dim, affine=False) self.norm_mlp = RMSNorm(dim, affine=False) self.cross_norm = RMSNorm(dim) self.self_attn = SelfAttention(dim, heads) self.cross_attn = CrossAttention(dim, heads) self.mlp = SwiGLU(dim, hidden) self.cross_gate = nn.Parameter(torch.zeros(1))
def modulation(self, cond, shared=None): if self.ada_rank: return self.ada_g * shared + self.ada_B(self.ada_A(cond)) + self.ada_E return self.ada(cond)
def forward(self, x, cond, rope, ctx, mask, shared=None): s1, c1, g1, s2, c2, g2 = (t.unsqueeze(1) for t in self.modulation(cond, shared).chunk(6, -1)) x = x + g1 * self.self_attn(self.norm_in(x) * (1 + c1) + s1, rope) x = x + self.cross_gate * self.cross_attn(self.cross_norm(x), ctx, mask) return x + g2 * self.mlp(self.norm_mlp(x) * (1 + c2) + s2)
class ConvResBlock(nn.Module): def __init__(self, ch, cond_dim, groups=8): super().__init__() self.norm = nn.GroupNorm(groups, ch) self.ada = nn.Linear(cond_dim, 2 * ch) self.conv = nn.Conv2d(ch, ch, 3, padding=1)
def forward(self, x, cond): scale, shift = self.ada(cond)[:, :, None, None].chunk(2, 1) return x + self.conv(F.silu(self.norm(x) * (1 + scale) + shift))
# rows of a 3x3 kernel that land on each of the two low-res rows read by output phase a_FOLD = torch.tensor([[[1., 0., 0.], [0., 1., 1.]], # a = 0: input rows (i-1, i) [[1., 1., 0.], [0., 0., 1.]]]) # a = 1: input rows (i, i+1)
class PhaseConv(nn.Conv2d): """A 3x3 conv applied after nearest-2x upsampling, computed exactly at the low resolution (docs/research/nyx-efficiency.md section 2): output pixel (2i+a, 2j+b) reads a 2x2 low-res window, so the 9 taps fold into one 2x2 kernel per phase: 16 MACs per low-res position and channel pair instead of 36. Same parameter (a 3x3 weight), so Nyx weights load unchanged. `forward(x_lowres)` == `conv2d(interpolate(x_lowres, 2, "nearest"), weight, padding=1)`."""
def __init__(self, cin, cout, phase=True): super().__init__(cin, cout, 3, padding=1) self.phase = phase
def forward(self, x): if not self.phase: return super().forward(F.interpolate(x, scale_factor=2, mode="nearest")) b, _, h, w = x.shape R = _FOLD.to(self.weight) outs = [] for a in (0, 1): for c in (0, 1): k = torch.einsum("rk,oikl,cl->oirc", R[a], self.weight, R[c]) outs.append(F.conv2d(F.pad(x, (1 - c, c, 1 - a, a)), k, self.bias)) y = torch.stack(outs, 2).view(b, -1, 2, 2, h, w) # [B, O, a, c, H, W] return y.permute(0, 1, 4, 2, 5, 3).reshape(b, -1, 2 * h, 2 * w)
def sinusoidal(t, dim=256, max_period=10_000.0): half = dim // 2 inv = 1.0 / (max_period ** (torch.arange(half, device=t.device, dtype=torch.float32) / half)) f = t.float()[:, None] * inv[None] return torch.cat([f.cos(), f.sin()], -1)
class SolsticeGenerator(nn.Module): def __init__(self, text_dim=768, pool_dim=768, text_tokens=32, text_norm=True, cond_dim=384, outer_blocks=2, core_blocks=8, outer_dim=256, core_dim=384, outer_heads=4, core_heads=6, outer_hidden=768, core_hidden=1024, stem=64, channels=4, phase_up=False, ada_rank=0, guidance=False, pred="v", self_cond=False, pix_blocks=0, pix_heads=4, pix_hidden=384): super().__init__() # pred "x0" (2026-12-02, change 5): the head predicts the clean sprite and forward() returns the velocity # (x_t - x0_hat) / t, so losses, samplers and exports keep working with v. self_cond (change 3): 4 more # input channels carry the previous x0 estimate (zeros when absent, so the model also runs without it). self.pred, self.self_cond = pred, self_cond self.text_tokens, self.pool_dim, self.channels = text_tokens, pool_dim, channels self.checkpoint = False self.outer_dim, self.core_dim = outer_dim, core_dim self.time_mlp = nn.Sequential(nn.Linear(256, cond_dim), nn.SiLU(), nn.Linear(cond_dim, cond_dim)) if pool_dim: self.pool_mlp = nn.Sequential(nn.Linear(pool_dim, cond_dim), nn.SiLU(), nn.Linear(cond_dim, cond_dim)) self.pool_norm = RMSNorm(pool_dim) if text_norm else nn.Identity() self.text_norm = RMSNorm(text_dim) if text_norm else nn.Identity() self.text_proj_outer = nn.Linear(text_dim, outer_dim) self.text_proj_inner = nn.Linear(text_dim, core_dim) self.stem_conv = nn.Conv2d(channels * (2 if self_cond else 1), stem, 3, padding=1) self.stem_blocks = nn.ModuleList([ConvResBlock(stem, cond_dim) for _ in range(2)]) self.down_32 = nn.Conv2d(stem, outer_dim, 2, stride=2) self.rope_16 = Rotary2D(16, 16, outer_dim // outer_heads) self.ada_rank = ada_rank if ada_rank: self.ada_shared_outer = nn.Linear(cond_dim, 6 * outer_dim) self.ada_shared_core = nn.Linear(cond_dim, 6 * core_dim) self.outer_encoder = nn.ModuleList([DiTBlock(outer_dim, outer_heads, outer_hidden, cond_dim, ada_rank) for _ in range(outer_blocks)]) self.down_16 = nn.Conv2d(outer_dim, core_dim, 2, stride=2) self.rope_8 = Rotary2D(8, 8, core_dim // core_heads) self.bottleneck = nn.ModuleList([DiTBlock(core_dim, core_heads, core_hidden, cond_dim, ada_rank) for _ in range(core_blocks)]) self.up_16 = PhaseConv(core_dim, outer_dim, phase_up) self.fuse_16 = nn.Conv2d(2 * outer_dim, outer_dim, 1) self.outer_decoder = nn.ModuleList([DiTBlock(outer_dim, outer_heads, outer_hidden, cond_dim, ada_rank) for _ in range(outer_blocks)]) self.up_32 = PhaseConv(outer_dim, stem, phase_up) self.fuse_32 = nn.Conv2d(2 * stem, stem, 1) self.out_blocks = nn.ModuleList([ConvResBlock(stem, cond_dim) for _ in range(2)]) # full-resolution attention (2026-12-02, change 2 / A/B "e"): DiT blocks over all 32x32 pixels at the stem # width, after the head's skip fuse, so each pixel is decided while attending to the whole sprite and the text self.pix_blocks = nn.ModuleList([DiTBlock(stem, pix_heads, pix_hidden, cond_dim) for _ in range(pix_blocks)]) if pix_blocks: self.rope_32 = Rotary2D(32, 32, stem // pix_heads) self.text_proj_pix = nn.Linear(text_dim, stem) self.out_norm = nn.GroupNorm(8, stem) self.out_conv = nn.Conv2d(stem, channels, 3, padding=1) self.apply(self._init) for blk in self.dit_blocks(): if ada_rank: # from scratch: zero B_i and the shared maps keep AdaLN-Zero's identity start nn.init.zeros_(blk.ada_B.weight) else: nn.init.zeros_(blk.ada.weight) nn.init.zeros_(blk.ada.bias) nn.init.zeros_(blk.cross_gate) if ada_rank: for lin in (self.ada_shared_outer, self.ada_shared_core): nn.init.zeros_(lin.weight) nn.init.zeros_(lin.bias) nn.init.zeros_(self.out_conv.weight) nn.init.zeros_(self.out_conv.bias) # guidance-scale embedding for CFG distillation (distill.py). Built after the init above, so a # model without it draws the same random init as before; its last layer is zero, so a student # loaded from a teacher computes exactly the teacher's output until it is trained. self.w_mlp = None if guidance: self.w_mlp = nn.Sequential(nn.Linear(256, cond_dim), nn.SiLU(), nn.Linear(cond_dim, cond_dim)) nn.init.xavier_uniform_(self.w_mlp[0].weight) nn.init.zeros_(self.w_mlp[0].bias) nn.init.zeros_(self.w_mlp[2].weight) nn.init.zeros_(self.w_mlp[2].bias)
@staticmethod def _init(m): if isinstance(m, (nn.Linear, nn.Conv2d)): nn.init.xavier_uniform_(m.weight) if m.bias is not None: nn.init.zeros_(m.bias)
def dit_blocks(self): yield from self.outer_encoder yield from self.bottleneck yield from self.outer_decoder yield from self.pix_blocks
def gates(self): return [float(b.cross_gate) for b in self.dit_blocks()]
def forward(self, x, t, pool, tokens, mask, w=None, sc=None): b = x.shape[0] x_t = x if self.self_cond: x = torch.cat([x, torch.zeros_like(x) if sc is None else sc.to(x.dtype)], 1) mask = mask.clone() mask[:, 0] = True cond = self.time_mlp(sinusoidal(t).to(x.dtype)) if self.w_mlp is not None and w is not None: cond = cond + self.w_mlp(sinusoidal(w).to(x.dtype)) if self.pool_dim: cond = cond + self.pool_mlp(self.pool_norm(pool)) tok = self.text_norm(tokens) ctx_o, ctx_i = self.text_proj_outer(tok), self.text_proj_inner(tok) sh_o = self.ada_shared_outer(cond) if self.ada_rank else None sh_i = self.ada_shared_core(cond) if self.ada_rank else None h = self.stem_conv(x) for blk in self.stem_blocks: h = blk(h, cond) skip_32 = h z = self.down_32(h).flatten(2).transpose(1, 2) for blk in self.outer_encoder: z = blk(z, cond, self.rope_16, ctx_o, mask, sh_o) skip_16 = z.transpose(1, 2).reshape(b, self.outer_dim, 16, 16) z = self.down_16(skip_16).flatten(2).transpose(1, 2) for blk in self.bottleneck: if self.checkpoint and self.training: z = torch.utils.checkpoint.checkpoint(blk, z, cond, self.rope_8, ctx_i, mask, sh_i, use_reentrant=False) else: z = blk(z, cond, self.rope_8, ctx_i, mask, sh_i) h = self.up_16(z.transpose(1, 2).reshape(b, self.core_dim, 8, 8)) z = self.fuse_16(torch.cat([h, skip_16], 1)).flatten(2).transpose(1, 2) for blk in self.outer_decoder: z = blk(z, cond, self.rope_16, ctx_o, mask, sh_o) h = self.up_32(z.transpose(1, 2).reshape(b, self.outer_dim, 16, 16)) h = self.fuse_32(torch.cat([h, skip_32], 1)) if len(self.pix_blocks): z = h.flatten(2).transpose(1, 2) ctx_p = self.text_proj_pix(tok) for blk in self.pix_blocks: z = blk(z, cond, self.rope_32, ctx_p, mask) h = z.transpose(1, 2).reshape(b, -1, 32, 32) for blk in self.out_blocks: h = blk(h, cond) out = self.out_conv(F.silu(self.out_norm(h))) if self.pred == "x0": # x_t = x0 + t v -> v = (x_t - x0_hat) / t, t floored so the conversion stays bounded return (x_t - out) / t.float().clamp(min=0.05).to(out.dtype)[:, None, None, None] return out
@staticmethod def x0_of(x_t, t, v): """The clean-sprite estimate implied by a velocity: x0 = x_t - t v.""" return x_t - t[:, None, None, None] * v123version https://git-lfs.github.com/spec/v1oid sha256:46181b0b6d9bb58fd33105a0242588ebcfe98cf1ea148c215880eb3fca093f01size 159437801123version https://git-lfs.github.com/spec/v1oid sha256:5b7c0443ce247a08dbf24b47ee8f18eac7aadee58ec3d2d03f1fb830309e3b17size 159699917123version https://git-lfs.github.com/spec/v1oid sha256:7f96178c654dd10ad85735a6104cee3d1290cfb7c95e55ddc6609b291d361ffcsize 313308177123version https://git-lfs.github.com/spec/v1oid sha256:063c3ec90e3cccf709a6a2d95ab67a2a3aed2d2976daa0f265a7b1628ada6c6bsize 83301237123version https://git-lfs.github.com/spec/v1oid sha256:04f23d6efb7e0b4f7285300ec2d5674871b1e2ff1cd6e2039c1c341ff6410744size 159437801123version https://git-lfs.github.com/spec/v1oid sha256:9927d4efb5c44fa2823608dfaeac09112125e41c288753dc790f725a9339c956size 159699917123version https://git-lfs.github.com/spec/v1oid sha256:ee1b743f332d5e4457a3d89226637c9968130ca55569da361e51d7862883ef91size 313308177123version https://git-lfs.github.com/spec/v1oid sha256:0d6905629c24bfd31f0d20449200722f261912b945a72fb02d569f58f51d6495size 83301237123version https://git-lfs.github.com/spec/v1oid sha256:901d8067c23ff56a922d5af9fbe9d4b8135a6a90b59e52b975038f6f5c8e934bsize 158953806123version https://git-lfs.github.com/spec/v1oid sha256:85e3135e9a703d6b6f55487d36ac1ad090439ecc8cca776fdb83063f280bb5casize 159214550123version https://git-lfs.github.com/spec/v1oid sha256:4173af431aaa76b3454fbed6a5a3c884ead28e8a069ce32fc45166221b116b1asize 312330114123version https://git-lfs.github.com/spec/v1oid sha256:1089128be805bfe9cac97f092d19acfd294b37a6f7f443e0f951e01d5ef11eb7size 83049286123version https://git-lfs.github.com/spec/v1oid sha256:744f9eea019fecfa2986266229419335c04e47872335e4239e3507257e248382size 307276776123version https://git-lfs.github.com/spec/v1oid sha256:73789b01d6d8aa187e5e56ad130ef6a78ab07a9db860afd2280757b87e5baa6dsize 307276776123version https://git-lfs.github.com/spec/v1oid sha256:bcb908b8610f051457d6a9579d38b43690412144902f32bb24d342415fc939f6size 307276776123version https://git-lfs.github.com/spec/v1oid sha256:d189e2b113331d45adf685f08b34bc3ae7f1c2208fcd5294b11f44d365665071size 307276776123version https://git-lfs.github.com/spec/v1oid sha256:26879148e29f605810f2926eb089c0b8661340113f2c01d4ad5a093fae59ec29size 306290320123version https://git-lfs.github.com/spec/v1oid sha256:cc853118bfc9fe5b33d16e10d7659fdf4bb187d60d0bc57be0b6529b717bf8d8size 307276776123version https://git-lfs.github.com/spec/v1oid sha256:a512120d17cc2f002f1318728639ea391ee726afab0210d7199769a004940ca5size 307276776123version https://git-lfs.github.com/spec/v1oid sha256:d6f32a6e2ec733862f495bc73b0ad1ccc0c429f72326e5c98b1d19cfb2bbf967size 307276776123version https://git-lfs.github.com/spec/v1oid sha256:b3e13b8be793933bb3290a7ea5b583e0673425530174a35cff5a59881329f8dcsize 307276776123version https://git-lfs.github.com/spec/v1oid sha256:4232bd3f93c51bfe1de76fc290a422bb5497b9d766adb10c119caaa88ac9dd5dsize 306290320.gitattributesAdded+37
README.mdAdded+111
config.jsonAdded+48
generate.pyAdded+181
images/architecture.pngAdded

Large File Pointer Details
- SHA256: 9d5728096b5c04a13f69b599a3fdf57ff8b6af39e30332e11ac185ec82a222de
- Pointer size: 131 Bytes
- Size of remote file: 110 kB
images/distillation.pngAdded

Large File Pointer Details
- SHA256: 4f332023fc3d48008d3b436abe750cdb025a81fb5ca3cc889b9b68f4cfb7c33f
- Pointer size: 130 Bytes
- Size of remote file: 77.9 kB
images/heldout-loss.pngAdded

Large File Pointer Details
- SHA256: 869c82f8412c0da113b154fa8132687de3097fcb44912899819c991d64638860
- Pointer size: 130 Bytes
- Size of remote file: 47.8 kB
images/training-loss.pngAdded

Large File Pointer Details
- SHA256: 4d2999c2e3832262ea1d06dfe535f17fd336bf24dc8cb0691e9971af861ad5e0
- Pointer size: 130 Bytes
- Size of remote file: 52.5 kB
model.pyAdded+310
onnx/72k/student-10-step/bf16.onnxAdded+3
onnx/72k/student-10-step/bf16w.onnxAdded+3
onnx/72k/student-10-step/fp32.onnxAdded+3
onnx/72k/student-10-step/int8_dynamic.onnxAdded+3
onnx/72k/student-5-step/bf16.onnxAdded+3
onnx/72k/student-5-step/bf16w.onnxAdded+3
onnx/72k/student-5-step/fp32.onnxAdded+3
onnx/72k/student-5-step/int8_dynamic.onnxAdded+3
onnx/72k/teacher/bf16.onnxAdded+3
onnx/72k/teacher/bf16w.onnxAdded+3
onnx/72k/teacher/fp32.onnxAdded+3
onnx/72k/teacher/int8_dynamic.onnxAdded+3
pytorch/100k/guidance-40-step.safetensorsAdded+3
pytorch/100k/student-10-step.safetensorsAdded+3
pytorch/100k/student-20-step.safetensorsAdded+3
pytorch/100k/student-5-step.safetensorsAdded+3
pytorch/100k/teacher.safetensorsAdded+3
pytorch/72k/guidance-40-step.safetensorsAdded+3
pytorch/72k/student-10-step.safetensorsAdded+3
pytorch/72k/student-20-step.safetensorsAdded+3
pytorch/72k/student-5-step.safetensorsAdded+3
pytorch/72k/teacher.safetensorsAdded+3