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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
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
latent_history = []

# ============================================================
# 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")


# ============================================================
# FUNCTION TO CONVERT LATENTS TO IMAGE
# ============================================================
def latent_to_image(latent):
    try:
        img_tensor = pipe.vae.decode(latent)
        img_tensor = (img_tensor / 2 + 0.5).clamp(0, 1)
        pil_img = T.ToPILImage()(img_tensor[0])
        return pil_img
    except Exception as e:
        log(f"⚠️ Failed to decode latent: {e}")
        return None



# ============================================================
# 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,
        attn_implementation="kernels-community/vllm-flash-attn3",
    )
    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")





from PIL import Image
import torch




def safe_generate_with_latents(
 transformer,
 vae,
 text_encoder,
 tokenizer,
 scheduler,
 pipe,
 prompt,
 height,
 width,
 steps,
 guidance_scale,
 negative_prompt,
 num_images_per_prompt,
 generator,
 cfg_normalization,
 cfg_truncation,
 max_sequence_length,
 ):

 try:

  latents_or_images = generate(
  transformer=transformer,
  vae=vae,
  text_encoder=text_encoder,
  tokenizer=tokenizer,
  scheduler=scheduler,
  prompt=prompt,
  height=height,
  width=width,
  num_inference_steps=steps,
  guidance_scale=guidance_scale,
  negative_prompt=negative_prompt,
  num_images_per_prompt=num_images_per_prompt,
  generator=generator,
  cfg_normalization=cfg_normalization,
  cfg_truncation=cfg_truncation,
  max_sequence_length=max_sequence_length,
  output_type="latent", # IMPORTANT
  )

  return latents_or_images, None

 except Exception as e:
    return None, e











