---
title: Universal Model Character LoRA Studio
emoji: 🎨
colorFrom: gray
colorTo: green
sdk: gradio
hf_oauth: true
fullWidth: true
sdk_version: 6.31.0
python_version: '3.12'
app_file: app.py
pinned: true
short_description: "Run waveshaker's 𝗠𝗢𝗦𝗦/𝗞𝗿𝗲𝗮𝟮/𝗔𝗻𝗶𝗺𝗮/𝗙𝗟𝗨𝗫/𝗣𝗼𝗻𝘆 LoRAs"
---
---
⚡ Universal LoRA Studio
---
### ⚙️ System Architecture
This Space is a specialized, on-demand inference engine designed to run Waveshaker's character LoRAs on ZeroGPU. To overcome Hugging Face's cross-space CORS restrictions and ZeroGPU's billing constraints, I use a **decoupled "Proxy-Driven" architecture** with a blazing-fast native frontend.
#### 🏗️ System Topology
| Layer | Role & Responsibility |
| :--- | :--- |
| **🖥 Client Layer** | Handles OAuth authentication, renders the UI, manages background file pre-warming, and submits payload parameters. |
| **🧠 Proxy & Scheduler Layer**
(FastAPI + Gradio) | Manages scanner bypasses, executes model pre-warming, serializes tasks, and enforces system limits. |
| **⚡ Execution Layer**
(ZeroGPU + ComfyUI) | Utilizes native SafeTensors loading with Linux Page Cache acceleration, leverages ComfyUI's native cache for model hot-swapping, and outputs WebP images with EXIF metadata.|
#### 🔄 Request Lifecycle
```text
[User] ──(OAuth Login)──► [Native Studio UI]
│
│ (POST `/api/warmup` & `/api/generate`)
▼
[FastAPI Gateway & Daemon Scheduler]
├── Input Validation (Enforces 1536px & steps limit)
├── ContextVar (Binds task_id & x-ip-token)
└── Native Daemon Thread (Decouples HTTP response)
│
┌─────────────────────┴─────────────────────┐
▼ (Parallel Page-Cache Preload) ▼ (On-Demand Prep)
[WarmupManager State Machine] [Background Worker & Env Prep]
├── P0 Preemption & posix_fadvise ├── On-demand LoRA download
├── Yield to _gen_inflight I/O └── Model switch lock (_model_switch_lock)
└── Syncs /tmp/warmup_state.json │
│ (Requests GPU slice)
▼
[Gradio + ZeroGPU (@spaces.GPU duration=90)]
├── Dummy Probe (Retains quota & allocates slot)
├── _warm_wait_in_gpu (Smart wait if progress ≥90%)
└── Threading Lock (Serializes jobs via _exec_lock)
│
│ (Passes to Singleton Executor)
▼
[ComfyUI Core Engine]
├── Loader Chain Cache (Stable node IDs)
├── RAM_PRESSURE Cache (lru=8, ram=16GB)
└── UnifiedProgressTqdm (Live step metrics)
│
│ (Outputs raw PNG)
▼
[Pillow Post-Processing & Re-warm]
├── WebP (Q90) + Binary EXIF Metadata Injection
└── Post-Gen Re-warm (Triggers WILLNEED)
│
▼
[Static `/output/` Mount] ──► [Browser Renders Image]
```
#### 📝 One-Sentence Summary
> A decoupled "Proxy-Driven" architecture: a native frontend passes LoRA parameters via URL, while a Gradio proxy bypasses cross-space CORS and ZeroGPU billing constraints. It serves generated images as physical WebP URLs with custom-injected ComfyUI EXIF metadata, delivering accurate billing.
#### 📜 Architecture Evolution
- **v0.1 (The FastAPI Initiation)**: The initial dual-track setup. FastAPI handled data routing, while Gradio rendered the UI. Due to cross-space CORS restrictions and a lack of `x-ip-token` handling, the frontend fell into the ZeroGPU anonymous pool.
- **v0.2 (The Gradio-Injection Era)**: A modular reconstruction (`core/`, `frontend/`, `ui/`). Introduced the `task_runner` for precise background scheduling and logging. To retain ZeroGPU billing, I hid Gradio components and injected native HTML/CSS/JS via Python. This successfully kept the GPU quota but introduced frontend performance bottlenecks and UI state sync issues.
- **v0.3 (The Decoupled Proxy UI)**: A new refactor. A 100% native static web UI is decoupled from the FastAPI backend. I implemented a dummy Gradio probe to trick the ZeroGPU scanner and used `ContextVar` to perfectly pass through the `x-ip-token`. Featuring a dual-Space sync mechanism (`frontend_cache`), it delivers faster loading,accurate ZeroGPU billing, and a pure native frontend experience.
- **v0.4 (The Performance Hardened Era)**: A brutal optimization phase to eliminate the 50s+ cold-start latency and multi-model memory leaks under ZeroGPU.
- **Binary Tensor Fast-Path**: Bypassed ComfyUI's native slow loading path by intercepting `load_torch_file` and implementing `numpy` zero-copy for large INT8/ConvRot tensors.
- **Lazy Execution & Native Cache**: Removed aggressive `empty_cache` and manual GC interventions. Relied entirely on ComfyUI's native `RAM_PRESSURE` (LRU 8, 16GB RAM limit) to orchestrate multi-model hot-swapping smoothly.
- **Queue-Aware Billing**: Adjusted `@spaces.GPU(duration=40)` to gracefully handle ZeroGPU queueing spikes during consecutive architecture switching.
- **Safety Boundaries**: Enforced hard pixel and edge limits (1536px) at both frontend and FastAPI levels to prevent OOM and timeout kills.
- **Result**: Cold-start load time dropped from ~24s to **~6.5s**. Cross-architecture hot-swapping (e.g., Flux 1536 → MOSS 1536) stabilized under **15s total**, completely eliminating the "ghost 35s" timeouts.
- **v0.5 (The Zero-Cost Warmup & Concurrency Hardened Era)**: Eliminated disk cold-read bottlenecks without burning a single second of ZeroGPU quota, while hardening full-stack state synchronization.
- **Page-Cache Warmup State Machine (`WarmupManager`)**: Implemented a pure CPU/IO file pre-warming engine using `os.posix_fadvise(WILLNEED)` and chunked sequential reads. Features dynamic cgroup v1/v2 memory budget awareness (`60% limit - anon`), random 32MB read-speed verification (`>= 600 MB/s`), and priority preemption (`P0` user selection interrupts `P1` boot sweep).
- **Tiered & Zero-GPU-Waste Scheduling**: Added a 3-tier frontend-backend warmup handshake (`lite` 200MB header read on page entry → `full` model preload on selection → 10-min `touch` heartbeat). In-GPU residual waits (`WARMUP_RESIDUAL_WAIT = 5.0s`) automatically abort early if warmup progress `< 90%`, avoiding idle GPU quota burn.
- **Stable Loader Chain & Progress Interception**: Locked loader node IDs (`1..N`) to maximize ComfyUI `RAM_PRESSURE` node-cache hits. Replaced `tqdm` with a re-entrant ref-counted monkey-patch bound to `ContextVar` and atomic `/tmp` metric dumps (`os.replace`) for flicker-free step/load telemetry.
- **Quota Ceiling & Resilience**: Raised `@spaces.GPU(duration=90)` (ceiling, not billed) to protect cold-start model loading from premature timeouts. Added exponential backoff retries, config background healing, and deep-link (`?model=&lora=`) image prefetching on the frontend.
- **v0.6 (The Targeted Preload & Zero-Stall Polish)**: Eliminated background I/O thrashing, state-file race conditions, and self-preemption bottlenecks discovered during real-world multi-model stress testing.
Targeted On-Demand Preloading: Disabled blind full-repository boot sweeps (`boot_sweep`) and background task resurrection (`_resume`). Restricted background disk reads strictly to the active/selected model, preventing idle models (e.g., MOSS) from evicting the user's current target (e.g., Krea2) out of the Linux Page Cache.
Zero-Stall GPU Entry: Removed the in-GPU residual wait (`_warm_wait_in_gpu`) to eliminate a 5.0s quota-burning stall caused by background sweep tasks overwriting the global warmup state file (`target="__sweep__"`). GPU slices now begin execution with 0ms delay upon allocation.
Same-Target Preload Coalescing: Added active-plan deduplication in `WarmupManager.request()` so rapid `select` → `submit` transitions coalesce seamlessly and inherit the generation `task_id` without resetting active file reads.
Tightened Quota Ceiling: Re-tuned `@spaces.GPU(duration=40)` to improve ZeroGPU queue scheduling priority while maintaining full cold-start headroom.
---
### 🔗 Ecosystem Links
- 🖼️ **[Browse the LoRA Gallery](https://huggingface.co/spaces/waveshaker/loras_gallery)** - Explore 1000+ community characters.
- 📊 **[Dataset](https://huggingface.co/datasets/waveshaker/dataset_collections)**
Engineered by waveshaker. Running on ZeroGPU. Duplicated and modified from 2i/pornmaster-krea2.