Spaces:
Restarting
on
Zero
Restarting
on
Zero
File size: 9,109 Bytes
a7fb1fd 85d3b9b 6eefcb5 b219c38 6eefcb5 a7fb1fd 85d3b9b a7fb1fd 85d3b9b a7fb1fd 6eefcb5 a7fb1fd 85d3b9b a7fb1fd 85d3b9b 6eefcb5 85d3b9b 6eefcb5 85d3b9b 6eefcb5 85d3b9b a7fb1fd 6eefcb5 b219c38 6eefcb5 b219c38 6eefcb5 b219c38 6eefcb5 b219c38 6eefcb5 b219c38 6eefcb5 b219c38 6eefcb5 b219c38 6eefcb5 b219c38 a7fb1fd 6eefcb5 a7fb1fd 85d3b9b 6eefcb5 a7fb1fd 85d3b9b a7fb1fd 85d3b9b 6eefcb5 a7fb1fd 85d3b9b a7fb1fd 85d3b9b 6eefcb5 85d3b9b 6eefcb5 a7fb1fd 6eefcb5 85d3b9b a7fb1fd 6eefcb5 a7fb1fd 3179e10 a7fb1fd 85d3b9b b219c38 6eefcb5 85d3b9b 6eefcb5 a7fb1fd 6eefcb5 a7fb1fd 6eefcb5 a7fb1fd 6eefcb5 a7fb1fd 6eefcb5 a7fb1fd 6eefcb5 85d3b9b a7fb1fd 6eefcb5 a7fb1fd 6eefcb5 a7fb1fd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
import torch
import spaces
import gradio as gr
import sys
import platform
import diffusers
import transformers
import psutil
import os
import time
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
from diffusers import ZImagePipeline, AutoModel
from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig
# ============================================================
# LOGGING BUFFER
# ============================================================
LOGS = ""
def log(msg):
global LOGS
print(msg)
LOGS += msg + "\n"
return msg
# ============================================================
# SYSTEM METRICS β LIVE GPU + CPU MONITORING
# ============================================================
def log_system_stats(tag=""):
try:
log(f"\n===== π₯ SYSTEM STATS {tag} =====")
# ============= GPU STATS =============
if torch.cuda.is_available():
allocated = torch.cuda.memory_allocated(0) / 1e9
reserved = torch.cuda.memory_reserved(0) / 1e9
total = torch.cuda.get_device_properties(0).total_memory / 1e9
free = total - allocated
log(f"π GPU Total : {total:.2f} GB")
log(f"π GPU Allocated : {allocated:.2f} GB")
log(f"π GPU Reserved : {reserved:.2f} GB")
log(f"π GPU Free : {free:.2f} GB")
# ============= CPU STATS ============
cpu = psutil.cpu_percent()
ram_used = psutil.virtual_memory().used / 1e9
ram_total = psutil.virtual_memory().total / 1e9
log(f"π§ CPU Usage : {cpu}%")
log(f"π§ RAM Used : {ram_used:.2f} GB / {ram_total:.2f} GB")
except Exception as e:
log(f"β οΈ Failed to log system stats: {e}")
# ============================================================
# ENVIRONMENT INFO
# ============================================================
log("===================================================")
log("π Z-IMAGE-TURBO DEBUGGING + LIVE METRIC LOGGER")
log("===================================================\n")
log(f"π PYTHON VERSION : {sys.version.replace(chr(10),' ')}")
log(f"π PLATFORM : {platform.platform()}")
log(f"π TORCH VERSION : {torch.__version__}")
log(f"π TRANSFORMERS VERSION : {transformers.__version__}")
log(f"π DIFFUSERS VERSION : {diffusers.__version__}")
log(f"π CUDA AVAILABLE : {torch.cuda.is_available()}")
log_system_stats("AT STARTUP")
if not torch.cuda.is_available():
raise RuntimeError("β CUDA Required")
device = "cuda"
gpu_id = 0
# ============================================================
# MODEL SETTINGS
# ============================================================
model_cache = "./weights/"
model_id = "Tongyi-MAI/Z-Image-Turbo"
torch_dtype = torch.bfloat16
USE_CPU_OFFLOAD = False
log("\n===================================================")
log("π§ MODEL CONFIGURATION")
log("===================================================")
log(f"Model ID : {model_id}")
log(f"Model Cache Directory : {model_cache}")
log(f"torch_dtype : {torch_dtype}")
log(f"USE_CPU_OFFLOAD : {USE_CPU_OFFLOAD}")
log_system_stats("BEFORE TRANSFORMER LOAD")
# ============================================================
# SAFE TRANSFORMER INSPECTION
# ============================================================
def inspect_transformer(model, name):
log(f"\nπ Inspecting {name}")
try:
candidates = ["transformer_blocks", "blocks", "layers", "encoder", "model"]
blocks = None
for attr in candidates:
if hasattr(model, attr):
blocks = getattr(model, attr)
break
if blocks is None:
log(f"β οΈ No block structure found in {name}")
return
if hasattr(blocks, "__len__"):
log(f"Total Blocks = {len(blocks)}")
else:
log("β οΈ Blocks exist but are not iterable")
for i in range(min(10, len(blocks) if hasattr(blocks, "__len__") else 0)):
log(f"Block {i} = {blocks[i].__class__.__name__}")
except Exception as e:
log(f"β οΈ Transformer inspect error: {e}")
# ============================================================
# LOAD TRANSFORMER β WITH LIVE STATS
# ============================================================
log("\n===================================================")
log("π§ LOADING TRANSFORMER BLOCK")
log("===================================================")
log("π Logging memory before load:")
log_system_stats("START TRANSFORMER LOAD")
try:
quant_cfg = DiffusersBitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch_dtype,
bnb_4bit_use_double_quant=True,
)
transformer = AutoModel.from_pretrained(
model_id,
cache_dir=model_cache,
subfolder="transformer",
quantization_config=quant_cfg,
torch_dtype=torch_dtype,
device_map=device,
)
log("β
Transformer loaded successfully.")
except Exception as e:
log(f"β Transformer load failed: {e}")
transformer = None
log_system_stats("AFTER TRANSFORMER LOAD")
if transformer:
inspect_transformer(transformer, "Transformer")
# ============================================================
# LOAD TEXT ENCODER
# ============================================================
log("\n===================================================")
log("π§ LOADING TEXT ENCODER")
log("===================================================")
log_system_stats("START TEXT ENCODER LOAD")
try:
quant_cfg2 = TransformersBitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch_dtype,
bnb_4bit_use_double_quant=True,
)
text_encoder = AutoModel.from_pretrained(
model_id,
cache_dir=model_cache,
subfolder="text_encoder",
quantization_config=quant_cfg2,
torch_dtype=torch_dtype,
device_map=device,
)
log("β
Text encoder loaded successfully.")
except Exception as e:
log(f"β Text encoder load failed: {e}")
text_encoder = None
log_system_stats("AFTER TEXT ENCODER LOAD")
if text_encoder:
inspect_transformer(text_encoder, "Text Encoder")
# ============================================================
# BUILD PIPELINE
# ============================================================
log("\n===================================================")
log("π§ BUILDING PIPELINE")
log("===================================================")
log_system_stats("START PIPELINE BUILD")
try:
pipe = ZImagePipeline.from_pretrained(
model_id,
transformer=transformer,
text_encoder=text_encoder,
torch_dtype=torch_dtype,
)
pipe.to(device)
log("β
Pipeline built successfully.")
except Exception as e:
log(f"β Pipeline build failed: {e}")
pipe = None
log_system_stats("AFTER PIPELINE BUILD")
# ============================================================
# INFERENCE
# ============================================================
@spaces.GPU
def generate_image(prompt, height, width, steps, seed):
global LOGS
LOGS = "" # reset logs
log("===================================================")
log("π¨ RUNNING INFERENCE")
log("===================================================")
log_system_stats("BEFORE INFERENCE")
try:
generator = torch.Generator(device).manual_seed(seed)
output = pipe(
prompt=prompt,
height=height,
width=width,
num_inference_steps=steps,
guidance_scale=0.0,
generator=generator,
)
log("β
Inference finished.")
log_system_stats("AFTER INFERENCE")
return output.images[0], LOGS
except Exception as e:
log(f"β Inference error: {e}")
return None, LOGS
# ============================================================
# UI
# ============================================================
with gr.Blocks(title="Z-Image Turbo Debugger") as demo:
gr.Markdown("## **Z-Image Turbo β Full Debug + Live GPU/CPU Monitor**")
with gr.Row():
with gr.Column(scale=1):
prompt = gr.Textbox(label="Prompt", value="Realistic male portrait")
height = gr.Slider(256, 2048, value=1024, step=8, label="Height")
width = gr.Slider(256, 2048, value=1024, step=8, label="Width")
steps = gr.Slider(1, 16, value=9, step=1, label="Steps")
seed = gr.Slider(0, 999999, value=42, step=1, label="Seed")
btn = gr.Button("Generate")
with gr.Column(scale=1):
image_out = gr.Image(label="Output")
logs_panel = gr.Textbox(label="π Logs", lines=30)
btn.click(generate_image,
inputs=[prompt, height, width, steps, seed],
outputs=[image_out, logs_panel])
demo.launch()
|