Text-to-Image
Transformers
Safetensors
English
supra
malcolmrey commited on
Commit
bef115e
·
1 Parent(s): 8bb2933

supra2 safetensors

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
README.md CHANGED
@@ -1,3 +1,63 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ base_model: SupraLabs/Supra2-IMG
4
+ pipeline_tag: text-to-image
5
+ library_name: transformers
6
+ datasets:
7
+ - LucasFang/FLUX-Reason-6M
8
+ language:
9
+ - en
10
+ tags:
11
+ - safetensors
12
+ - text-to-image
13
+ - supra
14
  ---
15
+
16
+ # Supra2-IMG safetensors
17
+
18
+ Safetensors build of [SupraLabs/Supra2-IMG](https://huggingface.co/SupraLabs/Supra2-IMG). The announcement is [Massive Release: Supra2-IMG, a tiny 100M text-to-image model](https://www.reddit.com/r/StableDiffusion/comments/1wmg1pb/massive_release_supra2img_a_tiny_100m_texttoimage/) on r/StableDiffusion.
19
+
20
+ The model is SupraLabs' work: a 104.1M-parameter text-to-image DiT, 256×256, trained from scratch for 10 epochs on [LucasFang/FLUX-Reason-6M](https://huggingface.co/datasets/LucasFang/FLUX-Reason-6M). The text encoder is frozen [Flan-T5-Base](https://huggingface.co/google/flan-t5-base). The VAE is [SD-VAE-FT-MSE](https://huggingface.co/stabilityai/sd-vae-ft-mse). License is Apache-2.0. Architecture and training details are on the original model card.
21
+
22
+ ## This repo
23
+
24
+ The original checkpoint is `model_final_ema.pt`. This repo hosts that checkpoint converted to FP32 safetensors.
25
+
26
+ `Supra2-IMG_fp32.safetensors` is a safetensors file, not a renamed PyTorch checkpoint. It holds 237 FP32 weight tensors plus the stored unconditional text embedding and mask used for classifier-free guidance. Metadata keeps `patch=2` and `ctx_len=128`.
27
+
28
+ Flan-T5-Base and SD-VAE-FT-MSE are included under their own names. They are the original models, not part of Supra2. `inference.py` loads the DiT, the text encoder, the tokenizer, and the VAE from this repo.
29
+
30
+ Files the script does not read were left out: the SentencePiece model, `tokenizer_config.json`, `special_tokens_map.json`, and the original repo `config.json`. The tokenizer vocab is in `flan-t5-base.tokenizer.json`.
31
+
32
+ `generate.bat` and `generate.sh` take a prompt and an output filename.
33
+
34
+ ## Files
35
+
36
+ | File | Role |
37
+ | --- | --- |
38
+ | `inference.py` | Sampling script |
39
+ | `generate.bat`, `generate.sh` | Launchers |
40
+ | `Supra2-IMG_fp32.safetensors` | DiT weights, FP32 |
41
+ | `flan-t5-base.safetensors` | Text encoder weights |
42
+ | `flan-t5-base.config.json` | Text encoder config |
43
+ | `flan-t5-base.tokenizer.json` | Tokenizer |
44
+ | `sd-vae-ft-mse.safetensors` | VAE weights |
45
+ | `sd-vae-ft-mse.config.json` | VAE config |
46
+
47
+ ## Generate
48
+
49
+ ```bat
50
+ generate.bat "a boat" boat.png
51
+ ```
52
+
53
+ ```bash
54
+ ./generate.sh "a boat" boat.png
55
+ ```
56
+
57
+ A bare filename is written next to the script. A full path is used as given.
58
+
59
+ ```bash
60
+ python inference.py --prompt "a boat" --seed 0 --cfg 3.0 --steps 50 --out boat.png
61
+ ```
62
+
63
+ Recommended settings from the original model card: seed `0`, CFG `3.0`, steps `50`.
Supra2-IMG_fp32.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:89851684d1b01e7020732d3c860e7bc4f7000edb94447c22260daa6a5b06c1ca
3
+ size 416599856
flan-t5-base.config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "T5ForConditionalGeneration"
4
+ ],
5
+ "d_ff": 2048,
6
+ "d_kv": 64,
7
+ "d_model": 768,
8
+ "decoder_start_token_id": 0,
9
+ "dropout_rate": 0.1,
10
+ "eos_token_id": 1,
11
+ "feed_forward_proj": "gated-gelu",
12
+ "initializer_factor": 1.0,
13
+ "is_encoder_decoder": true,
14
+ "layer_norm_epsilon": 1e-06,
15
+ "model_type": "t5",
16
+ "n_positions": 512,
17
+ "num_decoder_layers": 12,
18
+ "num_heads": 12,
19
+ "num_layers": 12,
20
+ "output_past": true,
21
+ "pad_token_id": 0,
22
+ "relative_attention_max_distance": 128,
23
+ "relative_attention_num_buckets": 32,
24
+ "task_specific_params": {
25
+ "summarization": {
26
+ "early_stopping": true,
27
+ "length_penalty": 2.0,
28
+ "max_length": 200,
29
+ "min_length": 30,
30
+ "no_repeat_ngram_size": 3,
31
+ "num_beams": 4,
32
+ "prefix": "summarize: "
33
+ },
34
+ "translation_en_to_de": {
35
+ "early_stopping": true,
36
+ "max_length": 300,
37
+ "num_beams": 4,
38
+ "prefix": "translate English to German: "
39
+ },
40
+ "translation_en_to_fr": {
41
+ "early_stopping": true,
42
+ "max_length": 300,
43
+ "num_beams": 4,
44
+ "prefix": "translate English to French: "
45
+ },
46
+ "translation_en_to_ro": {
47
+ "early_stopping": true,
48
+ "max_length": 300,
49
+ "num_beams": 4,
50
+ "prefix": "translate English to Romanian: "
51
+ }
52
+ },
53
+ "tie_word_embeddings": false,
54
+ "transformers_version": "4.23.1",
55
+ "use_cache": true,
56
+ "vocab_size": 32128
57
+ }
flan-t5-base.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1dfb70afdcedceb9f9fae2f9b68e004ad934361fb35b9b2bd50b45ea90790fc8
3
+ size 990345061
flan-t5-base.tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
generate.bat ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ setlocal
3
+ cd /d "%~dp0"
4
+
5
+ if "%~1"=="" goto :usage
6
+ if "%~2"=="" goto :usage
7
+
8
+ set "OUT=%~2"
9
+ if not "%OUT:~1,1%"==":" if not "%OUT:~0,1%"=="\" set "OUT=%~dp0%OUT%"
10
+
11
+ "C:\Development\trainers\maltrainer\venv\Scripts\python.exe" "%~dp0inference.py" --ckpt "%~dp0Supra2-IMG_fp32.safetensors" --prompt "%~1" --out "%OUT%"
12
+ exit /b %ERRORLEVEL%
13
+
14
+ :usage
15
+ echo Usage: generate.bat "your prompt" output.png
16
+ exit /b 1
generate.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ ROOT="$(cd "$(dirname "$0")" && pwd)"
5
+
6
+ if [[ $# -lt 2 ]]; then
7
+ echo 'Usage: ./generate.sh "your prompt" output.png'
8
+ exit 1
9
+ fi
10
+
11
+ if [[ -x "/c/Development/trainers/maltrainer/venv/Scripts/python.exe" ]]; then
12
+ PY="/c/Development/trainers/maltrainer/venv/Scripts/python.exe"
13
+ elif [[ -x "C:/Development/trainers/maltrainer/venv/Scripts/python.exe" ]]; then
14
+ PY="C:/Development/trainers/maltrainer/venv/Scripts/python.exe"
15
+ else
16
+ PY="${PYTHON:-python3}"
17
+ fi
18
+
19
+ OUT="$2"
20
+ case "$OUT" in
21
+ /* | [A-Za-z]:* | [A-Za-z]:\\*) ;;
22
+ *) OUT="$ROOT/$OUT" ;;
23
+ esac
24
+
25
+ "$PY" "$ROOT/inference.py" \
26
+ --ckpt "$ROOT/Supra2-IMG_fp32.safetensors" \
27
+ --prompt "$1" \
28
+ --out "$OUT"
inference.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Supra2-IMG inference — standalone text-to-image (DiT + Flan-T5-Base + SD VAE).
4
+
5
+ Works on Linux and Windows. No imports from other project files.
6
+
7
+ Usage:
8
+ python inference.py --prompt "a sea jellyfish floating in the pitch-black ocean depths" \\
9
+ --seed 0 --cfg 3.0 --steps 50 --n 1 --out jellyfish.png
10
+
11
+ generate.bat "a red rose in daylight" rose.png
12
+ ./generate.sh "a red rose in daylight" rose.png
13
+
14
+ Default checkpoint is Supra2-IMG_fp32.safetensors next to this script.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import math
21
+ import os
22
+ import sys
23
+ import time
24
+ from tqdm import tqdm
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Architecture constants (must match the trained checkpoint)
32
+ # ---------------------------------------------------------------------------
33
+ IMG_SIZE = 256
34
+ LATENT_SIZE = 32 # 256 / 8 (f8 VAE)
35
+ LATENT_CH = 4
36
+ PATCH = 2
37
+ NUM_TOKENS = (LATENT_SIZE // PATCH) ** 2
38
+
39
+ D_MODEL = 576
40
+ DEPTH = 14
41
+ N_HEADS = 9
42
+ MLP_RATIO = 4.0
43
+ D_CTX = 768 # Flan-T5-Base
44
+ MAX_CTX_LEN = 128
45
+ LOCAL_DIR = os.path.dirname(os.path.abspath(__file__))
46
+ FLAN_WEIGHTS = os.path.join(LOCAL_DIR, "flan-t5-base.safetensors")
47
+ FLAN_CONFIG = os.path.join(LOCAL_DIR, "flan-t5-base.config.json")
48
+ FLAN_TOKENIZER = os.path.join(LOCAL_DIR, "flan-t5-base.tokenizer.json")
49
+ VAE_WEIGHTS = os.path.join(LOCAL_DIR, "sd-vae-ft-mse.safetensors")
50
+ VAE_CONFIG = os.path.join(LOCAL_DIR, "sd-vae-ft-mse.config.json")
51
+ VAE_SCALE = 0.18215
52
+
53
+ HF_REPO = "SupraLabs/Supra2-IMG"
54
+ DEFAULT_CKPT_SAFETENSORS = os.path.join(LOCAL_DIR, "Supra2-IMG_fp32.safetensors")
55
+ DEFAULT_CKPT_PT = os.path.join(LOCAL_DIR, "model_final_ema.pt")
56
+ DEFAULT_CKPT = DEFAULT_CKPT_SAFETENSORS if os.path.isfile(DEFAULT_CKPT_SAFETENSORS) else DEFAULT_CKPT_PT
57
+
58
+
59
+ def log(msg: str) -> None:
60
+ """Print immediately so the user sees live progress."""
61
+ print(msg, flush=True)
62
+
63
+
64
+ def pick_device() -> torch.device:
65
+ if torch.cuda.is_available():
66
+ torch.cuda.set_device(0)
67
+ name = torch.cuda.get_device_name(0)
68
+ mem = torch.cuda.get_device_properties(0).total_memory / 1e9
69
+ log(f"[device] CUDA: {name} ({mem:.1f} GB)")
70
+ return torch.device("cuda:0")
71
+ if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
72
+ log("[device] Apple MPS")
73
+ return torch.device("mps")
74
+ log("[device] CPU (this will be slow)")
75
+ return torch.device("cpu")
76
+
77
+
78
+ # ===========================================================================
79
+ # MODEL
80
+ # ===========================================================================
81
+ def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
82
+ """AdaLN: x * (1 + scale) + shift."""
83
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
84
+
85
+
86
+ class TimestepEmbedder(nn.Module):
87
+ """Sinusoidal timestep embedding followed by an MLP."""
88
+
89
+ def __init__(self, hidden_size: int, freq_dim: int = 256) -> None:
90
+ super().__init__()
91
+ self.freq_dim = freq_dim
92
+ self.mlp = nn.Sequential(
93
+ nn.Linear(freq_dim, hidden_size),
94
+ nn.SiLU(),
95
+ nn.Linear(hidden_size, hidden_size),
96
+ )
97
+
98
+ def _sinusoidal(self, t: torch.Tensor) -> torch.Tensor:
99
+ half = self.freq_dim // 2
100
+ freqs = torch.exp(
101
+ -math.log(10000.0) * torch.arange(half, device=t.device) / half
102
+ )
103
+ args = t[:, None].float() * freqs[None] * 1000.0
104
+ emb = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
105
+ if self.freq_dim % 2:
106
+ emb = F.pad(emb, (0, 1))
107
+ return emb
108
+
109
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
110
+ return self.mlp(self._sinusoidal(t))
111
+
112
+
113
+ class Attention(nn.Module):
114
+ """Multi-head self- or cross-attention."""
115
+
116
+ def __init__(self, dim: int, n_heads: int, ctx_dim: int | None = None) -> None:
117
+ super().__init__()
118
+ self.n_heads = n_heads
119
+ self.head_dim = dim // n_heads
120
+ self.is_self = ctx_dim is None
121
+ if self.is_self:
122
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
123
+ else:
124
+ self.q = nn.Linear(dim, dim, bias=True)
125
+ self.kv = nn.Linear(ctx_dim, dim * 2, bias=True)
126
+ self.proj = nn.Linear(dim, dim, bias=True)
127
+
128
+ def forward(
129
+ self,
130
+ x: torch.Tensor,
131
+ ctx: torch.Tensor | None = None,
132
+ ctx_mask: torch.Tensor | None = None,
133
+ ) -> torch.Tensor:
134
+ B, N, C = x.shape
135
+ if self.is_self:
136
+ qkv = self.qkv(x).view(B, N, 3, self.n_heads, self.head_dim)
137
+ q, k, v = (qkv[:, :, i].transpose(1, 2) for i in range(3))
138
+ else:
139
+ M = ctx.shape[1]
140
+ q = self.q(x).view(B, N, self.n_heads, self.head_dim).transpose(1, 2)
141
+ kv = self.kv(ctx).view(B, M, 2, self.n_heads, self.head_dim)
142
+ k, v = kv[:, :, 0].transpose(1, 2), kv[:, :, 1].transpose(1, 2)
143
+
144
+ attn_mask = None
145
+ if ctx_mask is not None:
146
+ attn_mask = ctx_mask.bool()[:, None, None, :]
147
+
148
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
149
+ out = out.transpose(1, 2).reshape(B, N, C)
150
+ return self.proj(out)
151
+
152
+
153
+ class DiTBlock(nn.Module):
154
+ """DiT block: AdaLN-Zero self-attn + cross-attn + MLP."""
155
+
156
+ def __init__(self, dim: int, n_heads: int, ctx_dim: int, mlp_ratio: float) -> None:
157
+ super().__init__()
158
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
159
+ self.self_attn = Attention(dim, n_heads)
160
+ self.norm_ca = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
161
+ self.cross_attn = Attention(dim, n_heads, ctx_dim=dim)
162
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
163
+ hidden = int(dim * mlp_ratio)
164
+ self.mlp = nn.Sequential(
165
+ nn.Linear(dim, hidden),
166
+ nn.GELU(approximate="tanh"),
167
+ nn.Linear(hidden, dim),
168
+ )
169
+ self.adaln = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim, bias=True))
170
+
171
+ def forward(
172
+ self,
173
+ x: torch.Tensor,
174
+ c: torch.Tensor,
175
+ ctx: torch.Tensor,
176
+ ctx_mask: torch.Tensor | None,
177
+ ) -> torch.Tensor:
178
+ shift_sa, scale_sa, gate_sa, shift_mlp, scale_mlp, gate_mlp = self.adaln(c).chunk(6, dim=1)
179
+ x = x + gate_sa.unsqueeze(1) * self.self_attn(
180
+ modulate(self.norm1(x), shift_sa, scale_sa)
181
+ )
182
+ x = x + self.cross_attn(self.norm_ca(x), ctx=ctx, ctx_mask=ctx_mask)
183
+ x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
184
+ return x
185
+
186
+
187
+ class FinalLayer(nn.Module):
188
+ def __init__(self, dim: int, out_ch: int) -> None:
189
+ super().__init__()
190
+ self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
191
+ self.linear = nn.Linear(dim, out_ch, bias=True)
192
+ self.adaln = nn.Sequential(nn.SiLU(), nn.Linear(dim, 2 * dim, bias=True))
193
+
194
+ def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
195
+ shift, scale = self.adaln(c).chunk(2, dim=1)
196
+ return self.linear(modulate(self.norm(x), shift, scale))
197
+
198
+
199
+ class SupraDiT(nn.Module):
200
+ """~100M parameter DiT for rectified-flow text-to-image."""
201
+
202
+ def __init__(
203
+ self,
204
+ latent_ch: int = LATENT_CH,
205
+ d_model: int = D_MODEL,
206
+ depth: int = DEPTH,
207
+ n_heads: int = N_HEADS,
208
+ ctx_dim: int = D_CTX,
209
+ mlp_ratio: float = MLP_RATIO,
210
+ num_tokens: int = NUM_TOKENS,
211
+ ) -> None:
212
+ super().__init__()
213
+ self.num_tokens = num_tokens
214
+ self.patch = PATCH
215
+ self.x_embed = nn.Linear(latent_ch * PATCH * PATCH, d_model)
216
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_tokens, d_model))
217
+ self.t_embed = TimestepEmbedder(d_model)
218
+ self.ctx_proj = nn.Linear(ctx_dim, d_model)
219
+ self.blocks = nn.ModuleList(
220
+ [DiTBlock(d_model, n_heads, d_model, mlp_ratio) for _ in range(depth)]
221
+ )
222
+ self.final = FinalLayer(d_model, latent_ch * PATCH * PATCH)
223
+
224
+ def forward(
225
+ self,
226
+ z: torch.Tensor,
227
+ t: torch.Tensor,
228
+ ctx: torch.Tensor,
229
+ ctx_mask: torch.Tensor | None = None,
230
+ ) -> torch.Tensor:
231
+ B, C, H, W = z.shape
232
+ P = self.patch
233
+ h, w = H // P, W // P
234
+ x = z.view(B, C, h, P, w, P).permute(0, 2, 4, 1, 3, 5).reshape(B, h * w, C * P * P)
235
+ x = self.x_embed(x) + self.pos_embed
236
+ c = self.t_embed(t)
237
+ ctx = self.ctx_proj(ctx)
238
+ for blk in self.blocks:
239
+ x = blk(x, c, ctx, ctx_mask)
240
+ x = self.final(x, c)
241
+ return x.view(B, h, w, C, P, P).permute(0, 3, 1, 4, 2, 5).reshape(B, C, H, W)
242
+
243
+
244
+ # ===========================================================================
245
+ # Checkpoint download
246
+ # ===========================================================================
247
+ def ensure_checkpoint(path: str) -> str:
248
+ """Use local checkpoint or download model_final_ema.pt from Hugging Face."""
249
+ if os.path.isfile(path):
250
+ log(f"[ckpt] found {path}")
251
+ return path
252
+
253
+ log(f"[ckpt] {path} not found — downloading from {HF_REPO} ...")
254
+ try:
255
+ from huggingface_hub import hf_hub_download
256
+ except ImportError:
257
+ log("[ckpt] installing huggingface_hub ...")
258
+ import subprocess
259
+
260
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "huggingface_hub"])
261
+ from huggingface_hub import hf_hub_download
262
+
263
+ filename = os.path.basename(path) or "model_final_ema.pt"
264
+ downloaded = hf_hub_download(
265
+ repo_id=HF_REPO,
266
+ filename=filename,
267
+ local_dir=".",
268
+ local_dir_use_symlinks=False,
269
+ )
270
+ # Prefer the expected local path if the hub placed it elsewhere
271
+ if os.path.isfile(filename) and os.path.abspath(filename) != os.path.abspath(path):
272
+ import shutil
273
+
274
+ shutil.copy2(filename, path)
275
+ log(f"[ckpt] copied to {path}")
276
+ return path
277
+ log(f"[ckpt] downloaded: {downloaded}")
278
+ return downloaded if os.path.isfile(downloaded) else path
279
+
280
+
281
+ # ===========================================================================
282
+ # Sampling (Euler integration of the flow ODE + optional CFG)
283
+ # ===========================================================================
284
+ @torch.no_grad()
285
+ def generate(args: argparse.Namespace, device: torch.device) -> None:
286
+ import json
287
+
288
+ from transformers import T5Config, T5EncoderModel, T5TokenizerFast
289
+ from diffusers import AutoencoderKL
290
+ import torchvision.utils as vutils
291
+ from safetensors import safe_open
292
+ from safetensors.torch import load_file
293
+
294
+ ckpt_path = ensure_checkpoint(args.ckpt or DEFAULT_CKPT)
295
+
296
+ log("[model] building SupraDiT ...")
297
+ model = SupraDiT().to(device).eval()
298
+ n_params = sum(p.numel() for p in model.parameters())
299
+ log(f"[model] {n_params / 1e6:.1f}M parameters")
300
+
301
+ log(f"[model] loading weights from {ckpt_path} ...")
302
+ t0 = time.perf_counter()
303
+
304
+ cfg = {}
305
+ if ckpt_path.endswith(".safetensors"):
306
+ weights = load_file(ckpt_path, device=str(device))
307
+ with safe_open(ckpt_path, framework="pt", device="cpu") as f:
308
+ meta = f.metadata() or {}
309
+ cfg = {k: int(v) if v.isdigit() else v for k, v in meta.items()}
310
+ if "__uncond_text__" in weights:
311
+ cfg["uncond_text"] = weights.pop("__uncond_text__")
312
+ if "__uncond_mask__" in weights:
313
+ cfg["uncond_mask"] = weights.pop("__uncond_mask__")
314
+ else:
315
+ state = torch.load(ckpt_path, map_location=device, weights_only=False)
316
+ cfg = state.get("config", {}) if isinstance(state, dict) else {}
317
+ if isinstance(state, dict):
318
+ if cfg.get("patch", PATCH) != PATCH:
319
+ raise SystemExit(f"Checkpoint PATCH={cfg['patch']} != script PATCH={PATCH}")
320
+ weights = state["ema"] if "ema" in state else state.get("model", state)
321
+ else:
322
+ weights = state
323
+
324
+ model.load_state_dict(weights, strict=True)
325
+ log(f"[model] weights loaded in {time.perf_counter() - t0:.1f}s")
326
+
327
+ ctx_len = int(cfg.get("ctx_len", MAX_CTX_LEN))
328
+ log(f"[text] ctx_len={ctx_len}")
329
+
330
+ log(f"[text] loading {os.path.basename(FLAN_WEIGHTS)} ...")
331
+ tokenizer = T5TokenizerFast(tokenizer_file=FLAN_TOKENIZER, extra_ids=100)
332
+ text_model = T5EncoderModel(T5Config.from_json_file(FLAN_CONFIG))
333
+ text_weights = load_file(FLAN_WEIGHTS)
334
+ text_incompat = text_model.load_state_dict(text_weights, strict=False)
335
+ bad_missing = [k for k in text_incompat.missing_keys if "embed_tokens" not in k]
336
+ bad_unexpected = [
337
+ k for k in text_incompat.unexpected_keys if not k.startswith("decoder.") and k != "lm_head.weight"
338
+ ]
339
+ if bad_missing or bad_unexpected:
340
+ raise SystemExit(f"Flan-T5 load mismatch missing={bad_missing} unexpected={bad_unexpected}")
341
+ del text_weights
342
+ text_model = text_model.to(device).eval()
343
+ for p in text_model.parameters():
344
+ p.requires_grad = False
345
+
346
+ log(f"[vae] loading {os.path.basename(VAE_WEIGHTS)} ...")
347
+ with open(VAE_CONFIG, encoding="utf-8") as f:
348
+ vae = AutoencoderKL.from_config(json.load(f))
349
+ vae_weights = load_file(VAE_WEIGHTS)
350
+ vae._fix_state_dict_keys_on_load(vae_weights)
351
+ vae.load_state_dict(vae_weights, strict=True)
352
+ del vae_weights
353
+ vae = vae.to(device).eval()
354
+
355
+ torch.manual_seed(args.seed)
356
+ if device.type == "cuda":
357
+ torch.cuda.manual_seed_all(args.seed)
358
+
359
+ prompts = [args.prompt] * args.n
360
+ n_tok = len(tokenizer(args.prompt)["input_ids"])
361
+ log(f"[text] prompt tokens={n_tok} n={args.n} seed={args.seed} cfg={args.cfg} steps={args.steps}")
362
+ if n_tok > ctx_len:
363
+ log(f"[text] WARNING: prompt has {n_tok} tokens, truncated to ctx_len={ctx_len}")
364
+
365
+ tok = tokenizer(
366
+ prompts,
367
+ padding="max_length",
368
+ truncation=True,
369
+ max_length=ctx_len,
370
+ return_tensors="pt",
371
+ ).to(device)
372
+
373
+ use_amp = device.type == "cuda"
374
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
375
+ ctx = text_model(**tok).last_hidden_state.float()
376
+ cmask = tok["attention_mask"].float()
377
+
378
+ use_cfg = args.cfg > 1.0
379
+ if use_cfg:
380
+ if isinstance(cfg, dict) and "uncond_text" in cfg:
381
+ uncond_ctx = cfg["uncond_text"].to(device).float().unsqueeze(0).expand(args.n, -1, -1)
382
+ uncond_mask = cfg["uncond_mask"].to(device).float().unsqueeze(0).expand(args.n, -1)
383
+ log("[cfg] using stored unconditional embeddings")
384
+ else:
385
+ u_tok = tokenizer(
386
+ [""] * args.n,
387
+ padding="max_length",
388
+ truncation=True,
389
+ max_length=ctx_len,
390
+ return_tensors="pt",
391
+ ).to(device)
392
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
393
+ uncond_ctx = text_model(**u_tok).last_hidden_state.float()
394
+ uncond_mask = u_tok["attention_mask"].float()
395
+ log("[cfg] encoded empty string as unconditional")
396
+ ctx_all = torch.cat([ctx, uncond_ctx], 0)
397
+ mask_all = torch.cat([cmask, uncond_mask], 0)
398
+
399
+ z = torch.randn(args.n, LATENT_CH, LATENT_SIZE, LATENT_SIZE, device=device)
400
+ dt = 1.0 / args.steps
401
+ log(f"[sample] Euler flow, {args.steps} steps ...")
402
+ t_sample = time.perf_counter()
403
+
404
+ for i in tqdm(range(args.steps), desc="Generating", unit="step", dynamic_ncols=True):
405
+ t = torch.full((args.n,), i * dt, device=device)
406
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
407
+ if use_cfg:
408
+ v_both = model(torch.cat([z, z], 0), torch.cat([t, t], 0), ctx_all, mask_all)
409
+ v_cond, v_uncond = v_both.float().chunk(2, 0)
410
+ v = v_uncond + args.cfg * (v_cond - v_uncond)
411
+ else:
412
+ v = model(z, t, ctx, cmask).float()
413
+ z = z + dt * v
414
+
415
+ log(f"[sample] denoising done in {time.perf_counter() - t_sample:.1f}s")
416
+ log("[vae] decoding latents ...")
417
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
418
+ imgs = vae.decode(z / VAE_SCALE).sample
419
+ imgs = (imgs.clamp(-1, 1) + 1) / 2
420
+
421
+ out_dir = os.path.dirname(os.path.abspath(args.out))
422
+ if out_dir:
423
+ os.makedirs(out_dir, exist_ok=True)
424
+ vutils.save_image(imgs, args.out, nrow=int(math.ceil(math.sqrt(args.n))))
425
+ log(f"[done] saved {args.n} image(s) -> {args.out}")
426
+
427
+
428
+ def parse_args() -> argparse.Namespace:
429
+ p = argparse.ArgumentParser(description="Supra2-IMG standalone inference")
430
+ p.add_argument(
431
+ "--ckpt",
432
+ default=None,
433
+ help="Path to checkpoint (.safetensors or .pt)",
434
+ )
435
+ p.add_argument(
436
+ "--prompt",
437
+ default="a sea jellyfish floating in the pitch-black ocean depths",
438
+ help="Text prompt",
439
+ )
440
+ p.add_argument("--seed", type=int, default=0, help="RNG seed")
441
+ p.add_argument("--cfg", type=float, default=3.0, help="Classifier-free guidance scale")
442
+ p.add_argument("--steps", type=int, default=50, help="Euler ODE steps")
443
+ p.add_argument("--n", type=int, default=1, help="Number of images")
444
+ p.add_argument("--out", default="jellyfish.png", help="Output image path")
445
+ return p.parse_args()
446
+
447
+
448
+ def main() -> None:
449
+ args = parse_args()
450
+ log("=== Supra2-IMG inference ===")
451
+ device = pick_device()
452
+ generate(args, device)
453
+
454
+
455
+ if __name__ == "__main__":
456
+ main()
jellyfish.png ADDED

Git LFS Details

  • SHA256: af563a14a34d4c496c0d19f577ef2a14cfdad9e016fa6f88de8fd5190c224f94
  • Pointer size: 130 Bytes
  • Size of remote file: 33.2 kB
samples/ant.png ADDED

Git LFS Details

  • SHA256: 21979a616f07facd70f54ca6de36ddad76377664515c708b254ef2fc6b12624d
  • Pointer size: 130 Bytes
  • Size of remote file: 84.2 kB
samples/bee.png ADDED

Git LFS Details

  • SHA256: b2daa21f5fc0d0f3db7cd67f2ec44375d7b6a64810f53492ea449e30b8f032e2
  • Pointer size: 130 Bytes
  • Size of remote file: 93.9 kB
samples/boat.png ADDED

Git LFS Details

  • SHA256: dd46cb4ab97af046abbf235d5d47fcf2e7927e03bfeb3fa1351e2bc4b660fd82
  • Pointer size: 130 Bytes
  • Size of remote file: 97.9 kB
samples/car.png ADDED

Git LFS Details

  • SHA256: 128ccf41732b6928841dc67d6dd83531a1bfdc5256eaa1c92770720bfdad990e
  • Pointer size: 131 Bytes
  • Size of remote file: 102 kB
samples/clover_logo.png ADDED

Git LFS Details

  • SHA256: b684b2a6ce61f1f2cead0e0b2a111833013a3c02d68719254e0d166a1aa01628
  • Pointer size: 130 Bytes
  • Size of remote file: 19.2 kB
samples/flower.png ADDED

Git LFS Details

  • SHA256: 8e1ec8c639314ac90d5b88f170afed8fef4006685e8d6bbb24deb007648d97d8
  • Pointer size: 130 Bytes
  • Size of remote file: 80 kB
samples/house.png ADDED

Git LFS Details

  • SHA256: 91a651a7e985f2f798ea5652f316b57f65cc73dcb33246545a42dc23b84d9ce0
  • Pointer size: 130 Bytes
  • Size of remote file: 75.5 kB
samples/jellyfish.png ADDED

Git LFS Details

  • SHA256: af563a14a34d4c496c0d19f577ef2a14cfdad9e016fa6f88de8fd5190c224f94
  • Pointer size: 130 Bytes
  • Size of remote file: 33.2 kB
samples/jellyfish_official.png ADDED

Git LFS Details

  • SHA256: b87db098ec91d67ebd15b3a448daeac0a418dafd53b362ba96106dcc12750d98
  • Pointer size: 130 Bytes
  • Size of remote file: 60 kB
samples/nba_logo.png ADDED

Git LFS Details

  • SHA256: 3ae551926feaeca6f17d6073b34a18ad7459e09d894e0700ad42368b649fdea9
  • Pointer size: 130 Bytes
  • Size of remote file: 48.7 kB
samples/number_5.png ADDED

Git LFS Details

  • SHA256: a5770546112f395962dc6ee041080187767719377de2fd33f1f82e3c5b100e92
  • Pointer size: 130 Bytes
  • Size of remote file: 36.3 kB
samples/orchid.png ADDED

Git LFS Details

  • SHA256: db92b0797ff915c8a8de89cb235274e1b854df27bf3e2b48850f2342ca62c02f
  • Pointer size: 130 Bytes
  • Size of remote file: 74.8 kB
samples/red_panda.png ADDED

Git LFS Details

  • SHA256: f2ec44aae658356d4d1e3bd29ff3515938a3ea62922255b0b1880bbcb26096a2
  • Pointer size: 130 Bytes
  • Size of remote file: 95.5 kB
samples/red_square_blue_triangle.png ADDED

Git LFS Details

  • SHA256: 814fe88207505bda86c8dbf89351f9b9564156818a8144fa40dfe88dc5d44a15
  • Pointer size: 130 Bytes
  • Size of remote file: 42.7 kB
samples/rose.png ADDED

Git LFS Details

  • SHA256: 56894c1f65de616214e81e43adbaa8aeab32ee817a63e25a1d8c60ffd1bc4fc8
  • Pointer size: 130 Bytes
  • Size of remote file: 89.9 kB
samples/sun.png ADDED

Git LFS Details

  • SHA256: f86cf58e319f888c74e82d78250deb345c7b0c3b00e8b28f831ee30640a55e33
  • Pointer size: 130 Bytes
  • Size of remote file: 60.5 kB
sd-vae-ft-mse.config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.27.0",
4
+ "act_fn": "silu",
5
+ "block_out_channels": [
6
+ 128,
7
+ 256,
8
+ 512,
9
+ 512
10
+ ],
11
+ "down_block_types": [
12
+ "DownEncoderBlock2D",
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D"
16
+ ],
17
+ "force_upcast": true,
18
+ "in_channels": 3,
19
+ "latent_channels": 4,
20
+ "layers_per_block": 2,
21
+ "norm_num_groups": 32,
22
+ "out_channels": 3,
23
+ "sample_size": 256,
24
+ "scaling_factor": 0.18215,
25
+ "up_block_types": [
26
+ "UpDecoderBlock2D",
27
+ "UpDecoderBlock2D",
28
+ "UpDecoderBlock2D",
29
+ "UpDecoderBlock2D"
30
+ ]
31
+ }
sd-vae-ft-mse.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d993488569e928462932c8c38a0760b874d166399b14414135bd9c42df5815
3
+ size 334643276