Spaces:
Runtime error
Runtime error
moose commited on
Commit ·
73a98d6
1
Parent(s): 6c84590
Revert "Fix OOM by deferring model loading and AOT compilation to runtime"
Browse filesThis reverts commit 49afc981b928f696a30599430f66fe00bca60375.
Files changed (2)
- app.py+19-56
- optimization.py+5-21
23 unmodified lines242526272829303132333458 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511525 unmodified lines1581591601611621631649 unmodified lines17417517617717817918018118223 unmodified linesimport osimport gradio as gr# --- Lazy Loading State ---# Pipeline is loaded lazily on first inference to avoid memory issues during build_pipeline_instance = None_pipeline_initialized = Falsedef turn_into_video(input_images, output_images, prompt, progress=gr.Progress(track_tqdm=True)):if not input_images or not output_images:raise gr.Error("Please generate an output image first.")58 unmodified linesreturn gr.update(value=[evt.value])return gr.update()# --- Model Loading (Lazy) ---dtype = torch.bfloat16device = "cuda" if torch.cuda.is_available() else "cpu"def get_pipeline():"""Lazily initialize the pipeline on first use.This avoids loading ~40GB of models during build, which causes OOM.The pipeline is loaded and compiled on the first inference requestwhen GPU resources are available via ZeroGPU."""global _pipeline_instance, _pipeline_initializedif _pipeline_initialized:return _pipeline_instanceprint("=== Initializing pipeline (first request) ===")# Load the pipeline with transformerpipe = QwenImageEditPlusPipeline.from_pretrained("Qwen/Qwen-Image-Edit-2509",transformer=QwenImageTransformer2DModel.from_pretrained("linoyts/Qwen-Image-Edit-Rapid-AIO",subfolder='transformer',torch_dtype=dtype,device_map='cuda'),torch_dtype=dtype).to(device)# Load and fuse LoRA weightspipe.load_lora_weights("lovis93/next-scene-qwen-image-lora-2509",weight_name="next-scene_lora-v2-3000.safetensors",adapter_name="next-scene")pipe.set_adapters(["next-scene"], adapter_weights=[1.])pipe.fuse_lora(adapter_names=["next-scene"], lora_scale=1.)pipe.unload_lora_weights()# Apply optimizationspipe.transformer.__class__ = QwenImageTransformer2DModelpipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())# AOT compilation (already in GPU context from infer())print("=== Starting AOT compilation ===")optimize_pipeline_(pipe, image=[Image.new("RGB", (1024, 1024)), Image.new("RGB", (1024, 1024))], prompt="prompt", already_in_gpu_context=True)print("=== AOT compilation complete ===")_pipeline_instance = pipe_pipeline_initialized = Truereturn pipe# --- UI Constants and Helpers ---MAX_SEED = np.iinfo(np.int32).max5 unmodified linesreturn output_images# --- Main Inference Function (with hardcoded negative prompt) ---@spaces.GPU(duration=600) # Increased duration for first-request initializationdef infer(images,prompt,9 unmodified lines"""Generates an image using the local Qwen-Image diffusers pipeline."""# Get or initialize the pipeline (lazy loading)pipe = get_pipeline()# Hardcode the negative prompt as requestednegative_prompt = " "23 unmodified lines24252627282958 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171185 unmodified lines1241251261271281291309 unmodified lines14014114214314414523 unmodified linesimport osimport gradio as grdef turn_into_video(input_images, output_images, prompt, progress=gr.Progress(track_tqdm=True)):if not input_images or not output_images:raise gr.Error("Please generate an output image first.")58 unmodified linesreturn gr.update(value=[evt.value])return gr.update()# --- Model Loading ---dtype = torch.bfloat16device = "cuda" if torch.cuda.is_available() else "cpu"pipe = QwenImageEditPlusPipeline.from_pretrained("Qwen/Qwen-Image-Edit-2509",transformer= QwenImageTransformer2DModel.from_pretrained("linoyts/Qwen-Image-Edit-Rapid-AIO",subfolder='transformer',torch_dtype=dtype,device_map='cuda'),torch_dtype=dtype).to(device)pipe.load_lora_weights("lovis93/next-scene-qwen-image-lora-2509",weight_name="next-scene_lora-v2-3000.safetensors", adapter_name="next-scene")pipe.set_adapters(["next-scene"], adapter_weights=[1.])pipe.fuse_lora(adapter_names=["next-scene"], lora_scale=1.)pipe.unload_lora_weights()# Apply the same optimizations from the first versionpipe.transformer.__class__ = QwenImageTransformer2DModelpipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())# --- Ahead-of-time compilation ---optimize_pipeline_(pipe, image=[Image.new("RGB", (1024, 1024)), Image.new("RGB", (1024, 1024))], prompt="prompt")# --- UI Constants and Helpers ---MAX_SEED = np.iinfo(np.int32).max5 unmodified linesreturn output_images# --- Main Inference Function (with hardcoded negative prompt) ---@spaces.GPU(duration=300)def infer(images,prompt,9 unmodified lines"""Generates an image using the local Qwen-Image diffusers pipeline."""# Hardcode the negative prompt as requestednegative_prompt = " "
44 unmodified lines45464748495051525354555657585960611 unmodified line636465666768693 unmodified lines737475767778798081828384858644 unmodified lines}def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, already_in_gpu_context: bool = False, **kwargs: P.kwargs):"""Optimize the pipeline transformer with AOT compilation.Args:pipeline: The diffusion pipeline to optimizealready_in_gpu_context: If True, skip the @spaces.GPU decorator since we'realready running in a GPU context (e.g., called from within infer())"""def _compile_transformer_impl():with spaces.aoti_capture(pipeline.transformer) as call:pipeline(*args, **kwargs)1 unmodified linedynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES# quantize_(pipeline.transformer, Float8DynamicActivationFloat8WeightConfig())exported = torch.export.export(mod=pipeline.transformer,args=call.args,3 unmodified linesreturn spaces.aoti_compile(exported, INDUCTOR_CONFIGS)if already_in_gpu_context:# We're already in a GPU context, run directlycompiled = _compile_transformer_impl()else:# Need to allocate GPU for compilation@spaces.GPU(duration=1500)def compile_transformer():return _compile_transformer_impl()compiled = compile_transformer()spaces.aoti_apply(compiled, pipeline.transformer)44 unmodified lines45464748495051525354551 unmodified line575859606162633 unmodified lines6768697044 unmodified lines}def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):@spaces.GPU(duration=1500)def compile_transformer():with spaces.aoti_capture(pipeline.transformer) as call:pipeline(*args, **kwargs)1 unmodified linedynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES# quantize_(pipeline.transformer, Float8DynamicActivationFloat8WeightConfig())exported = torch.export.export(mod=pipeline.transformer,args=call.args,3 unmodified linesreturn spaces.aoti_compile(exported, INDUCTOR_CONFIGS)spaces.aoti_apply(compile_transformer(), pipeline.transformer)
app.py+19-56
optimization.py+5-21