File size: 16,069 Bytes
06f4f50
d55705b
06f4f50
d55705b
 
06f4f50
d55705b
06f4f50
d55705b
 
 
 
 
06f4f50
 
d55705b
 
 
 
 
06f4f50
 
d55705b
 
 
 
06f4f50
d55705b
 
 
06f4f50
d55705b
 
 
 
 
 
 
06f4f50
 
 
d55705b
06f4f50
 
 
 
 
 
 
 
 
 
d55705b
 
 
06f4f50
d55705b
 
 
06f4f50
d55705b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06f4f50
 
 
 
 
d55705b
06f4f50
 
d55705b
 
 
 
 
06f4f50
 
 
d55705b
06f4f50
 
 
 
 
 
 
d55705b
 
 
 
 
 
 
 
 
 
 
 
 
06f4f50
d55705b
06f4f50
d55705b
 
 
 
 
06f4f50
 
 
 
 
d55705b
06f4f50
d55705b
06f4f50
 
99eb427
 
 
d55705b
 
99eb427
d55705b
99eb427
177bcba
d55705b
177bcba
 
 
 
d55705b
177bcba
d55705b
 
177bcba
d55705b
177bcba
 
d55705b
06f4f50
d55705b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06f4f50
d55705b
 
 
 
 
 
 
06f4f50
d55705b
 
 
06f4f50
d55705b
 
 
 
 
 
 
 
 
 
 
06f4f50
d55705b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06f4f50
 
 
 
d55705b
06f4f50
d55705b
06f4f50
d55705b
 
 
 
 
 
 
 
06f4f50
 
d55705b
06f4f50
d55705b
06f4f50
d55705b
 
06f4f50
 
d55705b
06f4f50
d55705b
 
 
 
06f4f50
 
 
 
 
 
 
 
 
 
d55705b
 
 
 
06f4f50
 
 
 
 
 
d55705b
 
06f4f50
 
 
d55705b
 
 
06f4f50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d55705b
 
06f4f50
 
d55705b
 
06f4f50
 
 
 
 
d55705b
06f4f50
d55705b
06f4f50
d55705b
 
06f4f50
 
 
 
d55705b
 
 
 
 
06f4f50
d55705b
 
06f4f50
 
 
 
 
 
 
d55705b
06f4f50
d55705b
 
 
 
 
 
 
06f4f50
 
d55705b
06f4f50
 
 
 
 
 
 
 
d55705b
 
06f4f50
d55705b
06f4f50
 
 
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
"""

Custom Handler for FLUX.1-dev FP8 optimized for H100 GPU



This handler provides high-performance image generation using FLUX.1-dev with

FP8 quantization via torchao, optimized for HuggingFace Dedicated Endpoints.



Based on Runpod flux-dev-fp8 handler with HuggingFace Endpoint adaptations.



H100-Specific Optimizations:

- FP8 quantization via TorchAoConfig: ~2.5x speedup vs optimum-quanto

- torch.compile: CUDA graph optimization (~20-30% additional speedup)

- Full GPU mode: H100 80GB can load full model without offload

- Auto batch sizing: Optimal batch size based on GPU VRAM (8-12 for H100)



Environment Variables:

- HF_TOKEN: HuggingFace token for gated model access (required)

- USE_FP8: Enable FP8 quantization (default: "true")

- USE_COMPILE: Enable torch.compile (default: "true")

- BATCH_SIZE: Override auto-detected batch size (default: "0" = auto)

- NUM_INFERENCE_STEPS: Default inference steps (default: "28")



GPU Requirements:

- H100 80GB: Optimal (FP8 + full GPU + batch 8-12)

- H200 141GB: Supported (batch 24-32)

- L40S 48GB: Supported (batch 4-6)

- A100 80GB: Supported (FP8 disabled - CC 8.0, batch 6-8 BF16)



API Format (HuggingFace Standard):

- Single: {"inputs": "prompt text", "parameters": {...}}

- Batch: {"inputs": ["prompt1", "prompt2", ...], "parameters": {...}}



Response Format (HuggingFace Standard):

- Single: {"image": "data:image/png;base64,..."}

- Batch: [{"image": "data:image/png;base64,..."}, ...]



Performance (H100 80GB with FP8):

- ~3-4 seconds per image (vs ~8 seconds without FP8)

- Batch 8-12 images in parallel



References:

- FLUX.1-dev: https://huggingface.co/black-forest-labs/FLUX.1-dev

- torchao FP8: https://github.com/pytorch/ao

"""

