Spaces:
Running on Zero
Running on Zero
Commit ·
9ee5274
unverified ·
0
Parent(s):
docs: initial design spec for z-image-studio
Browse filesGradio app for Z-Image + Z-Image-Turbo via DiffSynth-Studio (no ComfyUI).
Three tabs (T2I dual-model / ControlNet Union / Upscale RealESRGAN+refine),
per-tab LoRA loader, MPS+CUDA dual-device, eager preload, Onyx Amber theme.
.gitignore
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
*.pyo
|
| 5 |
+
.venv/
|
| 6 |
+
venv/
|
| 7 |
+
.pytest_cache/
|
| 8 |
+
.ruff_cache/
|
| 9 |
+
.mypy_cache/
|
| 10 |
+
*.egg-info/
|
| 11 |
+
|
| 12 |
+
# Brainstorm + scratch
|
| 13 |
+
.superpowers/
|
| 14 |
+
|
| 15 |
+
# Model weights (never commit)
|
| 16 |
+
*.safetensors
|
| 17 |
+
*.gguf
|
| 18 |
+
*.bin
|
| 19 |
+
*.pt
|
| 20 |
+
*.pth
|
| 21 |
+
!assets/seed_inputs/*.png
|
| 22 |
+
!assets/seed_inputs/*.jpg
|
| 23 |
+
|
| 24 |
+
# Gradio runtime
|
| 25 |
+
gradio_cached_examples/
|
| 26 |
+
output/
|
| 27 |
+
flagged/
|
| 28 |
+
|
| 29 |
+
# OS / editor
|
| 30 |
+
.DS_Store
|
| 31 |
+
.idea/
|
| 32 |
+
.vscode/
|
| 33 |
+
*.swp
|
docs/superpowers/specs/2026-05-13-z-image-studio-design.md
ADDED
|
@@ -0,0 +1,346 @@
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# z-image-studio — Design Spec
|
| 2 |
+
|
| 3 |
+
| Field | Value |
|
| 4 |
+
| ------------ | -------------------------------------------------------------------------------------- |
|
| 5 |
+
| Date | 2026-05-13 |
|
| 6 |
+
| Status | Draft for review |
|
| 7 |
+
| Owner | Mayank Gupta |
|
| 8 |
+
| Brainstorm | `.superpowers/brainstorm/2440-1778660739/` (UI mockups Plate/Console/Atelier → Onyx variants → Amber chosen) |
|
| 9 |
+
|
| 10 |
+
A single-process Gradio 5.x app that runs the Z-Image and Z-Image-Turbo diffusion models with three task tabs (Text → Image, ControlNet, Upscale) plus a per-tab LoRA loader. The same code runs locally (auto-detected MPS on Apple Silicon, CUDA on NVIDIA) and on Hugging Face Spaces (ZeroGPU H200). Backend is `DiffSynth-Studio`'s `ZImagePipeline` — no ComfyUI bundling, no JSON workflows, no PromptServer stubs.
|
| 11 |
+
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
## 1. Goals · Non-goals
|
| 15 |
+
|
| 16 |
+
**Goals (v1)**
|
| 17 |
+
- Public HF Space exposing Z-Image base + Turbo with a model selector
|
| 18 |
+
- Three tabs: T2I (dual-model), ControlNet (Turbo + Union 2.1, all preprocessor modes), Upscale (RealESRGAN + Z-Image-Turbo refinement)
|
| 19 |
+
- LoRA upload + strength slider in each tab
|
| 20 |
+
- Eager preload of both transformers so model-switching in T2I is near-instant
|
| 21 |
+
- Local development on Apple Silicon MPS that matches HF behavior bit-for-bit
|
| 22 |
+
|
| 23 |
+
**Non-goals (v1)** — list locked, do not re-litigate during implementation
|
| 24 |
+
- Video / motion modes (this is image-only)
|
| 25 |
+
- Persistent storage add-on
|
| 26 |
+
- Output history persistence across sessions
|
| 27 |
+
- Multi-prompt queueing
|
| 28 |
+
- Custom LoRA add/remove rows (single LoRA per tab)
|
| 29 |
+
- LoRA on the Upscale refinement pass (locked to vanilla Turbo refinement)
|
| 30 |
+
- ControlNet on Z-Image base (no released ControlNet weights for base; Turbo-only)
|
| 31 |
+
- Gradio sidebar / drawer layout (LTX-style is overkill for 3 modes)
|
| 32 |
+
|
| 33 |
+
---
|
| 34 |
+
|
| 35 |
+
## 2. Architecture
|
| 36 |
+
|
| 37 |
+
```
|
| 38 |
+
┌──────────────────────────────────────────────────────────────┐
|
| 39 |
+
│ app.py — Gradio Blocks │
|
| 40 |
+
│ Header (gr.HTML) · Tabs · gr.Image / gr.JSON outputs │
|
| 41 |
+
└──────────────────┬───────────────────────────────────────────┘
|
| 42 |
+
│
|
| 43 |
+
▼
|
| 44 |
+
┌──────────────────────────────────────────────────────────────┐
|
| 45 |
+
│ backend.py — ZImageStudioBackend │
|
| 46 |
+
│ @spaces.GPU(duration=_duration_for) ← module-level │
|
| 47 |
+
│ ├─ pipeline: diffsynth.ZImagePipeline │
|
| 48 |
+
│ ├─ load_lora(safetensors, strength) — apply/revert ctx │
|
| 49 |
+
│ └─ generate(mode, params) → image, meta │
|
| 50 |
+
└──────────────────┬───────────────────────────────────────────┘
|
| 51 |
+
│
|
| 52 |
+
▼
|
| 53 |
+
┌──────────────────────────────────────────────────────────────┐
|
| 54 |
+
│ modes.py · preprocessors.py · upscale.py · lora.py · models.py │
|
| 55 |
+
└──────────────────────────────────────────────────────────────┘
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
Single pipeline instance shared across modes. The transformer swap (Base ↔ Turbo) is the only model-pool change — both already loaded on CPU. DiffSynth's `vram_management` swaps modules CPU↔GPU per call.
|
| 59 |
+
|
| 60 |
+
`@spaces.GPU` is the only divergence between local and Spaces — applied via a runtime check that yields an identity decorator off-Spaces.
|
| 61 |
+
|
| 62 |
+
---
|
| 63 |
+
|
| 64 |
+
## 3. Modes — DiffSynth call mappings
|
| 65 |
+
|
| 66 |
+
All three modes go through one `ZImagePipeline.__call__`. Mode-specific code is just argument shaping.
|
| 67 |
+
|
| 68 |
+
| Mode | Model | DiffSynth call shape | Source ComfyUI workflow |
|
| 69 |
+
| --- | --- | --- | --- |
|
| 70 |
+
| **T2I (Base)** | `Tongyi-MAI/Z-Image` | `pipe(prompt, negative_prompt, cfg_scale=4.0, num_inference_steps=25, sigma_shift=3.0, height, width, seed)` | `image_z_image.json` |
|
| 71 |
+
| **T2I (Turbo)** | `Tongyi-MAI/Z-Image-Turbo` | `pipe(prompt, cfg_scale=1.0, num_inference_steps=8, sigma_shift=3.0, height, width, seed)` | `image_z_image_turbo.json` |
|
| 72 |
+
| **ControlNet** | Turbo + `PAI/Z-Image-Turbo-Fun-Controlnet-Union-2.1` | `pipe(prompt, controlnet_inputs=[ControlNetInput(image=preprocessed, scale)], cfg_scale=1.0, num_inference_steps=9, sigma_shift=3.0)` | `image_z_image_turbo_fun_union_controlnet.json` |
|
| 73 |
+
| **Upscale** | Turbo + RealESRGAN_x4plus | `RealESRGAN_x4(input) → PIL.resize 0.5 → pipe(prompt="masterpiece, 8k", input_image=upscaled, denoising_strength=0.33, num_inference_steps=5, cfg_scale=1.0, sigma_shift=3.0)` | `utility_z_image_turbo_2k_upscaler.json` |
|
| 74 |
+
|
| 75 |
+
**LoRA wiring:** validated `safetensors` file + `gr.Slider(0.0, 1.5, value=0.8)` strength. Applied via DiffSynth's `merge_lora` inside an apply/revert context manager so the cached GPU model returns to a clean state after each request. Safetensors header sniffed before `@spaces.GPU` fires to reject mismatched LoRAs with a clear error (no GPU slot wasted).
|
| 76 |
+
|
| 77 |
+
**ControlNet preprocessors:** dropdown `["Canny", "Depth", "Pose", "Pre-processed (no-op)"]`. Backed by `controlnet_aux` with lazy imports (only the chosen preprocessor's deps load).
|
| 78 |
+
|
| 79 |
+
---
|
| 80 |
+
|
| 81 |
+
## 4. UI — Onyx Amber
|
| 82 |
+
|
| 83 |
+
Aesthetic locked from the brainstorm: warm dark, golden amber accent, Geist family. Reads as "studio at midnight" — not corporate, not gamer.
|
| 84 |
+
|
| 85 |
+
### 4.1 Color tokens
|
| 86 |
+
|
| 87 |
+
| Token | Value | Used for |
|
| 88 |
+
| ------------------ | ---------- | ----------------------------------------- |
|
| 89 |
+
| `body_bg` | `#0F0C08` | App body |
|
| 90 |
+
| `panel_bg` | `#0F0C08` | Panel background (same as body) |
|
| 91 |
+
| `input_bg` | `#0F0C08` | Text inputs, sliders |
|
| 92 |
+
| `canvas_bg` | `#110D08` | Image preview block background |
|
| 93 |
+
| `border` | `#2A2218` | All hairline borders |
|
| 94 |
+
| `text` | `#FAF1E3` | Primary text |
|
| 95 |
+
| `text_dim` | `#A89478` | Secondary text, labels |
|
| 96 |
+
| `accent` | `#FFB02E` | Active tab underline, primary button bg, radio-on bg, slider fill, LoRA tag |
|
| 97 |
+
| `accent_text` | `#1A1208` | Text on accent fills |
|
| 98 |
+
| `radius` | `8px` | Block radius, button radius |
|
| 99 |
+
| `radius_sm` | `6px` | Radio pill radius |
|
| 100 |
+
|
| 101 |
+
### 4.2 Typography
|
| 102 |
+
|
| 103 |
+
- Display + body: **Geist** (variable, free; loaded via `@import url(https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&display=swap)`)
|
| 104 |
+
- Mono: **Geist Mono** (labels, numeric readouts, status line, LoRA file metadata)
|
| 105 |
+
- Wired through `gr.themes.Base(font=[gr.themes.GoogleFont("Geist"), "sans-serif"], font_mono=[gr.themes.GoogleFont("Geist Mono"), "monospace"])`
|
| 106 |
+
|
| 107 |
+
### 4.3 Decoration
|
| 108 |
+
|
| 109 |
+
- Subtle warm vignette at top of body: `background-image: radial-gradient(ellipse 80% 60% at 50% 0%, rgba(255,176,46,0.06), transparent 70%)`
|
| 110 |
+
- Primary button glow: `box-shadow: 0 0 0 1px rgba(255,176,46,0.4), 0 8px 24px -8px rgba(255,176,46,0.35)`
|
| 111 |
+
- Image preview placeholder gradient (visible only before first generation): `radial-gradient(circle at 35% 25%, rgba(255,176,46,0.32), transparent 55%), linear-gradient(135deg, #2a1f0e, #573b0f, #FFB02E 115%)`
|
| 112 |
+
|
| 113 |
+
### 4.4 Component patterns (all Gradio-native shapes)
|
| 114 |
+
|
| 115 |
+
- **Tab strip** — top horizontal `gr.Tabs` with underline indicator in amber on the active tab.
|
| 116 |
+
- **Prompt** — `gr.Textbox(lines=4, label="Prompt")` — full width.
|
| 117 |
+
- **Model selector** — `gr.Radio(["Base", "Turbo"], value="Turbo", label="Model")` — T2I tab only.
|
| 118 |
+
- **LoRA loader** — `gr.File(label="LoRA", file_types=[".safetensors"])` + `gr.Slider(0.0, 1.5, value=0.8, label="LoRA strength", step=0.05)`. On phone they stack; on tablet+ they share a row.
|
| 119 |
+
- **Parameter sliders** — Steps, CFG (T2I-base only), Width, Height, Seed.
|
| 120 |
+
- **ControlNet-only** — additional `gr.Image(label="Control image")` + `gr.Dropdown(["Canny","Depth","Pose","Pre-processed"], value="Canny")` + `gr.Slider(0.0, 2.0, value=1.0, label="ControlNet scale")`.
|
| 121 |
+
- **Upscale-only** — additional `gr.Image(label="Input image")`; no model selector; the upscale prompt defaults to `"masterpiece, 8k"` and is editable.
|
| 122 |
+
- **Generate button** — `gr.Button("Generate", variant="primary")` — amber fill with glow.
|
| 123 |
+
- **Output** — `gr.Image(label="Output", show_download_button=True)` + `gr.JSON(label="Meta", value={...seed, steps, model, lora})`.
|
| 124 |
+
- **Status line** — `gr.Markdown` updated on generation start/end. Mono font, dim text.
|
| 125 |
+
|
| 126 |
+
### 4.5 Responsive behavior
|
| 127 |
+
|
| 128 |
+
Phone (< 600 px): single column. Controls then output. LoRA row stacks (file then strength). Tab labels truncate to `Text`, `ControlNet`, `Upscale`.
|
| 129 |
+
|
| 130 |
+
Tablet (600 – 1024 px): two-column grid below the tab strip. Controls on left, output on right. LoRA row goes side-by-side (file widget left, strength slider right).
|
| 131 |
+
|
| 132 |
+
Desktop (> 1024 px): same as tablet, but generous margins and a max-width on the controls column. No sidebar; tab strip remains horizontal.
|
| 133 |
+
|
| 134 |
+
Gradio's default `gr.Tabs` + `gr.Row`/`gr.Column` machinery already collapses on small viewports; we just need the CSS media query to swap from grid to stacked at < 600 px.
|
| 135 |
+
|
| 136 |
+
---
|
| 137 |
+
|
| 138 |
+
## 5. File layout
|
| 139 |
+
|
| 140 |
+
```
|
| 141 |
+
llm/z-image-studio/
|
| 142 |
+
├── app.py # Gradio Blocks: tabs, header, launch
|
| 143 |
+
├── backend.py # ZImageStudioBackend; @spaces.GPU decoration
|
| 144 |
+
├── modes.py # 3 mode handlers (T2I, ControlNet, Upscale) — pure functions
|
| 145 |
+
├── models.py # ModelConfig registry, preload helpers
|
| 146 |
+
├── preprocessors.py # Canny / Depth / Pose via controlnet_aux (lazy)
|
| 147 |
+
├── upscale.py # RealESRGAN x4 wrapper + 0.5-resize bridge
|
| 148 |
+
├── lora.py # LoRA safetensors header sniffer + apply/revert ctx
|
| 149 |
+
├── ui.py # Per-tab Gradio component builders
|
| 150 |
+
├── theme.py # Amber tokens + gr.themes.Base subclass + CSS string
|
| 151 |
+
├── pyproject.toml # ruff config; py311
|
| 152 |
+
├── requirements.txt # diffsynth-studio, gradio==5.x, spaces, controlnet-aux, realesrgan, ...
|
| 153 |
+
├── README.md # HF Space YAML frontmatter (preload_from_hub) + user docs
|
| 154 |
+
├── LICENSE # MIT
|
| 155 |
+
├── CLAUDE.md # Mirror sole-author rule + venv/no-conda + hf CLI
|
| 156 |
+
├── setup.sh # python3.11 -m venv .venv; pip install
|
| 157 |
+
├── tests/
|
| 158 |
+
│ ├── conftest.py
|
| 159 |
+
│ ├── test_modes.py
|
| 160 |
+
│ ├── test_models.py
|
| 161 |
+
│ ├── test_preprocessors.py
|
| 162 |
+
│ └── test_lora.py
|
| 163 |
+
├── assets/ # small seed images for smoke tests
|
| 164 |
+
└── docs/superpowers/
|
| 165 |
+
├── specs/2026-05-13-z-image-studio-design.md # this file
|
| 166 |
+
└── plans/ # plan from writing-plans (next)
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
Flat top-level layout (no `src/`, no nested packages). Each module owns one responsibility. Same convention as LTX2.3-AIO-Generator.
|
| 170 |
+
|
| 171 |
+
---
|
| 172 |
+
|
| 173 |
+
## 6. Models, preload, cache mirroring
|
| 174 |
+
|
| 175 |
+
### 6.1 HF Space YAML frontmatter (`README.md` top)
|
| 176 |
+
|
| 177 |
+
```yaml
|
| 178 |
+
---
|
| 179 |
+
title: Z-Image Studio
|
| 180 |
+
emoji: ⚡
|
| 181 |
+
colorFrom: yellow
|
| 182 |
+
colorTo: red
|
| 183 |
+
sdk: gradio
|
| 184 |
+
sdk_version: "5.50.0"
|
| 185 |
+
app_file: app.py
|
| 186 |
+
python_version: "3.11"
|
| 187 |
+
suggested_hardware: zero-a10g
|
| 188 |
+
hf_oauth: false
|
| 189 |
+
preload_from_hub:
|
| 190 |
+
- Tongyi-MAI/Z-Image transformer/diffusion_pytorch_model.safetensors,text_encoder/*.safetensors,vae/diffusion_pytorch_model.safetensors,tokenizer/*
|
| 191 |
+
- Tongyi-MAI/Z-Image-Turbo transformer/diffusion_pytorch_model.safetensors
|
| 192 |
+
- PAI/Z-Image-Turbo-Fun-Controlnet-Union-2.1 Z-Image-Turbo-Fun-Controlnet-Union-2.1-8steps.safetensors
|
| 193 |
+
- xinntao/Real-ESRGAN RealESRGAN_x4plus.pth
|
| 194 |
+
---
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
Total preload ≈ 30 – 35 GB. Both transformers share the same text encoder + VAE + tokenizer (downloaded once via the Z-Image entry). Well under the 150 GB ephemeral storage cap and well under the 10-entry preload list cap.
|
| 198 |
+
|
| 199 |
+
### 6.2 Runtime cache mirror
|
| 200 |
+
|
| 201 |
+
`app.py:_bootstrap()` runs once at module import on HF Spaces:
|
| 202 |
+
|
| 203 |
+
1. Walk `~/.cache/huggingface/hub` (preload tree, owned by the build user, read-only at runtime).
|
| 204 |
+
2. Build a parallel writable tree at `~/hf-cache-rw/`:
|
| 205 |
+
- `blobs/<sha>` files → hardlinked (zero copy, shared inode).
|
| 206 |
+
- `snapshots/<commit>/...` symlinks → preserved as-is.
|
| 207 |
+
- `refs/<branch>` → byte-copied (HF lib overwrites these on etag check).
|
| 208 |
+
- All dirs → `mkdir` (we own them).
|
| 209 |
+
3. Set `HF_HOME=~/hf-cache-rw` and `HF_HUB_CACHE=~/hf-cache-rw/hub`.
|
| 210 |
+
|
| 211 |
+
After mirror: preloaded reads are instant cache hits, and lazy downloads (LoRAs uploaded by users at runtime) write to dirs the runtime user owns. Same mechanism as LTX (`_mirror_preload_hf_cache` in their `app.py`). Falls back to symlink if `os.link()` returns EXDEV.
|
| 212 |
+
|
| 213 |
+
### 6.3 Pipeline construction at boot
|
| 214 |
+
|
| 215 |
+
```python
|
| 216 |
+
pipe = ZImagePipeline.from_pretrained(
|
| 217 |
+
torch_dtype=torch.bfloat16,
|
| 218 |
+
device=_auto_device(), # "cuda" | "mps" | "cpu"
|
| 219 |
+
model_configs=[
|
| 220 |
+
# Both transformers — model_pool keeps them on CPU and swaps on demand
|
| 221 |
+
ModelConfig(model_id="Tongyi-MAI/Z-Image", origin_file_pattern="transformer/*.safetensors", **vram_cfg),
|
| 222 |
+
ModelConfig(model_id="Tongyi-MAI/Z-Image-Turbo", origin_file_pattern="transformer/*.safetensors", **vram_cfg),
|
| 223 |
+
# Shared text encoder + VAE
|
| 224 |
+
ModelConfig(model_id="Tongyi-MAI/Z-Image", origin_file_pattern="text_encoder/*.safetensors", **vram_cfg),
|
| 225 |
+
ModelConfig(model_id="Tongyi-MAI/Z-Image", origin_file_pattern="vae/diffusion_pytorch_model.safetensors", **vram_cfg),
|
| 226 |
+
# ControlNet — eager preload at boot to avoid first-ControlNet-call wait.
|
| 227 |
+
# If startup RAM becomes tight on Spaces, move this to a lazy-load on first ControlNet request.
|
| 228 |
+
ModelConfig(model_id="PAI/Z-Image-Turbo-Fun-Controlnet-Union-2.1",
|
| 229 |
+
origin_file_pattern="Z-Image-Turbo-Fun-Controlnet-Union-2.1-8steps.safetensors", **vram_cfg),
|
| 230 |
+
],
|
| 231 |
+
tokenizer_config=ModelConfig(model_id="Tongyi-MAI/Z-Image", origin_file_pattern="tokenizer/"),
|
| 232 |
+
vram_limit=_vram_limit_for_device(),
|
| 233 |
+
)
|
| 234 |
+
```
|
| 235 |
+
|
| 236 |
+
Model selection (Base ↔ Turbo) inside the request handler just calls `pipe.dit = pipe.model_pool.fetch_model("z_image_dit", variant="base"|"turbo")` before `pipe(...)`. Per-call overhead: negligible — both are already on CPU.
|
| 237 |
+
|
| 238 |
+
---
|
| 239 |
+
|
| 240 |
+
## 7. ZeroGPU integration
|
| 241 |
+
|
| 242 |
+
### 7.1 Module-level decoration
|
| 243 |
+
|
| 244 |
+
```python
|
| 245 |
+
def _identity(fn): return fn
|
| 246 |
+
|
| 247 |
+
try:
|
| 248 |
+
import spaces # type: ignore
|
| 249 |
+
except ImportError:
|
| 250 |
+
spaces = None
|
| 251 |
+
|
| 252 |
+
_ON_SPACES = bool(os.environ.get("SPACES_ZERO_GPU"))
|
| 253 |
+
_GPU = spaces.GPU(duration=_duration_for) if (spaces and _ON_SPACES) else _identity
|
| 254 |
+
|
| 255 |
+
@_GPU
|
| 256 |
+
def _generate(pipeline, mode, params, progress=None) -> tuple[Image, dict]:
|
| 257 |
+
...
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
Module-level so ZeroGPU's startup analyzer detects it. Identity off-Spaces.
|
| 261 |
+
|
| 262 |
+
### 7.2 Duration estimator
|
| 263 |
+
|
| 264 |
+
```python
|
| 265 |
+
_BASE_DURATION_S = {"t2i_base": 30, "t2i_turbo": 12, "controlnet": 35, "upscale": 45}
|
| 266 |
+
_PER_STEP_S = {"t2i_base": 2.0, "t2i_turbo": 1.5, "controlnet": 2.0, "upscale": 1.5}
|
| 267 |
+
|
| 268 |
+
def _duration_for(pipeline, mode, params, progress=None, multiplier=1.0) -> int:
|
| 269 |
+
base = _BASE_DURATION_S[mode]
|
| 270 |
+
per_step = _PER_STEP_S[mode] * params.get("steps", 8)
|
| 271 |
+
image_size_factor = (params.get("width", 1024) * params.get("height", 1024)) / (1024 * 1024)
|
| 272 |
+
cold_buffer = 20 # CPU→GPU copy on first call
|
| 273 |
+
est = int((base + per_step + cold_buffer) * image_size_factor * multiplier)
|
| 274 |
+
return max(60, min(est, 180))
|
| 275 |
+
```
|
| 276 |
+
|
| 277 |
+
Clamped to `[60, 180]` — well within ZeroGPU per-call caps. Light Turbo T2I gets queue priority; heavy upscale reserves real headroom.
|
| 278 |
+
|
| 279 |
+
### 7.3 Auto-retry on timeout
|
| 280 |
+
|
| 281 |
+
If the first attempt raises `gradio.exceptions.Error('GPU task aborted')`, classified as `category='gpu_timeout'`, the handler re-submits once with `multiplier=2.0`. UI shows a banner. One retry only.
|
| 282 |
+
|
| 283 |
+
### 7.4 Context propagation
|
| 284 |
+
|
| 285 |
+
`contextvars.copy_context()` is passed into any worker thread that calls into the GPU path — same fix as LTX. Without it, ZeroGPU's request-identity lookup fails and the call hits the unlogged-user path.
|
| 286 |
+
|
| 287 |
+
---
|
| 288 |
+
|
| 289 |
+
## 8. Errors & edge cases
|
| 290 |
+
|
| 291 |
+
| Category | Detection | Recovery |
|
| 292 |
+
| --- | --- | --- |
|
| 293 |
+
| OOM (CUDA / MPS) | Exception class `OutOfMemoryError` / message match | Re-call with reduced `vram_limit` (90% of free memory). If still OOM, surface "Try smaller size / use Turbo" error in UI. |
|
| 294 |
+
| ZeroGPU timeout | `'gpu task aborted'` in error message | Auto-retry once with `multiplier=2.0`. Banner shown. |
|
| 295 |
+
| Bad LoRA file | Safetensors header sniff fails or unexpected key prefix | Reject before `@spaces.GPU` fires. Error message names the unexpected key. |
|
| 296 |
+
| Preprocessor failure | controlnet_aux raises (e.g. canny on solid-color image) | Warn; fall back to raw input image. |
|
| 297 |
+
| Missing input on ControlNet/Upscale | gr.Image.value is None | Generate button is `interactive=False` until image uploaded. Caught also server-side. |
|
| 298 |
+
| Quota exceeded | `'exceeded your gpu'` in error | Surface ZeroGPU quota message + link to user's profile. |
|
| 299 |
+
| Expired token | `'expired zerogpu proxy token'` | Tell user to refresh the page. |
|
| 300 |
+
|
| 301 |
+
---
|
| 302 |
+
|
| 303 |
+
## 9. Testing strategy
|
| 304 |
+
|
| 305 |
+
Four tiers, mirroring LTX:
|
| 306 |
+
|
| 307 |
+
- **L1 — no GPU, CI** (`pytest`): ruff format/check, mode parameter shaping (`modes.py`), LoRA safetensors header validation, preprocessor type contracts, model config registry.
|
| 308 |
+
- **L2 — no GPU, CI** (`pytest`): monkeypatch `ZImagePipeline.__call__` to capture args; assert each mode handler builds the right call. Mock `controlnet_aux` to capture preprocessor invocations.
|
| 309 |
+
- **L3 — GPU smoke, manual** (`pytest --gpu`): one image per mode at 384 × 384 (small to keep duration short). Verifies real pipeline produces non-blank output.
|
| 310 |
+
- **L4 — HF Space smoke, manual**: push to a private staging Space, run all 3 modes, verify model selector hot-swap doesn't OOM and LoRA upload + revert keeps cached model clean.
|
| 311 |
+
|
| 312 |
+
No mocks for `ZImagePipeline` internals — only for its `__call__` boundary. Tests use fixed-content `assets/seed_inputs/` images.
|
| 313 |
+
|
| 314 |
+
---
|
| 315 |
+
|
| 316 |
+
## 10. Repo, license, naming, conventions
|
| 317 |
+
|
| 318 |
+
| Item | Value |
|
| 319 |
+
| ------------------- | ------------------------------------------------------ |
|
| 320 |
+
| Local path | `/Users/techfreakworm/Projects/llm/z-image-studio` |
|
| 321 |
+
| GitHub repo (default) | `techfreakworm/z-image-studio` (confirm during plan) |
|
| 322 |
+
| HF Space (default) | `techfreakworm/z-image-studio` (confirm during plan) |
|
| 323 |
+
| License | **MIT** — DiffSynth (Apache-2.0) listed as dependency, not redistributed |
|
| 324 |
+
| Python | 3.11 (matches LTX, HF base image) |
|
| 325 |
+
| venv | `python3.11 -m venv .venv` — no conda |
|
| 326 |
+
| Model fetches | `hf` CLI (not `huggingface-cli`), HF cache |
|
| 327 |
+
| Linter | `ruff format` + `ruff check` |
|
| 328 |
+
| Commits | Conventional Commits style (`feat(ui): ...`, `fix(backend): ...`, etc.) — sole author = Mayank Gupta — no Claude co-author trailer, no "Generated with…" footer |
|
| 329 |
+
|
| 330 |
+
---
|
| 331 |
+
|
| 332 |
+
## 11. Decisions implicit in this spec (confirm in review)
|
| 333 |
+
|
| 334 |
+
1. **No t2v-style workflow JSON files** — DiffSynth's Python call surface IS the API, so we hand-code the four call shapes in `modes.py` (vs LTX which parameterizes JSONs).
|
| 335 |
+
2. **One pipeline instance** shared across modes. Transformer swap = the only model-pool change.
|
| 336 |
+
3. **No persistent storage add-on** needed — Pro Space + ephemeral storage is enough.
|
| 337 |
+
4. **License MIT** — say otherwise during review if you'd prefer Apache-2.0.
|
| 338 |
+
5. **ControlNet preload is in the YAML** — accept the larger startup at the gain of zero first-ControlNet-call wait. If RAM is tight at boot we'll move it to lazy.
|
| 339 |
+
|
| 340 |
+
---
|
| 341 |
+
|
| 342 |
+
## 12. Open questions (none blocking implementation)
|
| 343 |
+
|
| 344 |
+
- Final GitHub + HF namespace strings (defaults above are placeholders).
|
| 345 |
+
|
| 346 |
+
Everything else is settled. Ready to hand off to `writing-plans` for the implementation plan.
|