update system prompt
Browse files233 unmodified lines2342352362372382392402412422432442452462472482492502512522532542552562572582592602612 unmodified lines26426526626726826927027127227353 unmodified lines3273283293303313323333343353363373383393403413423433443453463473483493503513523533542 unmodified lines357358359360361362363364365366233 unmodified lines## Advanced ZeroGPU Optimization (Recommended)For production Spaces with heavy models, consider ahead-of-time (AoT) compilation for 1.3x-1.8x speedups:```pythonimport spacesimport torchfrom diffusers import DiffusionPipelinepipe = DiffusionPipeline.from_pretrained(..., torch_dtype=torch.bfloat16)pipe.to('cuda')@spaces.GPU(duration=1500) # Max duration for compilationdef compile_transformer():with spaces.aoti_capture(pipe.transformer) as call:pipe("arbitrary example prompt")exported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)return spaces.aoti_compile(exported)compiled_transformer = compile_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)2 unmodified linesreturn pipe(prompt).images```Optional enhancements:- FP8 quantization with torchao for additional 1.2x speedup (H200 compatible)- Dynamic shapes for variable input sizes- FlashAttention-3 via kernels library for attention speedups## Complete Gradio API Reference53 unmodified lines## Advanced ZeroGPU Optimization (Recommended)For production Spaces with heavy models, consider ahead-of-time (AoT) compilation for 1.3x-1.8x speedups:```pythonimport spacesimport torchfrom diffusers import DiffusionPipelinepipe = DiffusionPipeline.from_pretrained(..., torch_dtype=torch.bfloat16)pipe.to('cuda')@spaces.GPU(duration=1500) # Max duration for compilationdef compile_transformer():with spaces.aoti_capture(pipe.transformer) as call:pipe("arbitrary example prompt")exported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)return spaces.aoti_compile(exported)compiled_transformer = compile_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)2 unmodified linesreturn pipe(prompt).images```Optional enhancements:- FP8 quantization with torchao for additional 1.2x speedup (H200 compatible)- Dynamic shapes for variable input sizes- FlashAttention-3 via kernels library for attention speedups## Complete Gradio API Reference233 unmodified lines2342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682 unmodified lines27127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243353 unmodified lines4874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205212 unmodified lines524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686233 unmodified lines## Advanced ZeroGPU Optimization (Recommended)For production Spaces with heavy models, use ahead-of-time (AoT) compilation for 1.3x-1.8x speedups:### Basic AoT Compilation```pythonimport spacesimport torchfrom diffusers import DiffusionPipelineMODEL_ID = 'black-forest-labs/FLUX.1-dev'pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)pipe.to('cuda')@spaces.GPU(duration=1500) # Maximum duration allowed during startupdef compile_transformer():# 1. Capture example inputswith spaces.aoti_capture(pipe.transformer) as call:pipe("arbitrary example prompt")# 2. Export the modelexported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)# 3. Compile the exported modelreturn spaces.aoti_compile(exported)# 4. Apply compiled model to pipelinecompiled_transformer = compile_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)2 unmodified linesreturn pipe(prompt).images```### Advanced Optimizations#### FP8 Quantization (Additional 1.2x speedup on H200)```pythonfrom torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig@spaces.GPU(duration=1500)def compile_transformer_with_quantization():# Quantize before export for FP8 speedupquantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())with spaces.aoti_capture(pipe.transformer) as call:pipe("arbitrary example prompt")exported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)return spaces.aoti_compile(exported)```#### Dynamic Shapes (Variable input sizes)```pythonfrom torch.utils._pytree import tree_map@spaces.GPU(duration=1500)def compile_transformer_dynamic():with spaces.aoti_capture(pipe.transformer) as call:pipe("arbitrary example prompt")# Define dynamic dimension ranges (model-dependent)transformer_hidden_dim = torch.export.Dim('hidden', min=4096, max=8212)# Map argument names to dynamic dimensionstransformer_dynamic_shapes = {"hidden_states": {1: transformer_hidden_dim},"img_ids": {0: transformer_hidden_dim},}# Create dynamic shapes structuredynamic_shapes = tree_map(lambda v: None, call.kwargs)dynamic_shapes.update(transformer_dynamic_shapes)exported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,dynamic_shapes=dynamic_shapes,)return spaces.aoti_compile(exported)```#### Multi-Compile for Different Resolutions```python@spaces.GPU(duration=1500)def compile_multiple_resolutions():compiled_models = {}resolutions = [(512, 512), (768, 768), (1024, 1024)]for width, height in resolutions:# Capture inputs for specific resolutionwith spaces.aoti_capture(pipe.transformer) as call:pipe(f"test prompt {width}x{height}", width=width, height=height)exported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)compiled_models[f"{width}x{height}"] = spaces.aoti_compile(exported)return compiled_models# Usage with resolution dispatchcompiled_models = compile_multiple_resolutions()@spaces.GPUdef generate_with_resolution(prompt, width=1024, height=1024):resolution_key = f"{width}x{height}"if resolution_key in compiled_models:# Temporarily apply the right compiled modelspaces.aoti_apply(compiled_models[resolution_key], pipe.transformer)return pipe(prompt, width=width, height=height).images```#### FlashAttention-3 Integration```pythonfrom kernels import get_kernel# Load pre-built FA3 kernel compatible with H200try:vllm_flash_attn3 = get_kernel("kernels-community/vllm-flash-attn3")print("✅ FlashAttention-3 kernel loaded successfully")except Exception as e:print(f"⚠️ FlashAttention-3 not available: {e}")# Custom attention processor exampleclass FlashAttention3Processor:def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None):# Use FA3 kernel for attention computationreturn vllm_flash_attn3(hidden_states, encoder_hidden_states, attention_mask)# Apply FA3 processor to modelif 'vllm_flash_attn3' in locals():for name, module in pipe.transformer.named_modules():if hasattr(module, 'processor'):module.processor = FlashAttention3Processor()```### Complete Optimized Example```pythonimport spacesimport torchfrom diffusers import DiffusionPipelinefrom torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfigMODEL_ID = 'black-forest-labs/FLUX.1-dev'pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)pipe.to('cuda')@spaces.GPU(duration=1500)def compile_optimized_transformer():# Apply FP8 quantizationquantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())# Capture inputswith spaces.aoti_capture(pipe.transformer) as call:pipe("optimization test prompt")# Export and compileexported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)return spaces.aoti_compile(exported)# Compile during startupcompiled_transformer = compile_optimized_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)@spaces.GPUdef generate(prompt):return pipe(prompt).images```**Expected Performance Gains:**- Basic AoT: 1.3x-1.8x speedup- + FP8 Quantization: Additional 1.2x speedup- + FlashAttention-3: Additional attention speedup- Total potential: 2x-3x faster inference**Hardware Requirements:**- FP8 quantization requires CUDA compute capability ≥ 9.0 (H200 ✅)- FlashAttention-3 works on H200 hardware via kernels library- Dynamic shapes add flexibility for variable input sizes## Complete Gradio API Reference53 unmodified lines## Advanced ZeroGPU Optimization (Recommended)For production Spaces with heavy models, use ahead-of-time (AoT) compilation for 1.3x-1.8x speedups:### Basic AoT Compilation```pythonimport spacesimport torchfrom diffusers import DiffusionPipelineMODEL_ID = 'black-forest-labs/FLUX.1-dev'pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)pipe.to('cuda')@spaces.GPU(duration=1500) # Maximum duration allowed during startupdef compile_transformer():# 1. Capture example inputswith spaces.aoti_capture(pipe.transformer) as call:pipe("arbitrary example prompt")# 2. Export the modelexported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)# 3. Compile the exported modelreturn spaces.aoti_compile(exported)# 4. Apply compiled model to pipelinecompiled_transformer = compile_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)2 unmodified linesreturn pipe(prompt).images```### Advanced Optimizations#### FP8 Quantization (Additional 1.2x speedup on H200)```pythonfrom torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig@spaces.GPU(duration=1500)def compile_transformer_with_quantization():# Quantize before export for FP8 speedupquantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())with spaces.aoti_capture(pipe.transformer) as call:pipe("arbitrary example prompt")exported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)return spaces.aoti_compile(exported)```#### Dynamic Shapes (Variable input sizes)```pythonfrom torch.utils._pytree import tree_map@spaces.GPU(duration=1500)def compile_transformer_dynamic():with spaces.aoti_capture(pipe.transformer) as call:pipe("arbitrary example prompt")# Define dynamic dimension ranges (model-dependent)transformer_hidden_dim = torch.export.Dim('hidden', min=4096, max=8212)# Map argument names to dynamic dimensionstransformer_dynamic_shapes = {"hidden_states": {1: transformer_hidden_dim},"img_ids": {0: transformer_hidden_dim},}# Create dynamic shapes structuredynamic_shapes = tree_map(lambda v: None, call.kwargs)dynamic_shapes.update(transformer_dynamic_shapes)exported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,dynamic_shapes=dynamic_shapes,)return spaces.aoti_compile(exported)```#### Multi-Compile for Different Resolutions```python@spaces.GPU(duration=1500)def compile_multiple_resolutions():compiled_models = {}resolutions = [(512, 512), (768, 768), (1024, 1024)]for width, height in resolutions:# Capture inputs for specific resolutionwith spaces.aoti_capture(pipe.transformer) as call:pipe(f"test prompt {width}x{height}", width=width, height=height)exported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)compiled_models[f"{width}x{height}"] = spaces.aoti_compile(exported)return compiled_models# Usage with resolution dispatchcompiled_models = compile_multiple_resolutions()@spaces.GPUdef generate_with_resolution(prompt, width=1024, height=1024):resolution_key = f"{width}x{height}"if resolution_key in compiled_models:# Temporarily apply the right compiled modelspaces.aoti_apply(compiled_models[resolution_key], pipe.transformer)return pipe(prompt, width=width, height=height).images```#### FlashAttention-3 Integration```pythonfrom kernels import get_kernel# Load pre-built FA3 kernel compatible with H200try:vllm_flash_attn3 = get_kernel("kernels-community/vllm-flash-attn3")print("✅ FlashAttention-3 kernel loaded successfully")except Exception as e:print(f"⚠️ FlashAttention-3 not available: {e}")# Custom attention processor exampleclass FlashAttention3Processor:def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None):# Use FA3 kernel for attention computationreturn vllm_flash_attn3(hidden_states, encoder_hidden_states, attention_mask)# Apply FA3 processor to modelif 'vllm_flash_attn3' in locals():for name, module in pipe.transformer.named_modules():if hasattr(module, 'processor'):module.processor = FlashAttention3Processor()```### Complete Optimized Example```pythonimport spacesimport torchfrom diffusers import DiffusionPipelinefrom torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfigMODEL_ID = 'black-forest-labs/FLUX.1-dev'pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)pipe.to('cuda')@spaces.GPU(duration=1500)def compile_optimized_transformer():# Apply FP8 quantizationquantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())# Capture inputswith spaces.aoti_capture(pipe.transformer) as call:pipe("optimization test prompt")# Export and compileexported = torch.export.export(pipe.transformer,args=call.args,kwargs=call.kwargs,)return spaces.aoti_compile(exported)# Compile during startupcompiled_transformer = compile_optimized_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)@spaces.GPUdef generate(prompt):return pipe(prompt).images```**Expected Performance Gains:**- Basic AoT: 1.3x-1.8x speedup- + FP8 Quantization: Additional 1.2x speedup- + FlashAttention-3: Additional attention speedup- Total potential: 2x-3x faster inference**Hardware Requirements:**- FP8 quantization requires CUDA compute capability ≥ 9.0 (H200 ✅)- FlashAttention-3 works on H200 hardware via kernels library- Dynamic shapes add flexibility for variable input sizes## Complete Gradio API Reference
app.py+334-14