File size: 14,821 Bytes
6b16954
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Custom Handler for FLUX.1-dev optimized for H200 GPU



This handler enables high-quality image generation using FLUX.1-dev model

on Hugging Face Dedicated Endpoints with NVIDIA H200 GPU optimizations.



H200-Specific Optimizations:

- FP8 quantization: Native FP8 support on Hopper architecture (~1.5-2.4x speedup)

- BF16 precision: Optimal for H200 Tensor Cores

- torch.compile: CUDA graph optimization (~1.3x speedup)

- VAE slicing: Memory-efficient batch processing

- Large batch size: H200's 141GB VRAM enables 16+ images in parallel



Environment Variables:

- TORCH_COMPILE_MODE: "reduce-overhead" (default), "default", "max-autotune", "false"

- FIXED_BATCH_SIZE: Batch size for CUDA graphs (default: 16 for H200)

- NUM_INFERENCE_STEPS: Default inference steps (default: 28)

- ENABLE_FP8: FP8 quantization (default: "auto" - enabled for CC >= 8.9)



GPU Requirements:

- H200 141GB: Optimal (FP8 + full quality + large batch)

- H100 80GB: Supported (FP8 enabled)

- L40S 48GB: Supported (FP8 enabled, smaller batch)

- A100 80GB: Supported (FP8 disabled - CC 8.0 doesn't support native FP8)



API Format:

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

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



Response Format:

- Single: {"image": "base64..."}

- Batch: [{"image": "base64..."}, {"image": "base64..."}, ...]



Performance (H200):

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

- Up to 16 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

# Environment configuration
TORCH_COMPILE_MODE = os.environ.get("TORCH_COMPILE_MODE", "reduce-overhead").lower()
ENABLE_TORCH_COMPILE = TORCH_COMPILE_MODE != "false"
FIXED_BATCH_SIZE = int(os.environ.get("FIXED_BATCH_SIZE", "16"))  # H200 141GB can handle batch 16
NUM_INFERENCE_STEPS = int(os.environ.get("NUM_INFERENCE_STEPS", "28"))
ENABLE_FP8 = os.environ.get("ENABLE_FP8", "auto").lower()


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

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



        Optimizations:

        - FP8 quantization (for Hopper/Ada GPUs with CC >= 8.9)

        - BF16 precision (native Tensor Core support)

        - torch.compile with reduce-overhead mode

        - VAE slicing for memory efficiency



        Args:

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

        """
        from diffusers import FluxPipeline

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

        self.device = torch.device("cuda")
        self._compiled = False
        self._fp8_enabled = False

        # Log GPU info
        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-H200] GPU: {gpu_props.name}")
        print(f"[FLUX-H200] GPU Memory: {self.gpu_memory_gb:.1f} GB")
        print(f"[FLUX-H200] Compute Capability: {gpu_props.major}.{gpu_props.minor}")
        print(f"[FLUX-H200] CUDA Version: {torch.version.cuda}")
        print(f"[FLUX-H200] PyTorch Version: {torch.__version__}")

        # H200 doesn't need offload - full GPU mode
        # For smaller GPUs, enable offload
        if self.gpu_memory_gb >= 100:
            self.use_offload = False
            print("[FLUX-H200] H200 detected - full GPU mode enabled")
        elif self.gpu_memory_gb >= 60:
            self.use_offload = False
            print("[FLUX-H200] Large GPU detected - full GPU mode enabled")
        else:
            self.use_offload = True
            print("[FLUX-H200] Smaller GPU detected - CPU offload enabled")

        # 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 = "black-forest-labs/FLUX.1-dev"

        print(f"[FLUX-H200] Loading model from: {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-H200] Using HF_TOKEN for authentication (length={len(hf_token)}, prefix={hf_token[:4]}...)")
        else:
            print("[FLUX-H200] Warning: HF_TOKEN not set, may fail for gated models")

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

        # Load pipeline with BF16
        self.pipe = FluxPipeline.from_pretrained(
            model_id,
            torch_dtype=torch.bfloat16,
            token=hf_token,
        )

        # Enable VAE slicing for memory-efficient batch processing
        self.pipe.enable_vae_slicing()
        print("[FLUX-H200] VAE slicing enabled")

        # Apply offloading or move to GPU
        if self.use_offload:
            print("[FLUX-H200] Using model CPU offload")
            self.pipe.enable_model_cpu_offload()
        else:
            print("[FLUX-H200] Loading full model to GPU")
            self.pipe.to(self.device)

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

        # Apply FP8 quantization for supported GPUs
        self._maybe_apply_fp8()

        # Apply torch.compile (after FP8 to compile quantized model)
        if ENABLE_TORCH_COMPILE:
            self._apply_torch_compile()
            self._run_warmup()
        else:
            print("[FLUX-H200] torch.compile disabled")
            self._compiled = False

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

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

    def _maybe_apply_fp8(self):
        """Apply FP8 quantization for supported GPUs (CC >= 8.9)."""
        # Check if FP8 is disabled
        if ENABLE_FP8 == "false":
            print("[FLUX-H200] FP8 disabled by environment variable")
            return

        # FP8 requires Compute Capability >= 8.9 (Ada Lovelace, Hopper)
        # H200: CC 9.0, H100: CC 9.0, L40S: CC 8.9, RTX 4090: CC 8.9
        # A100: CC 8.0 (not supported for native FP8)
        if self.compute_capability < 8.9:
            if ENABLE_FP8 == "true":
                print(f"[FLUX-H200] FP8 requested but GPU CC {self.compute_capability} < 8.9, skipping")
            else:
                print(f"[FLUX-H200] GPU CC {self.compute_capability} < 8.9, FP8 not available")
            return

        try:
            from torchao.quantization import quantize_, float8_weight_only

            print("[FLUX-H200] Applying FP8 quantization to transformer...")
            fp8_start = time.time()

            # Quantize transformer weights to FP8
            quantize_(self.pipe.transformer, float8_weight_only())

            self._fp8_enabled = True
            print(f"[FLUX-H200] FP8 quantization applied in {time.time() - fp8_start:.1f}s")

            # Log memory savings
            allocated = torch.cuda.memory_allocated() / 1e9
            print(f"[FLUX-H200] GPU memory after FP8: {allocated:.2f}GB")

        except ImportError:
            print("[FLUX-H200] torchao not installed, skipping FP8 quantization")
            print("[FLUX-H200] Install with: pip install torchao>=0.5.0")
        except Exception as e:
            print(f"[FLUX-H200] FP8 quantization failed: {e}")
            import traceback
            traceback.print_exc()

    def _apply_torch_compile(self):
        """Apply torch.compile optimization to transformer."""
        print(f"[FLUX-H200] Applying torch.compile (mode={TORCH_COMPILE_MODE})...")
        compile_start = time.time()

        try:
            compile_mode = TORCH_COMPILE_MODE if TORCH_COMPILE_MODE in ["default", "reduce-overhead", "max-autotune"] else "reduce-overhead"

            # Only compile the transformer (main computation)
            # VAE decoder runs in eager mode for stability
            self.pipe.transformer = torch.compile(
                self.pipe.transformer,
                mode=compile_mode,
                fullgraph=False,
            )
            self._compiled = True
            print(f"[FLUX-H200] torch.compile applied in {time.time() - compile_start:.1f}s")
        except Exception as e:
            print(f"[FLUX-H200] torch.compile failed: {e}")
            self._compiled = False

    def _run_warmup(self):
        """Run warmup inference to capture CUDA graphs."""
        print(f"[FLUX-H200] Running warmup at 1344x768 (batch_size={FIXED_BATCH_SIZE})...")
        warmup_start = time.time()
        try:
            with torch.inference_mode():
                warmup_prompts = ["warmup test image"] * FIXED_BATCH_SIZE
                _ = self.pipe(
                    prompt=warmup_prompts,
                    num_inference_steps=NUM_INFERENCE_STEPS,
                    width=1344,
                    height=768,
                    guidance_scale=3.5,
                )
            print(f"[FLUX-H200] Warmup completed in {time.time() - warmup_start:.1f}s")
        except Exception as e:
            print(f"[FLUX-H200] Warmup failed: {e}")
            self._compiled = False
            print("[FLUX-H200] Falling back to non-compiled mode")

    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).



        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: 1344)

                    - height: Image height (default: 768)

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



        Returns:

            Single dict or list of dicts with base64-encoded images

        """
        # 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", 1344)
        height = parameters.get("height", 768)
        seed = parameters.get("seed", -1)

        print(f"[FLUX-H200] Processing {len(prompts)} prompt(s)")
        print(f"[FLUX-H200] 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-H200] Using seed: {seed}")

        # Process in fixed-size batches
        all_images = []
        batch_size = FIXED_BATCH_SIZE if self._compiled else min(len(prompts), FIXED_BATCH_SIZE)

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

            # Pad batch for CUDA graph compatibility (only when compiled)
            if self._compiled and actual_count < FIXED_BATCH_SIZE:
                padding_prompt = batch_prompts[-1]
                batch_prompts = batch_prompts + [padding_prompt] * (FIXED_BATCH_SIZE - actual_count)
                print(f"[FLUX-H200] Batch {i // batch_size + 1}: {actual_count} real + {FIXED_BATCH_SIZE - actual_count} padding")
            else:
                print(f"[FLUX-H200] Batch {i // batch_size + 1}: {actual_count} images")

            # Generate images
            gen_start = time.time()
            with torch.inference_mode():
                result = self.pipe(
                    prompt=batch_prompts,
                    num_inference_steps=num_inference_steps,
                    width=width,
                    height=height,
                    guidance_scale=guidance_scale,
                    generator=generator,
                )
                all_images.extend(result.images[:actual_count])

            gen_time = time.time() - gen_start
            print(f"[FLUX-H200] Batch generated in {gen_time:.1f}s ({gen_time/actual_count:.1f}s per image)")

            # Clean up after each batch
            self._cleanup_memory()

        # Encode images to base64
        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}"
            })
            print(f"[FLUX-H200] Encoded image {idx + 1}/{len(all_images)}")

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