#!/usr/bin/env python3
"""Benchmark pinned MOSS audio decoding from GPU-resident codec IDs."""

import argparse
import json
import math
import platform
from pathlib import Path
import subprocess
import time

from huggingface_hub import snapshot_download
import numpy as np
import soundfile as sf
import torch
import torch.nn.functional as F
import transformers
from transformers import AutoModel


REPO_ID = "OpenMOSS-Team/MOSS-Audio-Tokenizer-v2"
REVISION = "f6e20e543b33d2c252a7ef71bdf8aa71e5ff9169"
CONFIGS = {
    "bf16": ("bf16", "bf16"),
    "fp32-w-bf16": ("fp32", "bf16"),
    "fp32": ("fp32", "fp32"),
}


def parse_args():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--snapshot", type=Path)
    parser.add_argument("--frames", type=int, nargs="+", default=[1, 4, 12, 25, 75, 150, 375])
    parser.add_argument("--warmups", type=int, default=5)
    parser.add_argument("--repeats", type=int, default=30)
    parser.add_argument("--configs", choices=CONFIGS, nargs="+", default=list(CONFIGS))
    parser.add_argument("--backend", choices=["sdpa", "flash_attention_2"], default="sdpa")
    parser.add_argument("--output", type=Path, default=Path(__file__).with_name("offline_results.json"))
    args = parser.parse_args()
    if min(args.frames) < 1 or args.warmups < 1 or args.repeats < 1:
        parser.error("frames, warmups and repeats must all be positive")
    if args.backend == "flash_attention_2" and "fp32" in args.configs:
        parser.error("flash_attention_2 requires BF16 compute in this checkpoint")
    return args


def get_snapshot(path):
    if path is not None:
        return path
    return Path(snapshot_download(
        REPO_ID,
        revision=REVISION,
        allow_patterns=["*.py", "*.json", "*.safetensors", "demo/*.wav"],
    ))