from typing import Dict, List, Any, Union
import torch
from io import BytesIO
import base64
import time
import os
import gc

# Model ID
MODEL_ID = "black-forest-labs/FLUX.1-dev"

# Environment configuration
USE_FP8 = os.environ.get("USE_FP8", "true").lower() == "true"
USE_COMPILE = os.environ.get("USE_COMPILE", "true").lower() == "true"
BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "0"))  # 0 = auto-detect
NUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "28"))


def get_optimal_batch_size(gpu_memory_gb: float, use_fp8: bool) -> int:
    """Determine optimal batch size based on GPU memory and precision."""
    if use_fp8:
        # FP8: ~12GB model + ~4GB per image
        if gpu_memory_gb >= 140:  # H200
            return 24
        elif gpu_memory_gb >= 80:  # H100/A100
            return 8
        elif gpu_memory_gb >= 48:  # L40S
            return 6
        else:
            return 4
    else:
        # BF16: ~24GB model + ~8GB per image
        if gpu_memory_gb >= 140:  # H200
            return 12
        elif gpu_memory_gb >= 80:  # H100/A100
            return 4
        elif gpu_memory_gb >= 48:  # L40S
            return 3
        else:
            return 2


class EndpointHandler:
    def __init__(self, path: str = ""):
        """

        Initialize the FLUX.1-dev pipeline with H100 optimizations.



        Optimizations:

        - FP8 quantization via TorchAoConfig (for Hopper GPUs with CC >= 8.9)

        - torch.compile with reduce-overhead mode

        - Full GPU mode (no offload for H100/H200)

        - Auto batch sizing



        Args:

            path: Path to model weights (provided by Inference Endpoints)

        """
        from diffusers import FluxPipeline, FluxTransformer2DModel, TorchAoConfig

        if not torch.cuda.is_available():
            raise RuntimeError("GPU is required for FLUX.1-dev inference")

        self.device = torch.device("cuda")
        gpu_props = torch.cuda.get_device_properties(0)
        self.gpu_memory_gb = gpu_props.total_memory / 1e9
        self.compute_capability = gpu_props.major + gpu_props.minor / 10

        print(f"[FLUX-FP8] GPU: {gpu_props.name}")
        print(f"[FLUX-FP8] GPU Memory: {self.gpu_memory_gb:.1f} GB")
        print(f"[FLUX-FP8] Compute Capability: {gpu_props.major}.{gpu_props.minor}")
        print(f"[FLUX-FP8] CUDA Version: {torch.version.cuda}")
        print(f"[FLUX-FP8] PyTorch Version: {torch.__version__}")

        # Check compute capability for FP8 (requires 8.9+)
        if USE_FP8 and self.compute_capability < 8.9:
            print(f"[FLUX-FP8] WARNING: FP8 requires CC 8.9+, got {self.compute_capability}")
            print("[FLUX-FP8] Falling back to BF16")
            self.use_fp8 = False
        else:
            self.use_fp8 = USE_FP8

        # Determine batch size
        self.batch_size = BATCH_SIZE if BATCH_SIZE > 0 else get_optimal_batch_size(
            self.gpu_memory_gb, self.use_fp8
        )
        print(f"[FLUX-FP8] Batch Size: {self.batch_size} (FP8={self.use_fp8}, compile={USE_COMPILE})")

        # Check if path contains a valid diffusers model
        if path and os.path.exists(os.path.join(path, "model_index.json")):
            model_id = path
        else:
            model_id = MODEL_ID

        print(f"[FLUX-FP8] Loading model: {model_id}")
        load_start = time.time()

        # Get HuggingFace token for gated model access
        hf_token = os.environ.get("HF_TOKEN")
        if hf_token:
            hf_token = hf_token.strip()
            print(f"[FLUX-FP8] Using HF_TOKEN for authentication (length={len(hf_token)})")
        else:
            raise RuntimeError("HF_TOKEN is required for FLUX.1-dev (gated model)")

        # Verify token has access to the gated model before loading
        if model_id == MODEL_ID:
            from huggingface_hub import HfApi
            try:
                api = HfApi(token=hf_token)
                model_info = api.model_info(model_id)
                print(f"[FLUX-FP8] Token verified: Access to {model_id} confirmed (gated={model_info.gated})")
            except Exception as e:
                print(f"[FLUX-FP8] Token verification failed: {e}")
                print("[FLUX-FP8] Please ensure:")
                print("  1. HF_TOKEN has 'read' permission")
                print(f"  2. You have accepted the license at https://huggingface.co/{model_id}")
                raise RuntimeError(f"Cannot access gated model: {e}")

        torch_dtype = torch.bfloat16

        # Load with FP8 quantization using TorchAoConfig (diffusers native)
        if self.use_fp8 and self.compute_capability >= 8.9:
            print("[FLUX-FP8] Loading transformer with TorchAoConfig FP8 quantization (float8dq_e4m3_row)...")
            try:
                # float8dq_e4m3_row: FP8 dynamic quantization with per-row scaling
                # This provides best accuracy vs speed tradeoff (~2.5x faster than optimum-quanto)
                quantization_config = TorchAoConfig("float8dq_e4m3_row")

                transformer = FluxTransformer2DModel.from_pretrained(
                    model_id,
                    subfolder="transformer",
                    quantization_config=quantization_config,
                    torch_dtype=torch_dtype,
                    token=hf_token,
                )
                print("[FLUX-FP8] Transformer loaded with FP8 quantization")

                self.pipe = FluxPipeline.from_pretrained(
                    model_id,
                    transformer=transformer,
                    torch_dtype=torch_dtype,
                    token=hf_token,
                )
                print("[FLUX-FP8] Pipeline created with quantized transformer")

            except Exception as e:
                print(f"[FLUX-FP8] FP8 quantization failed: {e}")
                print("[FLUX-FP8] Falling back to BF16...")
                self.use_fp8 = False
                self.pipe = FluxPipeline.from_pretrained(
                    model_id,
                    torch_dtype=torch_dtype,
                    token=hf_token,
                )
        else:
            # Load without quantization
            print("[FLUX-FP8] Loading pipeline without FP8 quantization (BF16)...")
            self.pipe = FluxPipeline.from_pretrained(
                model_id,
                torch_dtype=torch_dtype,
                token=hf_token,
            )

        # Enable VAE slicing for memory efficiency
        self.pipe.enable_vae_slicing()
        print("[FLUX-FP8] VAE slicing enabled")

        # Move to GPU (full GPU mode for H100/H200)
        # H100 80GB and H200 141GB can load full model without offload
        # Smaller GPUs need CPU offload (incompatible with torch.compile fullgraph)
        self.use_compile_actual = USE_COMPILE
        if self.gpu_memory_gb >= 70:  # H100 80GB, H200 141GB
            print("[FLUX-FP8] Loading full model to GPU (required for torch.compile)")
            self.pipe.to(self.device)
        elif self.gpu_memory_gb >= 40:
            print("[FLUX-FP8] Using model CPU offload (torch.compile disabled)")
            self.pipe.enable_model_cpu_offload()
            self.use_compile_actual = False  # Incompatible with CPU offload hooks
        else:
            print("[FLUX-FP8] Using sequential CPU offload (torch.compile disabled)")
            self.pipe.enable_sequential_cpu_offload()
            self.use_compile_actual = False  # Incompatible with CPU offload hooks

        print(f"[FLUX-FP8] Model loaded in {time.time() - load_start:.1f}s")

        # Apply torch.compile for additional speedup
        self._compiled = False
        if self.use_compile_actual:
            print("[FLUX-FP8] Applying torch.compile to transformer (mode=reduce-overhead)...")
            try:
                self.pipe.transformer = torch.compile(
                    self.pipe.transformer,
                    mode="reduce-overhead",
                )
                self._compiled = True
                print("[FLUX-FP8] torch.compile applied successfully")
            except Exception as e:
                print(f"[FLUX-FP8] torch.compile failed (will continue without): {e}")

        # Note: Warmup is now called separately from main.py as a background task
        # to allow /health endpoint to respond immediately after model load

        # Clean up memory
        gc.collect()
        torch.cuda.empty_cache()

        allocated = torch.cuda.memory_allocated() / 1e9
        print(f"[FLUX-FP8] Ready (compile={self._compiled}, fp8={self.use_fp8}, GPU allocated={allocated:.2f}GB)")

    def run_warmup(self):
        """

        Run warmup to trigger Triton JIT compilation during initialization.



        Uses production settings (1536x864, 28 steps) to ensure complete compilation.

        This matches Runpod implementation for consistent behavior.

        """
        print(f"[FLUX-FP8] Running warmup (1 image, 1536x864, {NUM_INFERENCE_STEPS} steps) to trigger Triton compilation...")
        warmup_start = time.time()
        try:
            with torch.no_grad():
                _ = self.pipe(
                    prompt="warmup",
                    num_inference_steps=NUM_INFERENCE_STEPS,
                    width=1536,
                    height=864,
                    guidance_scale=3.5,
                )
            print(f"[FLUX-FP8] Triton compilation completed in {time.time() - warmup_start:.1f}s")
        except Exception as e:
            print(f"[FLUX-FP8] Warmup failed: {e}")
            import traceback
            traceback.print_exc()
            print("[FLUX-FP8] Will retry compilation on first request")

    def _cleanup_memory(self):
        """Clean up GPU memory."""
        gc.collect()
        torch.cuda.empty_cache()

    def __call__(self, data: Dict[str, Any]) -> Union[Dict[str, str], List[Dict[str, str]]]:
        """

        Process image generation request(s).



        HuggingFace Standard Format:

        - Single: {"inputs": "prompt text", "parameters": {...}}

        - Batch: {"inputs": ["prompt1", "prompt2", ...], "parameters": {...}}



        Args:

            data: Request body containing:

                - inputs: Single prompt (str) or list of prompts (List[str])

                - parameters (optional):

                    - num_inference_steps: Number of denoising steps (default: 28)

                    - guidance_scale: Prompt adherence (default: 3.5)

                    - width: Image width (default: 1536)

                    - height: Image height (default: 864)

                    - seed: Random seed for reproducibility (default: -1, random)



        Returns:

            HuggingFace Standard Format:

            - Single: {"image": "data:image/png;base64,..."}

            - Batch: [{"image": "data:image/png;base64,..."}, ...]

        """
        # Extract inputs
        inputs = data.get("inputs", data)
        parameters = data.get("parameters", {})

        # Normalize inputs to list
        single_input = isinstance(inputs, str)
        if single_input:
            prompts = [inputs]
        else:
            prompts = inputs

        # Extract parameters with FLUX.1-dev defaults
        num_inference_steps = parameters.get("num_inference_steps", NUM_INFERENCE_STEPS)
        guidance_scale = parameters.get("guidance_scale", 3.5)
        width = parameters.get("width", 1536)
        height = parameters.get("height", 864)
        seed = parameters.get("seed", -1)

        print(f"[FLUX-FP8] Processing {len(prompts)} prompt(s)")
        print(f"[FLUX-FP8] Settings: steps={num_inference_steps}, guidance={guidance_scale}, size={width}x{height}")

        # Set up generator for reproducibility
        generator = None
        if seed != -1:
            generator = torch.Generator(device="cpu").manual_seed(seed)
            print(f"[FLUX-FP8] Using seed: {seed}")

        # Process in batches
        all_images = []
        batch_size = self.batch_size

        for i in range(0, len(prompts), batch_size):
            batch_prompts = prompts[i:i + batch_size]
            actual_count = len(batch_prompts)

            # Log prompt lengths for debugging
            prompt_lengths = [len(p) for p in batch_prompts]
            print(f"[FLUX-FP8] Batch {i // batch_size + 1}: {actual_count} images, prompt chars: {prompt_lengths}")

            batch_start = time.time()

            # Use inference_mode for best performance with torchao
            with torch.no_grad():
                result = self.pipe(
                    prompt=batch_prompts,
                    num_inference_steps=num_inference_steps,
                    width=width,
                    height=height,
                    guidance_scale=guidance_scale,
                    generator=generator,
                    max_sequence_length=512,  # T5 max is 512 tokens (diffusers limitation), CLIP is 77
                )
                all_images.extend(result.images)

            batch_time = time.time() - batch_start
            time_per_image = batch_time / actual_count
            print(f"[FLUX-FP8] Batch {i // batch_size + 1} completed in {batch_time:.1f}s ({time_per_image:.2f}s/image)")

            # Cleanup after each batch
            self._cleanup_memory()

        # Encode images to base64 (HuggingFace standard format)
        encoded_results = []
        for idx, image in enumerate(all_images):
            buffered = BytesIO()
            image.save(buffered, format="PNG")
            b64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
            encoded_results.append({
                "image": f"data:image/png;base64,{b64_image}"
            })
            if (idx + 1) % 10 == 0 or idx == len(all_images) - 1:
                print(f"[FLUX-FP8] Encoded image {idx + 1}/{len(all_images)}")

        # Return dict for single input, list for batch (HuggingFace standard)
        if single_input:
            return encoded_results[0]
        return encoded_results