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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

"""PyTorch model optimization utilities for exporting and compiling models.

This module provides utilities for:
- Converting SyncBatchNorm layers to standard BatchNorm
- Benchmarking model performance
- Exporting models with torch.export
- Compiling models with torch.compile
"""

import argparse
from typing import Any

import numpy as np
import torch
from sapiens.dense.models import init_model
from torch import nn


# =============================================================================
# BatchNorm Conversion Utilities
# =============================================================================


class _BatchNormXd(nn.modules.batchnorm._BatchNorm):
    """A general BatchNorm layer without input dimension check.

    Reproduced from @kapily's work:
    (https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547)

    The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc
    is `_check_input_dim` that is designed for tensor sanity checks.
    The check has been bypassed in this class for the convenience of converting
    SyncBatchNorm.
    """

    def _check_input_dim(self, input: torch.Tensor) -> None:
        return


def revert_sync_batchnorm(module: nn.Module) -> nn.Module:
    """Convert all SyncBatchNorm layers in the model to BatchNormXd layers.

    Adapted from @kapily's work:
    (https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547)

    Args:
        module: The module containing `SyncBatchNorm` layers.

    Returns:
        The converted module with `BatchNormXd` layers.
    """
    module_output = module
    module_checklist = [torch.nn.modules.batchnorm.SyncBatchNorm]

    if isinstance(module, tuple(module_checklist)):
        module_output = _BatchNormXd(
            module.num_features,
            module.eps,
            module.momentum,
            module.affine,
            module.track_running_stats,
        )
        if module.affine:
            with torch.no_grad():
                module_output.weight = module.weight
                module_output.bias = module.bias
        module_output.running_mean = module.running_mean
        module_output.running_var = module.running_var
        module_output.num_batches_tracked = module.num_batches_tracked
        module_output.training = module.training
        if hasattr(module, "qconfig"):
            module_output.qconfig = module.qconfig

    for name, child in module.named_children():
        try:
            module_output.add_module(name, revert_sync_batchnorm(child))
        except Exception:
            print(f"Failed to convert {child} from SyncBN to BN!")

    del module
    return module_output


def convert_batchnorm(module: nn.Module) -> nn.Module:
    """Convert SyncBatchNorm to BatchNorm2d and optionally SiLU to ReLU.

    Args:
        module: The module to convert.

    Returns:
        The converted module.
    """
    module_output = module

    if isinstance(module, torch.nn.SyncBatchNorm):
        module_output = torch.nn.BatchNorm2d(
            module.num_features,
            module.eps,
            module.momentum,
            module.affine,
            module.track_running_stats,
        )
        if module.affine:
            module_output.weight.data = module.weight.data.clone().detach()
            module_output.bias.data = module.bias.data.clone().detach()
            module_output.weight.requires_grad = module.weight.requires_grad
            module_output.bias.requires_grad = module.bias.requires_grad
        module_output.running_mean = module.running_mean
        module_output.running_var = module.running_var
        module_output.num_batches_tracked = module.num_batches_tracked

    if isinstance(module, torch.nn.SiLU):
        module_output = torch.nn.ReLU(inplace=True)

    for name, child in module.named_children():
        module_output.add_module(name, convert_batchnorm(child))

    del module
    return module_output


# =============================================================================
# Benchmarking Utilities
# =============================================================================


def benchmark_model(
    model: nn.Module,
    inputs: dict[str, Any],
    model_name: str = "",
    num_warmup: int = 3,
    num_iterations: int = 10,
) -> float:
    """Benchmark model inference time.

    Args:
        model: The model to benchmark.
        inputs: Dictionary containing 'imgs' tensor.
        model_name: Name for logging purposes.
        num_warmup: Number of warmup iterations (not counted).
        num_iterations: Number of timed iterations.

    Returns:
        Mean inference time per sample in milliseconds.
    """
    imgs = (
        inputs["imgs"][0, ...].unsqueeze(0)
        if model_name.lower() == "original"
        else inputs["imgs"]
    )

    if not torch.cuda.is_available():
        raise RuntimeError("CUDA is required for benchmarking")

    start_event = torch.cuda.Event(enable_timing=True)
    end_event = torch.cuda.Event(enable_timing=True)
    times = []

    stream = torch.cuda.Stream()
    stream.wait_stream(torch.cuda.current_stream())

    with torch.cuda.stream(stream), torch.no_grad():
        # Warmup
        for _ in range(num_warmup):
            model(imgs)
            torch.cuda.synchronize()

        # Timed iterations
        for _ in range(num_iterations):
            torch.cuda.synchronize()
            start_event.record()
            model(imgs)
            end_event.record()
            torch.cuda.synchronize()
            times.append(start_event.elapsed_time(end_event))

    torch.cuda.current_stream().wait_stream(stream)

    mean_time = np.mean(times) / imgs.shape[0]
    print(f"Benchmark results for '{model_name}':")
    print(f"  Average time per sample: {mean_time:.2f} ms")
    print(f"  Total time ({num_iterations} iterations): {sum(times):.2f} ms")
    print(f"  Individual times: {[f'{t:.2f}' for t in times]}")

    return mean_time


# =============================================================================
# Input Generation
# =============================================================================


def create_demo_inputs(input_shape: tuple[int, int, int, int]) -> dict[str, Any]:
    """Create demo inputs for model testing and export.

    Args:
        input_shape: Tuple of (N, C, H, W) for input dimensions.

    Returns:
        Dictionary with 'imgs' tensor and 'img_metas' list.
    """
    n, c, h, w = input_shape
    rng = np.random.RandomState(0)
    imgs = rng.rand(*input_shape)

    img_metas = [
        {
            "img_shape": (h, w, c),
            "ori_shape": (h, w, c),
            "pad_shape": (h, w, c),
            "filename": "<demo>.png",
            "scale_factor": 1.0,
            "flip": False,
        }
        for _ in range(n)
    ]

    return {
        "imgs": torch.FloatTensor(imgs),
        "img_metas": img_metas,
    }