def speech_codes(model, demo_path):
    audio, sample_rate = sf.read(demo_path, always_2d=True, dtype="float32")
    waveform = torch.from_numpy(audio.T.copy()).unsqueeze(0).cuda()
    target_samples = round(waveform.shape[-1] * model.sampling_rate / sample_rate)
    waveform = F.interpolate(waveform, size=target_samples, mode="linear", align_corners=False)
    waveform = waveform.repeat(1, model.number_channels, 1)
    aligned_samples = (target_samples // model.downsample_rate) * model.downsample_rate
    encoded = model.encode(waveform[..., :aligned_samples], return_dict=True)
    assert encoded.audio_codes.shape[0] == model.quantizer.num_quantizers == 32
    assert int(encoded.audio_codes_lengths.item()) == aligned_samples // model.downsample_rate
    return encoded.audio_codes.contiguous(), {
        "demo_source_rate_hz": sample_rate,
        "demo_source_channels": audio.shape[1],
        "demo_source_samples": audio.shape[0],
        "encoded_samples_per_channel": aligned_samples,
        "encoded_frames": encoded.audio_codes.shape[-1],
    }


def benchmark_row(model, codes, name, backend, warmups, repeats):
    frames = codes.shape[-1]
    expected_samples = frames * model.downsample_rate
    torch.cuda.synchronize()
    for _ in range(warmups):
        result = model.decode(codes, return_dict=True)
    torch.cuda.synchronize()
    assert result.audio.shape == (1, model.number_channels, expected_samples)
    assert int(result.audio_lengths.item()) == expected_samples
    assert torch.isfinite(result.audio).all().item()
    output_dtype = str(result.audio.dtype)
    del result

    start_event = torch.cuda.Event(enable_timing=True)
    end_event = torch.cuda.Event(enable_timing=True)
    start_event.record()
    end_event.record()
    torch.cuda.synchronize()
    torch.cuda.reset_peak_memory_stats()
    start_allocated_mib = torch.cuda.memory_allocated() / 1024**2
    wall_ms = []
    gpu_event_ms = []
    for _ in range(repeats):
        torch.cuda.synchronize()
        start = time.perf_counter_ns()
        start_event.record()
        result = model.decode(codes, return_dict=True)
        end_event.record()
        torch.cuda.synchronize()
        wall_ms.append((time.perf_counter_ns() - start) / 1e6)
        gpu_event_ms.append(start_event.elapsed_time(end_event))
        del result

    median_ms = float(np.median(wall_ms))
    audio_seconds = expected_samples / model.sampling_rate
    weight_dtype, compute_dtype = CONFIGS[name]
    return {
        "dtype": name,
        "weight_dtype": weight_dtype,
        "compute_dtype": compute_dtype,
        "backend": backend,
        "frames": frames,
        "audio_seconds": audio_seconds,
        "samples_per_channel": expected_samples,
        "audio_dtype": output_dtype,
        "median_ms": median_ms,
        "p95_ms": float(np.percentile(wall_ms, 95)),
        "gpu_event_median_ms": float(np.median(gpu_event_ms)),
        "realtime_x": 1000 * audio_seconds / median_ms,
        "start_allocated_mib": start_allocated_mib,
        "peak_allocated_mib": torch.cuda.max_memory_allocated() / 1024**2,
        "wall_ms": wall_ms,
        "gpu_event_ms": gpu_event_ms,
    }


def write_results(path, results):
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(json.dumps(results, indent=2) + "\n")
    temporary.replace(path)


@torch.inference_mode()
def main():
    args = parse_args()
    torch.set_num_threads(4)
    torch.backends.cuda.matmul.fp32_precision = "ieee"
    torch.backends.cudnn.conv.fp32_precision = "ieee"
    snapshot = get_snapshot(args.snapshot)
    gpu = torch.cuda.get_device_properties(0)
    driver = subprocess.check_output(
        ["nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"],
        text=True,
    ).splitlines()[0]
    results = {
        "environment": {
            "repo_id": REPO_ID,
            "revision": REVISION,
            "gpu": gpu.name,
            "gpu_memory_mib": gpu.total_memory / 1024**2,
            "gpu_compute_capability": f"{gpu.major}.{gpu.minor}",
            "driver": driver,
            "torch": torch.__version__,
            "transformers": transformers.__version__,
            "cuda": torch.version.cuda,
            "cudnn": torch.backends.cudnn.version(),
            "python": platform.python_version(),
            "platform": platform.platform(),
            "tf32_matmul": torch.backends.cuda.matmul.fp32_precision,
            "tf32_cudnn_conv": torch.backends.cudnn.conv.fp32_precision,
        },
        "method": {
            "batch_size": 1,
            "codebooks": 32,
            "warmups": args.warmups,
            "repeats": args.repeats,
            "input": "Pinned model-card demo, linearly resampled from 24 to 48 kHz, mono duplicated to stereo, frame-aligned, encoded once, then code sequence repeated and cropped for longer cases.",
            "timed": "Public unchunked model.decode on GPU-resident IDs through synchronized GPU-resident waveform and output length, including Python dispatch and in-call synchronization.",
            "peak_scope": "PyTorch CUDA tensor memory with both encoder and decoder resident.",
        },
        "rows": [],
    }

    codes_source = None
    model = None
    current_weight_dtype = None
    for name in args.configs:
        weight_dtype, compute_dtype = CONFIGS[name]
        if current_weight_dtype != weight_dtype:
            del model
            torch.cuda.empty_cache()
            model = AutoModel.from_pretrained(
                snapshot, trust_remote_code=True, low_cpu_mem_usage=True, codec_weight_dtype=weight_dtype,
            ).eval().to("cuda")
            current_weight_dtype = weight_dtype
        model.set_attention_implementation(args.backend)
        model.set_compute_dtype(compute_dtype)
        if args.backend == "flash_attention_2":
            from flash_attn import flash_attn_varlen_func
            assert callable(flash_attn_varlen_func)
        results["environment"]["sampling_rate_hz"] = model.sampling_rate
        results["environment"]["samples_per_code_frame"] = model.downsample_rate
        if codes_source is None:
            codes_source, source_metadata = speech_codes(model, snapshot / "demo" / "demo_gt.wav")
            results["method"].update(source_metadata)
            results["method"]["source_encoded_with"] = name
        print(name, args.backend, model.get_codec_dtype_summary(), flush=True)
        for frames in args.frames:
            repetitions = math.ceil(frames / codes_source.shape[-1])
            codes = codes_source.repeat(1, 1, repetitions)[..., :frames].contiguous()
            row = benchmark_row(model, codes, name, args.backend, args.warmups, args.repeats)
            results["rows"].append(row)
            write_results(args.output, results)
            print(
                f"{frames:4} frames {row['audio_seconds']:5.2f}s: "
                f"{row['median_ms']:8.2f} ms median, {row['p95_ms']:8.2f} ms p95, "
                f"{row['realtime_x']:7.2f}x real time",
                flush=True,
            )


if __name__ == "__main__":
    main()