def safe_get_latents(pipe, height, width, generator, device, LOGS):
    """
    Attempts multiple ways to get latents.
    Returns a valid tensor even if pipeline hides UNet.
    """
    # Try official prepare_latents
    try:
        if hasattr(pipe, "unet") and hasattr(pipe.unet, "in_channels"):
            num_channels = pipe.unet.in_channels
            latents = pipe.prepare_latents(
                batch_size=1,
                num_channels=num_channels,
                height=height,
                width=width,
                dtype=torch.float32,
                device=device,
                generator=generator
            )
            LOGS.append("βœ… Latents extracted using official prepare_latents.")
            return latents
    except Exception as e:
        LOGS.append(f"⚠️ Official latent extraction failed: {e}")

    # Try hidden internal attribute
    try:
        if hasattr(pipe, "_default_latents"):
            LOGS.append("⚠️ Using hidden _default_latents.")
            return pipe._default_latents
    except:
        pass

    # Fallback: raw Gaussian tensor
    try:
        LOGS.append("⚠️ Using raw Gaussian latents fallback.")
        return torch.randn(
            (1, 4, height // 8, width // 8),
            generator=generator,
            device=device,
            dtype=torch.float32
        )
    except Exception as e:
        LOGS.append(f"⚠️ Gaussian fallback failed: {e}")

    LOGS.append("❗ Using CPU hard fallback latents.")
    return torch.randn((1, 4, height // 8, width // 8))


# --------------------------
# Main generation function
# --------------------------
@spaces.GPU
def generate_image(prompt, height, width, steps, seed, guidance_scale=0.0):
 LOGS = []
 def log(msg):
  LOGS.append(msg)
  print(msg)


 generator = torch.Generator(device).manual_seed(int(seed))
 log("🎨 START IMAGE GENERATION")
# ==========================================================
# πŸ§ͺ TRY ADVANCED LATENT GENERATOR (Your original generate())
# ==========================================================
 latents, latent_err = safe_generate_with_latents(
    transformer=transformer,
    vae=vae,
    text_encoder=text_encoder,
    tokenizer=tokenizer,
    scheduler=scheduler,
    pipe=pipe,
    prompt=prompt,
    height=height,
    width=width,
    steps=steps,
    guidance_scale=guidance_scale,
    negative_prompt="",
    num_images_per_prompt=1,
    generator=generator,
    cfg_normalization=False,
    cfg_truncation=1.0,
    max_sequence_length=4096,
   )

 if latent_err is None:
    log("βœ… Latent generator succeeded.")
    try:
        # Decode latents to image
        shift_factor = getattr(vae.config, "shift_factor", 0.0) or 0.0
        dec = (latents.to(vae.dtype) / vae.config.scaling_factor) + shift_factor
        image = vae.decode(dec, return_dict=False)[0]

        image = (image / 2 + 0.5).clamp(0, 1)
        image = image.cpu().permute(0, 2, 3, 1).numpy()
        image = (image * 255).round().astype("uint8")
        from PIL import Image
        image = Image.fromarray(image[0])

        log("🟒 Final image decoded from latent generator.")
        return image, latents, LOGS

    except Exception as decode_error:
        log(f"⚠️ Latent decode failed: {decode_error}")
        log("πŸ” Falling back to standard pipeline...")

 else:
    log(f"⚠️ Latent generator failed: {latent_err}")
    log("πŸ” Switching to standard pipeline...")

# ==========================================================
# 🟩 STANDARD PIPELINE FALLBACK (Never fails)
# ==========================================================
 try:
    output = pipe(
        prompt=prompt,
        height=height,
        width=width,
        num_inference_steps=steps,
        guidance_scale=guidance_scale,
        generator=generator,
    )
    image = output.images[0]
    log("🟒 Standard pipeline succeeded.")
    return image, None, LOGS

 except Exception as e:
    log(f"❌ Standard pipeline failed: {e}")
    return None, None, LOGS

# --------------------------
# Helper: Safe latent extractor
# --------------------------
def safe_get_latents0(pipe, height, width, generator, device, LOGS):
    """
    Attempts multiple ways to get latents.
    Returns a valid tensor even if pipeline hides UNet.
    """
    # Try official prepare_latents
    try:
        if hasattr(pipe, "unet") and hasattr(pipe.unet, "in_channels"):
            num_channels = pipe.unet.in_channels
            latents = pipe.prepare_latents(
                batch_size=1,
                num_channels=num_channels,
                height=height,
                width=width,
                dtype=torch.float32,
                device=device,
                generator=generator
            )
            LOGS.append("βœ… Latents extracted using official prepare_latents.")
            return latents
    except Exception as e:
        LOGS.append(f"⚠️ Official latent extraction failed: {e}")

    # Try hidden internal attribute
    try:
        if hasattr(pipe, "_default_latents"):
            LOGS.append("⚠️ Using hidden _default_latents.")
            return pipe._default_latents
    except:
        pass

    # Fallback: raw Gaussian tensor
    try:
        LOGS.append("⚠️ Using raw Gaussian latents fallback.")
        return torch.randn(
            (1, 4, height // 8, width // 8),
            generator=generator,
            device=device,
            dtype=torch.float32
        )
    except Exception as e:
        LOGS.append(f"⚠️ Gaussian fallback failed: {e}")

    LOGS.append("❗ Using CPU hard fallback latents.")
    return torch.randn((1, 4, height // 8, width // 8))


# --------------------------
# Main generation function
# --------------------------
@spaces.GPU
def generate_image0(prompt, height, width, steps, seed, guidance_scale=0.0):
    LOGS = []
    latents = None
    image = None
    gallery = []

    # placeholder image if all fails
    placeholder = Image.new("RGB", (width, height), color=(255, 255, 255))
    print(prompt)

    try:
        generator = torch.Generator(device).manual_seed(int(seed))

        # -------------------------------
        # Try advanced latent extraction
        # -------------------------------
        try:
            latents = safe_get_latents(pipe, height, width, generator, device, LOGS)

            output = pipe(
                prompt=prompt,
                height=height,
                width=width,
                num_inference_steps=steps,
                guidance_scale=guidance_scale,
                generator=generator,
                latents=latents
            )

            image = output.images[0]
            gallery = [image]
            LOGS.append("βœ… Advanced latent pipeline succeeded.")

        except Exception as e:
            LOGS.append(f"⚠️ Latent mode failed: {e}")
            LOGS.append("πŸ” Switching to standard pipeline...")

            try:
                output = pipe(
                    prompt=prompt,
                    height=height,
                    width=width,
                    num_inference_steps=steps,
                    guidance_scale=guidance_scale,
                    generator=generator,
                )
                image = output.images[0]
                gallery = [image]
                LOGS.append("βœ… Standard pipeline succeeded.")

            except Exception as e2:
                LOGS.append(f"❌ Standard pipeline failed: {e2}")
                image = placeholder
                gallery = [image]

        return image, gallery, LOGS

    except Exception as e:
        LOGS.append(f"❌ Total failure: {e}")
        return placeholder, [placeholder], LOGS

# ============================================================
# UI
# ============================================================

with gr.Blocks(title="Z-Image- experiment - dont run")as demo:
  gr.Markdown("# **πŸš€ do not run Z-Image-Turbo β€” Final Image & Latents**")


  with gr.Row():
    with gr.Column(scale=1):
        prompt = gr.Textbox(label="Prompt", value="boat in Ocean")
        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, 50, value=20, step=1, label="Inference Steps")
        seed = gr.Number(value=42, label="Seed")
        run_btn = gr.Button("Generate Image")

    with gr.Column(scale=1):
        final_image = gr.Image(label="Final Image")
        latent_gallery = gr.Gallery(
           label="Latent Steps",
                columns=4,
              height=256,
             preview=True
              )

        logs_box = gr.Textbox(label="Logs", lines=15)

    run_btn.click(
      generate_image,
      inputs=[prompt, height, width, steps, seed],
      outputs=[final_image, latent_gallery, logs_box]
     )



demo.launch()