# =============================================================================
# Model Export and Compilation
# =============================================================================


class _ToDeviceTransformer(torch.fx.Transformer):
    """FX Transformer to move operations to a specific device."""

    def __init__(self, module: nn.Module, device: str):
        super().__init__(module)
        self.target_device = torch.device(device)

    def call_function(self, target, args, kwargs):
        if "device" not in kwargs:
            return super().call_function(target, args, kwargs)

        kwargs = dict(kwargs)
        kwargs["device"] = self.target_device
        return super().call_function(target, args, kwargs)


def compile_and_export_model(
    model: nn.Module,
    inputs: dict[str, Any],
    output_file: str = "compiled_model.pt",
    max_batch_size: int = 32,
    dtype: torch.dtype = torch.bfloat16,
) -> None:
    """Export model using torch.export and optionally compile with torch.compile.

    Args:
        model: The model to export.
        inputs: Demo inputs for tracing.
        output_file: Path to save the exported model.
        max_batch_size: Maximum batch size for dynamic shapes.
        dtype: Data type for the model.
    """
    inputs["imgs"] = inputs["imgs"].to(dtype)
    imgs = inputs["imgs"]
    model.eval()

    # Define dynamic shapes
    dynamic_batch = torch.export.Dim("batch", min=1, max=max_batch_size)
    dynamic_h = torch.export.Dim("h", min=1024, max=2048)
    dynamic_w = torch.export.Dim("w", min=768, max=1536)
    dynamic_shapes = {"inputs": {0: dynamic_batch, 2: dynamic_h, 3: dynamic_w}}

    # Export model
    exported_model = torch.export.export(
        model,
        args=(imgs,),
        kwargs={},
        dynamic_shapes=dynamic_shapes,
    )
    torch.export.save(exported_model, output_file)
    print(f"Model exported to: {output_file}")

    if not torch.cuda.is_available():
        return
    # Compile and benchmark
    device = "cuda:0"
    model = torch.export.load(output_file).module().to(device)
    model = _ToDeviceTransformer(model, device).transform()
    imgs = imgs.to(device)
    inputs["imgs"] = inputs["imgs"].to(device)

    _compile_and_benchmark(model, imgs, inputs)


def _compile_and_benchmark(
    model: nn.Module,
    imgs: torch.Tensor,
    inputs: dict[str, Any],
) -> None:
    """Compile model and benchmark different compilation modes.

    Args:
        model: Model to compile.
        imgs: Input images tensor.
        inputs: Full inputs dictionary for benchmarking.
    """
    modes = {"default": "default"}
    best_mode = None
    min_mean = float("inf")

    for mode_name, mode in modes.items():
        print(f"Compiling model with '{mode_name}' mode...")

        compiled_model = torch.compile(model, mode=mode)

        # Warmup
        stream = torch.cuda.Stream()
        stream.wait_stream(torch.cuda.current_stream())
        with torch.cuda.stream(stream), torch.no_grad():
            for _ in range(3):
                compiled_model(imgs)
                torch.cuda.synchronize()
        torch.cuda.current_stream().wait_stream(stream)

        mean_time = benchmark_model(compiled_model, inputs, model_name=mode_name)
        if mean_time < min_mean:
            min_mean = mean_time
            best_mode = mode_name

    print(f"Best compilation mode: {best_mode}")


# =============================================================================
# CLI Interface
# =============================================================================


def parse_args() -> argparse.Namespace:
    """Parse command line arguments.

    Returns:
        Parsed arguments.
    """
    parser = argparse.ArgumentParser(
        description="Export and optimize a model for deployment"
    )
    parser.add_argument("config", help="Model config file path")
    parser.add_argument("--checkpoint", help="Checkpoint file path")
    parser.add_argument(
        "--shape",
        type=int,
        nargs="+",
        default=[1024, 768],
        help="Input image size as (height, width)",
    )
    parser.add_argument(
        "--output-file",
        "--output-dir",
        type=str,
        required=True,
        help="Output file path for exported model",
    )
    parser.add_argument(
        "--max-batch-size",
        type=int,
        default=32,
        help="Maximum batch size for dynamic export",
    )
    parser.add_argument(
        "--fp16",
        action="store_true",
        help="Use fp16 instead of bfloat16",
    )

    return parser.parse_args()


def main() -> None:
    """Main entry point for model optimization CLI."""
    args = parse_args()

    # Determine input shape
    if len(args.shape) == 1:
        input_shape = (16, 3, args.shape[0], args.shape[0])
    elif len(args.shape) == 2:
        input_shape = (16, 3, args.shape[0], args.shape[1])
    else:
        raise ValueError("Shape must be 1 or 2 integers (height, width)")

    # Clamp batch size
    max_batch_size = args.max_batch_size
    input_shape = (max(1, min(input_shape[0], max_batch_size)), *input_shape[1:])

    # Initialize model
    model = init_model(args.config, args.checkpoint, device="cpu")
    model.eval()
    model = revert_sync_batchnorm(model)

    # Create demo inputs
    demo_inputs = create_demo_inputs(input_shape)

    # Set dtype
    dtype = torch.half if args.fp16 else torch.bfloat16
    model.to(dtype)
    demo_inputs["imgs"] = demo_inputs["imgs"].to(dtype)

    # Export and compile
    compile_and_export_model(
        model,
        demo_inputs,
        output_file=args.output_file,
        max_batch_size=max_batch_size,
        dtype=dtype,
    )


if __name__ == "__main__":
    main()