Align defaults with official example (keep Advanced controls)
Browse files53 unmodified lines5455565758596053 unmodified lines- Prompt- Resolution category + explicit WxH selection- Seed (with random toggle)- Steps, CFG, scheduler + shift (and extra scheduler params), max sequence length- LoRA toggle + strength (enabled only if the file is found)## Git LFS note53 unmodified lines545556575859606153 unmodified lines- Prompt- Resolution category + explicit WxH selection- Seed (with random toggle)- Steps + Time Shift- Advanced: CFG, scheduler + extra scheduler params, max sequence length- LoRA toggle + strength (enabled only if the file is found)## Git LFS note
149 unmodified lines1501511521531541551561571581597 unmodified lines1671681691701711721731 unmodified line1751761771781791802 unmodified lines1831841851861871883 unmodified lines192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232193 unmodified lines4264274284294304314324334344 unmodified lines4394404414424434444454464474484494504514524534544552 unmodified lines45845946046146246346446546646711 unmodified lines47948048148248348448548648712 unmodified lines50050150250350450550650750850951051151251351436 unmodified lines55155255355455555655755855956056156256356456516 unmodified lines58258358458558658758858959059159259359459533 unmodified lines62963063163263363463563663763810 unmodified lines649650651652653654655656657658659660661662663149 unmodified linespipe: ZImagePipeline | None = Nonelora_loaded: bool = Falselora_error: str | None = Nonepipe_lock = threading.Lock()pipe_on_gpu: bool = Falseaoti_loaded: bool = Falseapplied_attention_backend: str | None = Noneaoti_error: str | None = Nonetransformer_compiled: bool = Falsetransformer_compile_attempted: bool = False7 unmodified linesexcept Exception:passdef module_available(module_name: str) -> bool:try:return importlib.util.find_spec(module_name) is not None1 unmodified linereturn Falsedef parse_resolution(resolution: str) -> Tuple[int, int]:match = re.search(r"(\d+)\s*[×x]\s*(\d+)", resolution)if match:2 unmodified linesdef set_attention_backend_safe(transformer, backend: str) -> str:candidates: List[str] = []if backend:candidates.append(backend)3 unmodified linescandidates.append(f"_{backend}")candidates.extend(["flash", "xformers", "native"])last_exc: Exception | None = Nonefor name in candidates:if not name:continuetry:transformer.set_attention_backend(name)return nameexcept Exception as exc: # noqa: BLE001last_exc = exccontinueraise RuntimeError(f"Failed to set attention backend (tried {candidates}): {last_exc}")def attach_lora(pipeline: ZImagePipeline) -> Tuple[bool, str | None]:if not LORA_PATH or not os.path.isfile(LORA_PATH):return False, "LoRA file not found"if not module_available("peft"):return False, "PEFT backend is required for LoRA. Install `peft` and restart."try:folder, weight_name = os.path.split(LORA_PATH)folder = folder or "."pipeline.load_lora_weights(folder, weight_name=weight_name)set_lora_scale(pipeline, 1.0)return True, Noneexcept Exception as exc: # noqa: BLE001return False, f"Failed to load LoRA: {exc}"def set_lora_scale(pipeline: ZImagePipeline, scale: float) -> None:weight = max(float(scale), 0.0)try:pipeline.set_adapters(["default"], adapter_weights=[weight])except TypeError:pipeline.set_adapters(["default"], weights=[weight])def load_models() -> Tuple[ZImagePipeline, bool, str | None]:193 unmodified linessteps: int,shift: float,guidance_scale: float,max_sequence_length: int,use_lora: bool,lora_scale: float,scheduler_name: str,num_train_timesteps: int,use_dynamic_shifting: bool,4 unmodified linesgenerator = torch.Generator("cuda").manual_seed(seed)set_scheduler(pipeline,scheduler_name,num_train_timesteps=num_train_timesteps,shift=shift,use_dynamic_shifting=use_dynamic_shifting,base_shift=base_shift,max_shift=max_shift,)if lora_loaded:if use_lora:set_lora_scale(pipeline, lora_scale)else:set_lora_scale(pipeline, 0.0)2 unmodified linesprompt=prompt,height=height,width=width,guidance_scale=guidance_scale,num_inference_steps=steps,generator=generator,max_sequence_length=max_sequence_length,).images[0]return image, seed11 unmodified linessteps=9,shift=3.0,guidance_scale=0.0,max_sequence_length=512,use_lora=False,lora_scale=0.0,scheduler_name="FlowMatch Euler",num_train_timesteps=1000,use_dynamic_shifting=False,12 unmodified linesif ENABLE_COMPILE and pipe is not None:ensure_on_gpu()if ENABLE_AOTI and not aoti_loaded and pipe is not None and getattr(pipe, "transformer", None) is not None:try:pipe.transformer.layers._repeated_blocks = ["ZImageTransformerBlock"]spaces.aoti_blocks_load(pipe.transformer.layers, AOTI_REPO, variant=AOTI_VARIANT)aoti_loaded = Trueaoti_error = Noneprint(f"AoTI loaded: {AOTI_REPO} (variant={AOTI_VARIANT})")except Exception as exc: # noqa: BLE001aoti_error = str(exc)print(f"AoTI load failed (continuing without AoTI): {exc}")if ENABLE_WARMUP and pipe is not None:ensure_on_gpu()try:36 unmodified linestry:image = generate_image(pipeline=pipe,prompt=prompt,resolution=resolution.split(" ")[0] if " " in resolution else resolution,seed=new_seed,steps=int(steps) + 1,shift=float(shift),guidance_scale=float(cfg),max_sequence_length=int(max_sequence_length),use_lora=use_lora,lora_scale=float(lora_scale),scheduler_name=str(scheduler_name),num_train_timesteps=int(num_train_timesteps),use_dynamic_shifting=bool(use_dynamic_shifting),16 unmodified linespipe_status = "loaded (GPU)" if pipe and pipe_on_gpu else "loaded (CPU)" if pipe else "not loaded"lora_file_status = "found" if os.path.isfile(LORA_PATH) else "missing"if lora_loaded:lora_status = f"LoRA: loaded ({LORA_PATH})"elif lora_error:lora_status = f"LoRA: not loaded ({lora_error})"else:lora_status = f"LoRA file: {LORA_PATH} ({lora_file_status})"attention_status = applied_attention_backend or "unknown"aoti_status = "loaded" if aoti_loaded else f"failed ({aoti_error})" if aoti_error else "not loaded"if not ENABLE_COMPILE:compile_status = "off"elif transformer_compiled:33 unmodified linesseed = gr.Number(label="Seed", value=42, precision=0)random_seed = gr.Checkbox(label="Random Seed", value=True)with gr.Accordion("KSampler / Advanced", open=False):with gr.Row():steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=8, step=1)cfg = gr.Slider(label="CFG", minimum=0.0, maximum=10.0, value=DEFAULT_CFG, step=0.1)with gr.Row():scheduler_name = gr.Dropdown(10 unmodified lines)with gr.Row():shift = gr.Slider(label="Time Shift", minimum=1.0, maximum=10.0, value=3.0, step=0.1)use_dynamic_shifting = gr.Checkbox(label="use_dynamic_shifting", value=False)with gr.Row():base_shift = gr.Slider(label="base_shift", minimum=0.0, maximum=10.0, value=0.5, step=0.1)max_shift = gr.Slider(label="max_shift", minimum=0.0, maximum=10.0, value=3.0, step=0.1)max_seq = gr.Slider(label="Max Sequence Length", minimum=256, maximum=1024, value=512, step=16)with gr.Row():lora_controls_enabled = bool(lora_loaded)use_lora = gr.Checkbox(label="Use LoRA", value=lora_controls_enabled, interactive=lora_controls_enabled)149 unmodified lines1501511521531541551561571581591601617 unmodified lines1691701711721731741 unmodified line1761771781791801811821831841851861871882 unmodified lines1911921931941951961973 unmodified lines201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276193 unmodified lines4704714724734744754764774784 unmodified lines4834844854864874884894904914924934944954964974984992 unmodified lines50250350450550650750850951051111 unmodified lines52352452552652752852953053112 unmodified lines54454554654754854955055155255355455555655755855956056156256336 unmodified lines60060160260360460560660760860961061161261361416 unmodified lines63163263363463563663763863964064164264364464564664764864965065165265365433 unmodified lines68868969069169269369469569669769869910 unmodified lines710711712713714715716717718719720721722149 unmodified linespipe: ZImagePipeline | None = Nonelora_loaded: bool = Falselora_error: str | None = Nonelora_adapter_name: str | None = Nonepipe_lock = threading.Lock()pipe_on_gpu: bool = Falseaoti_loaded: bool = Falseapplied_attention_backend: str | None = Noneattention_backend_error: str | None = Noneaoti_error: str | None = Nonetransformer_compiled: bool = Falsetransformer_compile_attempted: bool = False7 unmodified linesexcept Exception:passdef module_available(module_name: str) -> bool:try:return importlib.util.find_spec(module_name) is not None1 unmodified linereturn Falsedef summarize_error(message: str, *, max_len: int = 120) -> str:one_line = " ".join(str(message).split())if len(one_line) <= max_len:return one_linereturn one_line[: max_len - 1] + "…"def parse_resolution(resolution: str) -> Tuple[int, int]:match = re.search(r"(\d+)\s*[×x]\s*(\d+)", resolution)if match:2 unmodified linesdef set_attention_backend_safe(transformer, backend: str) -> str:global attention_backend_errorcandidates: List[str] = []if backend:candidates.append(backend)3 unmodified linescandidates.append(f"_{backend}")candidates.extend(["flash", "xformers", "native"])attention_backend_error = Noneerrors: dict[str, Exception] = {}last_exc: Exception | None = Nonefor name in candidates:if not name:continuetry:transformer.set_attention_backend(name)if backend and name != backend:for key in (backend, backend.lstrip("_"), f"_{backend}"):if key in errors:attention_backend_error = str(errors[key])breakif attention_backend_error is None and last_exc is not None:attention_backend_error = str(last_exc)return nameexcept Exception as exc: # noqa: BLE001last_exc = excerrors[name] = exccontinueraise RuntimeError(f"Failed to set attention backend (tried {candidates}): {last_exc}")def attach_lora(pipeline: ZImagePipeline) -> Tuple[bool, str | None]:global lora_adapter_nameif not LORA_PATH or not os.path.isfile(LORA_PATH):return False, "LoRA file not found"if not module_available("peft"):return False, "PEFT backend is required for LoRA. Install `peft` and restart."def extract_present_adapter_names(exc: Exception) -> List[str]:msg = str(exc)match = re.search(r"present adapters:\s*(\{[^}]*\})", msg)if not match:return []return re.findall(r"'([^']+)'", match.group(1))try:folder, weight_name = os.path.split(LORA_PATH)folder = folder or "."preferred_adapter = os.environ.get("LORA_ADAPTER_NAME", "default")lora_adapter_name = preferred_adaptertry:pipeline.load_lora_weights(folder, weight_name=weight_name, adapter_name=preferred_adapter)except TypeError:pipeline.load_lora_weights(folder, weight_name=weight_name)try:set_lora_scale(pipeline, 1.0)except Exception as exc: # noqa: BLE001adapter_names = extract_present_adapter_names(exc)if adapter_names:lora_adapter_name = adapter_names[0]set_lora_scale(pipeline, 1.0)else:raisereturn True, Noneexcept Exception as exc: # noqa: BLE001lora_adapter_name = Nonereturn False, f"Failed to load LoRA: {exc}"def set_lora_scale(pipeline: ZImagePipeline, scale: float) -> None:weight = max(float(scale), 0.0)adapter = lora_adapter_name or "default"try:pipeline.set_adapters([adapter], adapter_weights=[weight])except TypeError:pipeline.set_adapters([adapter], weights=[weight])def load_models() -> Tuple[ZImagePipeline, bool, str | None]:193 unmodified linessteps: int,shift: float,guidance_scale: float,use_lora: bool,lora_scale: float,max_sequence_length: int,scheduler_name: str,num_train_timesteps: int,use_dynamic_shifting: bool,4 unmodified linesgenerator = torch.Generator("cuda").manual_seed(seed)set_scheduler(pipeline,str(scheduler_name),num_train_timesteps=int(num_train_timesteps),shift=float(shift),use_dynamic_shifting=bool(use_dynamic_shifting),base_shift=float(base_shift),max_shift=float(max_shift),)if lora_loaded:if use_lora:set_lora_scale(pipeline, float(lora_scale))else:set_lora_scale(pipeline, 0.0)2 unmodified linesprompt=prompt,height=height,width=width,guidance_scale=float(guidance_scale),num_inference_steps=int(steps),generator=generator,max_sequence_length=int(max_sequence_length),).images[0]return image, seed11 unmodified linessteps=9,shift=3.0,guidance_scale=0.0,use_lora=False,lora_scale=0.0,max_sequence_length=512,scheduler_name="FlowMatch Euler",num_train_timesteps=1000,use_dynamic_shifting=False,12 unmodified linesif ENABLE_COMPILE and pipe is not None:ensure_on_gpu()if ENABLE_AOTI and not aoti_loaded and pipe is not None and getattr(pipe, "transformer", None) is not None:if not module_available("kernels"):aoti_loaded = Falseaoti_error = "kernels module not available"print("AoTI unavailable (kernels module not available).")else:try:pipe.transformer.layers._repeated_blocks = ["ZImageTransformerBlock"]spaces.aoti_blocks_load(pipe.transformer.layers, AOTI_REPO, variant=AOTI_VARIANT)aoti_loaded = Trueaoti_error = Noneprint(f"AoTI loaded: {AOTI_REPO} (variant={AOTI_VARIANT})")except Exception as exc: # noqa: BLE001aoti_error = str(exc)print(f"AoTI load failed (continuing without AoTI): {exc}")if ENABLE_WARMUP and pipe is not None:ensure_on_gpu()try:36 unmodified linestry:image = generate_image(pipeline=pipe,prompt=str(prompt),resolution=str(resolution),seed=new_seed,steps=int(steps) + 1,shift=float(shift),guidance_scale=float(cfg),use_lora=use_lora,lora_scale=float(lora_scale),max_sequence_length=int(max_sequence_length),scheduler_name=str(scheduler_name),num_train_timesteps=int(num_train_timesteps),use_dynamic_shifting=bool(use_dynamic_shifting),16 unmodified linespipe_status = "loaded (GPU)" if pipe and pipe_on_gpu else "loaded (CPU)" if pipe else "not loaded"lora_file_status = "found" if os.path.isfile(LORA_PATH) else "missing"if lora_loaded:adapter = lora_adapter_name or "default"lora_status = f"LoRA: loaded ({LORA_PATH}, adapter={adapter})"elif lora_error:lora_status = f"LoRA: not loaded ({lora_error})"else:lora_status = f"LoRA file: {LORA_PATH} ({lora_file_status})"attention_status = applied_attention_backend or "unknown"if attention_backend_error and ATTENTION_BACKEND and attention_status != ATTENTION_BACKEND:attention_status = f"{attention_status} ({ATTENTION_BACKEND} unavailable: {summarize_error(attention_backend_error)})"if aoti_loaded:aoti_status = "loaded"elif aoti_error:label = "unavailable" if "kernels" in aoti_error.lower() else "failed"aoti_status = f"{label} ({summarize_error(aoti_error)})"else:aoti_status = "not loaded"if not ENABLE_COMPILE:compile_status = "off"elif transformer_compiled:33 unmodified linesseed = gr.Number(label="Seed", value=42, precision=0)random_seed = gr.Checkbox(label="Random Seed", value=True)with gr.Row():steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=8, step=1)shift = gr.Slider(label="Time Shift", minimum=1.0, maximum=10.0, value=3.0, step=0.1)with gr.Accordion("KSampler / Advanced", open=False):cfg = gr.Slider(label="CFG", minimum=0.0, maximum=10.0, value=DEFAULT_CFG, step=0.1)with gr.Row():scheduler_name = gr.Dropdown(10 unmodified lines)with gr.Row():use_dynamic_shifting = gr.Checkbox(label="use_dynamic_shifting", value=False)max_seq = gr.Slider(label="Max Sequence Length", minimum=256, maximum=1024, value=512, step=16)with gr.Row():base_shift = gr.Slider(label="base_shift", minimum=0.0, maximum=10.0, value=0.5, step=0.1)max_shift = gr.Slider(label="max_shift", minimum=0.0, maximum=10.0, value=3.0, step=0.1)with gr.Row():lora_controls_enabled = bool(lora_loaded)use_lora = gr.Checkbox(label="Use LoRA", value=lora_controls_enabled, interactive=lora_controls_enabled)
README.md+2-1
app.py+96-37