#!/usr/bin/env python3

"""Generates a matrix to be utilized through github actions

Will output a condensed version of the matrix if on a pull request that only
includes the latest version of python we support built on three different
architectures:
    * CPU
    * Latest CUDA
    * Latest ROCM
    * Latest XPU
"""

from __future__ import annotations

import ast
import json
import os
import re
from pathlib import Path
from typing import NamedTuple


SCRIPT_DIR = Path(__file__).absolute().parent
REPO_ROOT = SCRIPT_DIR.parent.parent


CUDA_ARCHES = ["13.2", "13.4", "13.5"]
CUDA_WINDOWS_ARCHES = ["13.2", "13.4", "13.5"]
CUDA_STABLE = "13.2"
# Only consumed by generate_docker_release_matrix.py, whose Dockerfile installs
# an already-published torch nightly. A CUDA version belongs here only once its
# wheels are on the download.pytorch.org index.
CUDA_ARCHES_FULL_VERSION = {
    "13.2": "13.2.2",
    "13.4": "13.4.3",
    "13.5": "13.5.0",
}
# CUDA versions that can only produce the runtime docker image. The devel image
# apt-installs cuda-toolkit-<major>-<minor> from NVIDIA's repo.
# Drop an entry once its toolkit ships in the apt repo.
CUDA_ARCHES_RUNTIME_IMAGE_ONLY = []
CUDA_ARCHES_CUDNN_VERSION = {
    "13.2": "9",
    "13.4": "9",
    "13.5": "9",
}

ROCM_ARCHES = ["10.1", "10.2"]


class RocmPreviewLane(NamedTuple):
    arch: str
    channel: str


# Preview is a stable channel, not a version; keep its external names together.
ROCM_PREVIEW = RocmPreviewLane(arch="preview", channel="rocm-preview")
ROCM_PREVIEW_ARCHES = [ROCM_PREVIEW.arch]
# Matches PYTORCH_ROCM_ARCH in .ci/docker/manywheel/build.sh, except that the
# preview build also adds gfx1250-strict, which has no device-* extra (its
# libraries ship in device-gfx1250). Preview's device-all also pulls targets
# torch is not built for, e.g. gfx900.
ROCM_PREVIEW_DEVICES = "gfx908;gfx90a;gfx942;gfx950;gfx1030;gfx1100;gfx1101;gfx1102;gfx1103;gfx1200;gfx1201;gfx1150;gfx1151;gfx1250"

XPU_ARCHES = ["xpu"]

CPU_AARCH64_ARCH = ["cpu-aarch64"]

CPU_S390X_ARCH = ["cpu-s390x"]

CUDA_AARCH64_ARCHES = [
    "13.2-aarch64",
    "13.4-aarch64",
    "13.5-aarch64",
]

# For CUDA, every wheel of a version (Linux x86_64 and aarch64, Windows) declares
# both the "linux" and the "windows" list; the markers keep each platform to its
# own packages. uv, Poetry and PDM apply one wheel's dependencies to every wheel
# of that version, so per-platform lists break their lock files (#207773).
PYTORCH_EXTRA_INSTALL_REQUIREMENTS = {
    "13.2": {
        "linux": (
            "cuda-toolkit[nvrtc,cudart,cupti,cufft,cusparse,cufile,nvjitlink,nvtx]==13.2.2; platform_system == 'Linux' | "
            "nvidia-cublas==13.4.3.11; platform_system == 'Linux' | "
            "nvidia-cusolver==12.2.0.11; platform_system == 'Linux' | "
            "cuda-bindings>=13.0.3,<14; platform_system == 'Linux' and python_version < '3.15' | "
            "nvidia-cudnn-cu13==9.28.1.4; platform_system == 'Linux' | "
            "nvidia-cusparselt-cu13==0.8.1.post1; platform_system == 'Linux' | "
            "nvidia-nccl-cu13==2.32.3; platform_system == 'Linux' | "
            "nvidia-nvshmem-cu13==3.8.0; platform_system == 'Linux'"
        ),
        "windows": (
            "cuda-toolkit[nvrtc,cudart,cupti,cufft,curand,cusolver,cusparse,cublas,cufile,nvjitlink,nvtx]==13.2.2; platform_system == 'Windows' and platform_machine == 'AMD64' | "
            "cuda-pathfinder>=1.8.5; platform_system == 'Windows' and platform_machine == 'AMD64' | "
            "nvidia-cudnn-cu13==9.28.1.4; platform_system == 'Windows' and platform_machine == 'AMD64' | "
            "nvidia-cusparselt-cu13==0.8.1.post1; platform_system == 'Windows' and platform_machine == 'AMD64'"
        ),
    },
    "13.4": {
        "linux": (
            "cuda-toolkit[nvrtc,cudart,cupti,cufft,cusparse,cufile,nvjitlink,nvtx]==13.4.3; platform_system == 'Linux' | "
            "nvidia-cublas>=13.7.0.27,<=13.8.1.7; platform_system == 'Linux' | "
            "nvidia-cusolver==12.3.2.15; platform_system == 'Linux' | "
            "cuda-bindings>=13.0.3,<14; platform_system == 'Linux' and python_version < '3.15' | "
            "cupti-python==13.4.0; platform_system == 'Linux' and python_version < '3.15' | "
            "nvidia-cudnn-cu13==9.28.1.4; platform_system == 'Linux' | "
            "nvidia-cusparselt-cu13==0.8.1.post1; platform_system == 'Linux' | "
            "nvidia-nccl-cu13==2.32.3; platform_system == 'Linux' | "
            "nvidia-nvshmem-cu13==3.8.0; platform_system == 'Linux'"
        ),
        "windows": (
            "cuda-toolkit[nvrtc,cudart,cupti,cufft,curand,cusolver,cusparse,cublas,cufile,nvjitlink,nvtx]==13.4.3; platform_system == 'Windows' and platform_machine == 'AMD64' | "
            "cuda-pathfinder>=1.8.5; platform_system == 'Windows' and platform_machine == 'AMD64' | "
            "nvidia-cudnn-cu13==9.28.1.4; platform_system == 'Windows' and platform_machine == 'AMD64' | "
            "nvidia-cusparselt-cu13==0.8.1.post1; platform_system == 'Windows' and platform_machine == 'AMD64'"
        ),
    },
    "13.5": {
        "linux": (
            "cuda-toolkit[nvrtc,cudart,cupti,cufft,cusolver,cusparse,cublas,cufile,nvjitlink,nvtx]==13.5.0; platform_system == 'Linux' | "
            "cuda-bindings>=13.0.3,<14; platform_system == 'Linux' and python_version < '3.15' | "
            "cupti-python==13.5.0; platform_system == 'Linux' and python_version < '3.15' | "
            "nvidia-cudnn-cu13==9.28.1.4; platform_system == 'Linux' | "
            "nvidia-cusparselt-cu13==0.8.1.post1; platform_system == 'Linux' | "
            "nvidia-nccl-cu13==2.32.3; platform_system == 'Linux' | "
            "nvidia-nvshmem-cu13==3.7.2; platform_system == 'Linux'"
        ),
        "windows": (
            "cuda-toolkit[nvrtc,cudart,cupti,cufft,curand,cusolver,cusparse,cublas,cufile,nvjitlink,nvtx]==13.5.0; platform_system == 'Windows' and platform_machine == 'AMD64' | "
            "cuda-pathfinder>=1.8.5; platform_system == 'Windows' and platform_machine == 'AMD64' | "
            "nvidia-cudnn-cu13==9.28.1.4; platform_system == 'Windows' and platform_machine == 'AMD64' | "
            "nvidia-cusparselt-cu13==0.8.1.post1; platform_system == 'Windows' and platform_machine == 'AMD64'"
        ),
    },
    # dependency on latest patch version for (major, minor)
    "10.1": ("rocm[libraries,device-all]==10.1.*"),
    "10.2": ("rocm[libraries,device-all]==10.2.*"),
    # binary_populate_env.sh appends ==<pin> at build time, so pin bumps
    # don't change generated workflows.
    ROCM_PREVIEW.arch: (
        "rocm[libraries,"
        + ",".join(f"device-{gfx}" for gfx in ROCM_PREVIEW_DEVICES.split(";"))
        + "]"
    ),
    # The XPU runtime is on oneAPI 2026.1. The intel-openmp<2026.2.0 caps in
    # .ci/docker/requirements-ci.txt and .ci/wheel/windows/build_install_deps.py (XPU
    # builds only) exist because of this pin (#201218); lift them when XPU moves to 2026.2.
    "xpu": (
        "intel-cmplr-lib-rt==2026.2.0 | "
        "intel-cmplr-lib-ur==2026.2.0 | "
        "intel-cmplr-lic-rt==2026.2.0 | "
        "intel-sycl-rt==2026.2.0 | "
        "oneccl-devel==2022.2.1; platform_system == 'Linux' and platform_machine == 'x86_64' | "
        "oneccl==2022.2.1; platform_system == 'Linux' and platform_machine == 'x86_64' | "
        "modified-libfabric==2.6.13; platform_system == 'Linux' and platform_machine == 'x86_64' | "
        # onemkl-license 2026.2.0 ships a win_amd64 wheel only; the Linux mkl
        # wheel dropped its onemkl-license requirement in 2026.2.
        "onemkl-license==2026.2.0; platform_system == 'Windows' and platform_machine == 'AMD64' | "
        "onemkl-sycl-blas==2026.2.0 | "
        "onemkl-sycl-dft==2026.2.0 | "
        "onemkl-sycl-lapack==2026.2.0 | "
        "onemkl-sycl-rng==2026.2.0 | "
        "onemkl-sycl-sparse==2026.2.0 | "
        "dpcpp-cpp-rt==2026.2.0 | "
        "intel-opencl-rt==2026.2.0 | "
        "mkl==2026.2.0 | "
        "intel-openmp==2026.2.0 | "
        "tbb==2023.2.0 | "
        "tcmlib==1.6.0 | "
        "umf==1.2.0 | "
        "intel-pti==1.2.1 | "
        "pyzes==0.1.3; platform_system == 'Linux' and platform_machine == 'x86_64'"
    ),
}


# Used by tools/nightly.py
PYTORCH_NIGHTLY_PIP_INDEX_URL = "https://download.pytorch.org/whl/nightly"
NIGHTLY_SOURCE_MATRIX = {
    "cpu": dict(
        name="cpu",
        index_url=f"{PYTORCH_NIGHTLY_PIP_INDEX_URL}/cpu",
        supported_platforms=["Linux", "macOS", "Windows"],
        accelerator="cpu",
    )
}
CUDA_NIGHTLY_SOURCE_MATRIX = {
    f"cuda-{major}.{minor}": dict(
        name=f"cuda-{major}.{minor}",
        index_url=f"{PYTORCH_NIGHTLY_PIP_INDEX_URL}/cu{major}{minor}",
        supported_platforms=(
            ["Linux", "Windows"]
            if f"{major}.{minor}" in CUDA_WINDOWS_ARCHES
            else ["Linux"]
        ),
        accelerator="cuda",
    )
    for major, minor in (map(int, version.split(".")) for version in CUDA_ARCHES)
}
ROCM_NIGHTLY_SOURCE_MATRIX = {
    f"rocm-{major}.{minor}": dict(
        name=f"rocm-{major}.{minor}",
        index_url=f"{PYTORCH_NIGHTLY_PIP_INDEX_URL}/rocm{major}.{minor}",
        supported_platforms=["Linux"],
        accelerator="rocm",
    )
    for major, minor in (map(int, version.split(".")) for version in ROCM_ARCHES)
}
ROCM_NIGHTLY_SOURCE_MATRIX[ROCM_PREVIEW.channel] = dict(
    name=ROCM_PREVIEW.channel,
    index_url=f"{PYTORCH_NIGHTLY_PIP_INDEX_URL}/{ROCM_PREVIEW.channel}",
    supported_platforms=["Linux"],
    accelerator="rocm",
)
XPU_NIGHTLY_SOURCE_MATRIX = {
    "xpu": dict(
        name="xpu",
        index_url=f"{PYTORCH_NIGHTLY_PIP_INDEX_URL}/xpu",
        supported_platforms=["Linux"],
        accelerator="xpu",
    )
}
NIGHTLY_SOURCE_MATRIX.update(CUDA_NIGHTLY_SOURCE_MATRIX)
NIGHTLY_SOURCE_MATRIX.update(ROCM_NIGHTLY_SOURCE_MATRIX)
NIGHTLY_SOURCE_MATRIX.update(XPU_NIGHTLY_SOURCE_MATRIX)


def get_nccl_wheel_version(arch_version: str) -> str:
    requirements = map(
        str.strip,
        re.split("[;|]", PYTORCH_EXTRA_INSTALL_REQUIREMENTS[arch_version]["linux"]),
    )
    return next(x for x in requirements if x.startswith("nvidia-nccl")).split("==")[1]


def read_nccl_pin(arch_version: str) -> str:
    import sys

    sys.path.append(str(REPO_ROOT / "tools"))
    # Single source of truth for NCCL version
    from optional_submodules import read_nccl_pin

    return read_nccl_pin(arch_version)


def validate_nccl_dep_consistency(arch_version: str) -> None:
    nccl_release_tag = read_nccl_pin(arch_version)
    wheel_ver = get_nccl_wheel_version(arch_version)
    if not nccl_release_tag.startswith(f"v{wheel_ver}"):
        raise RuntimeError(
            f"{arch_version} NCCL release tag version {nccl_release_tag} "
            f"does not correspond to wheel version {wheel_ver}"
        )


def _parse_linux_cudnn_versions() -> dict[str, str]:
    """Return {cuda_short_version: cudnn_version} from install_cuda.sh."""
    text = (REPO_ROOT / ".ci" / "docker" / "common" / "install_cuda.sh").read_text()
    results: dict[str, str] = {}
    func_re = re.compile(r"^function install_(\d+)\s*\{")
    cudnn_re = re.compile(r"^\s*CUDNN_VERSION=(\S+)")
    current_func: str | None = None
    for line in text.splitlines():
        m = func_re.match(line)
        if m:
            digits = m.group(1)
            current_func = digits[:-1] + "." + digits[-1]
            continue
        if current_func is not None:
            m = cudnn_re.match(line)
            if m:
                results[current_func] = m.group(1)
                current_func = None
    return results


def _parse_windows_cudnn_versions() -> dict[str, str]:
    """Return {cuda_short_version: cudnn_version} from cuda_install.bat."""
    text = (
        REPO_ROOT / ".ci" / "pytorch" / "windows" / "internal" / "cuda_install.bat"
    ).read_text()
    results: dict[str, str] = {}
    label_re = re.compile(r"^:cuda(\d+)\s*$")
    cudnn_re = re.compile(
        r"^set CUDNN_FOLDER=cudnn-windows-x86_64-([0-9.]+)_cuda\d+-archive"
    )
    current_label: str | None = None
    for line in text.splitlines():
        m = label_re.match(line)
        if m:
            digits = m.group(1)
            current_label = digits[:-1] + "." + digits[-1]
            continue
        if current_label is not None:
            m = cudnn_re.match(line)
            if m:
                results[current_label] = m.group(1)
                current_label = None
    return results


def validate_cudnn_version_consistency(arch_version: str) -> None:
    linux_versions = _parse_linux_cudnn_versions()
    windows_versions = _parse_windows_cudnn_versions()
    linux_ver = linux_versions.get(arch_version)
    windows_ver = windows_versions.get(arch_version)
    if linux_ver is None or windows_ver is None:
        return
    if linux_ver != windows_ver:
        raise RuntimeError(
            f"cuDNN version mismatch for CUDA {arch_version}: "
            f"Linux has {linux_ver} (.ci/docker/common/install_cuda.sh) "
            f"but Windows has {windows_ver} (.ci/pytorch/windows/internal/cuda_install.bat)"
        )


_BUILD_ENV_SETUP = REPO_ROOT / ".ci" / "wheel" / "linux" / "build_env_setup.py"
_RUNTIME_CUDA_INIT = REPO_ROOT / "torch" / "cuda" / "__init__.py"


def _read_dict_constant(path: Path, name: str) -> dict[str, dict[str, set[int]]]:
    """Parse a top-level annotated `name: dict[...] = {...}` literal from a Python file."""
    tree = ast.parse(path.read_text())
    for node in ast.walk(tree):
        if (
            isinstance(node, ast.AnnAssign)
            and isinstance(node.target, ast.Name)
            and node.target.id == name
            and node.value is not None
        ):
            return ast.literal_eval(node.value)
    raise RuntimeError(f"{name} not found in {path}")


def validate_runtime_release_table_consistency() -> None:
    """Ensure torch/cuda/__init__.py's recommendation table matches the build matrix.

    PYTORCH_RELEASES_CODE_CC (runtime) and TORCH_CUDA_ARCH_LIST_TABLE (build)
    use the same {cuda_version: {host_arch: set[cc_int]}} shape, so a direct
    dict equality check catches any drift between them.
    """
    runtime = _read_dict_constant(_RUNTIME_CUDA_INIT, "PYTORCH_RELEASES_CODE_CC")
    build = _read_dict_constant(_BUILD_ENV_SETUP, "TORCH_CUDA_ARCH_LIST_TABLE")
    if runtime != build:
        raise RuntimeError(
            "PYTORCH_RELEASES_CODE_CC in torch/cuda/__init__.py is out of sync "
            "with TORCH_CUDA_ARCH_LIST_TABLE in .ci/wheel/linux/build_env_setup.py.\n"
            f"runtime: {runtime}\nbuild:   {build}"
        )


def arch_type(arch_version: str) -> str:
    if arch_version in CUDA_ARCHES:
        return "cuda"
    elif arch_version in ROCM_ARCHES + ROCM_PREVIEW_ARCHES:
        return "rocm"
    elif arch_version in XPU_ARCHES:
        return "xpu"
    elif arch_version in CPU_AARCH64_ARCH:
        return "cpu-aarch64"
    elif arch_version in CPU_S390X_ARCH:
        return "cpu-s390x"
    elif arch_version in CUDA_AARCH64_ARCHES:
        return "cuda-aarch64"
    else:  # arch_version should always be "cpu" in this case
        return "cpu"


DEFAULT_TAG = os.getenv("RELEASE_VERSION_TAG", "main")

WHEEL_CONTAINER_IMAGES = {
    **{gpu_arch: f"manylinux2_28-builder:cuda{gpu_arch}" for gpu_arch in CUDA_ARCHES},
    **{
        gpu_arch: f"manylinuxaarch64-builder:cuda{gpu_arch.replace('-aarch64', '')}"
        for gpu_arch in CUDA_AARCH64_ARCHES
    },
    **{gpu_arch: f"manylinux2_28-builder:rocm{gpu_arch}" for gpu_arch in ROCM_ARCHES},
    ROCM_PREVIEW.arch: f"manylinux2_28-builder:{ROCM_PREVIEW.channel}",
    "xpu": "manylinux2_28-builder:xpu",
    "cpu": "manylinux2_28-builder:cpu",
    "cpu-aarch64": "manylinux2_28_aarch64-builder:cpu-aarch64",
    "cpu-s390x": "manylinuxs390x-builder:cpu-s390x",
}

RELEASE = "release"
DEBUG = "debug"

FULL_PYTHON_VERSIONS = [
    "3.11",
    "3.12",
    "3.13",
    "3.14",
    "3.14t",
    "3.15",
    "3.15t",
]
# Preview tracks a moving SDK; skip the oldest Python to keep the lane small.
ROCM_PREVIEW_PYTHON_VERSIONS = FULL_PYTHON_VERSIONS[
    FULL_PYTHON_VERSIONS.index("3.12") :
]


def translate_desired_cuda(gpu_arch_type: str, gpu_arch_version: str) -> str:
    return {
        "cpu": "cpu",
        "cpu-aarch64": "cpu",
        "cpu-s390x": "cpu",
        "cuda": f"cu{gpu_arch_version.replace('.', '')}",
        "cuda-aarch64": f"cu{gpu_arch_version.replace('-aarch64', '').replace('.', '')}",
        "rocm": f"rocm{gpu_arch_version}",
        "xpu": "xpu",
    }.get(gpu_arch_type, gpu_arch_version)


def list_without(in_list: list[str], without: list[str]) -> list[str]:
    return [item for item in in_list if item not in without]


def generate_libtorch_matrix(
    os: str,
    release_type: str,
    arches: list[str] | None = None,
    libtorch_variants: list[str] | None = None,
) -> list[dict[str, str]]:
    if arches is None:
        arches = ["cpu"]
        if os == "windows":
            arches += CUDA_WINDOWS_ARCHES
    if libtorch_variants is None:
        libtorch_variants = [
            "shared-with-deps",
            "shared-without-deps",
            "static-with-deps",
            "static-without-deps",
        ]

    ret: list[dict[str, str]] = []
    for arch_version in arches:
        for libtorch_variant in libtorch_variants:
            gpu_arch_type = arch_type(arch_version)
            gpu_arch_version = "" if arch_version == "cpu" else arch_version
            ret.append(
                {
                    "gpu_arch_type": gpu_arch_type,
                    "gpu_arch_version": gpu_arch_version,
                    "desired_cuda": translate_desired_cuda(
                        gpu_arch_type, gpu_arch_version
                    ),
                    "libtorch_config": release_type,
                    "libtorch_variant": libtorch_variant,
                    "container_image": "",
                    "container_image_tag_prefix": "",
                    "package_type": "libtorch",
                    "build_name": f"libtorch-{gpu_arch_type}{gpu_arch_version}-{libtorch_variant}-{release_type}".replace(
                        ".", "_"
                    ),
                }
            )
    return ret


def generate_wheels_matrix(
    os: str,
    arches: list[str] | None = None,
    python_versions: list[str] | None = None,
) -> list[dict[str, str]]:
    package_type = "wheel"
    if os == "linux" or os == "linux-aarch64" or os == "linux-s390x":
        # NOTE: We only build manywheel packages for x86_64 and aarch64 and s390x linux
        package_type = "manywheel"

    if python_versions is None:
        python_versions = FULL_PYTHON_VERSIONS

    if arches is None:
        # Define default compute archivectures
        arches = ["cpu"]
        if os == "linux":
            arches += CUDA_ARCHES + ROCM_ARCHES + ROCM_PREVIEW_ARCHES + XPU_ARCHES
        elif os == "windows":
            arches += CUDA_WINDOWS_ARCHES + XPU_ARCHES
        elif os == "linux-aarch64":
            # Separate new if as the CPU type is different and
            # uses different build/test scripts
            arches = CPU_AARCH64_ARCH + CUDA_AARCH64_ARCHES
        elif os == "linux-s390x":
            # Only want the one arch as the CPU type is different and
            # uses different build/test scripts
            arches = ["cpu-s390x"]

    ret: list[dict[str, str]] = []
    for python_version in python_versions:
        for arch_version in arches:
            gpu_arch_type = arch_type(arch_version)
            gpu_arch_version = (
                ""
                if arch_version == "cpu"
                or arch_version == "cpu-aarch64"
                or arch_version == "cpu-s390x"
                or arch_version == "xpu"
                else arch_version
            )

            if (
                arch_version == ROCM_PREVIEW.arch
                and python_version not in ROCM_PREVIEW_PYTHON_VERSIONS
            ):
                continue

            # TODO: Enable Python 3.15 on linux-s390x.
            if os not in [
                "linux",
                "linux-aarch64",
                "windows",
                "windows-arm64",
                "macos-arm64",
            ] and (python_version == "3.15" or python_version == "3.15t"):
                continue

            # CUDA wheels require PYTORCH_EXTRA_INSTALL_REQUIREMENTS
            # to install CUDA runtime libraries from PyPI.

            if (
                arch_version in CUDA_ARCHES
                and os in ("linux", "windows")
                or arch_version in CUDA_AARCH64_ARCHES
            ):
                desired_cuda = translate_desired_cuda(gpu_arch_type, gpu_arch_version)
                cuda_version = (
                    f"{desired_cuda[2:4]}.{desired_cuda[4:]}"
                    if os == "linux-aarch64"
                    else arch_version
                )
                cuda_reqs = PYTORCH_EXTRA_INSTALL_REQUIREMENTS[cuda_version]
                ret.append(
                    {
                        "python_version": python_version,
                        "gpu_arch_type": gpu_arch_type,
                        "gpu_arch_version": gpu_arch_version,
                        "desired_cuda": desired_cuda,
                        "container_image": WHEEL_CONTAINER_IMAGES[arch_version].split(
                            ":"
                        )[0],
                        "container_image_tag_prefix": WHEEL_CONTAINER_IMAGES[
                            arch_version
                        ].split(":")[1],
                        "package_type": package_type,
                        "pytorch_extra_install_requirements": f"{cuda_reqs['linux']} | {cuda_reqs['windows']}",
                        "build_name": (
                            f"{package_type}-py{python_version}-{gpu_arch_type}"
                            f"{'-' if 'aarch64' in gpu_arch_type else ''}{gpu_arch_version.replace('-aarch64', '')}".replace(
                                ".", "_"
                            )
                        ),  # include special case for aarch64 build, remove the -aarch64 postfix
                    }
                )
            else:
                ret.append(
                    {
                        "python_version": python_version,
                        "gpu_arch_type": gpu_arch_type,
                        "gpu_arch_version": gpu_arch_version,
                        "desired_cuda": translate_desired_cuda(
                            gpu_arch_type, gpu_arch_version
                        ),
                        "container_image": WHEEL_CONTAINER_IMAGES[arch_version].split(
                            ":"
                        )[0],
                        "container_image_tag_prefix": WHEEL_CONTAINER_IMAGES[
                            arch_version
                        ].split(":")[1],
                        "package_type": package_type,
                        "build_name": f"{package_type}-py{python_version}-{gpu_arch_type}{gpu_arch_version}".replace(
                            ".", "_"
                        ),
                        "pytorch_extra_install_requirements": (
                            PYTORCH_EXTRA_INSTALL_REQUIREMENTS["xpu"]
                            if gpu_arch_type == "xpu"
                            else PYTORCH_EXTRA_INSTALL_REQUIREMENTS.get(
                                gpu_arch_version, ""
                            )
                            if gpu_arch_type == "rocm"
                            else PYTORCH_EXTRA_INSTALL_REQUIREMENTS[CUDA_STABLE][
                                "linux"
                            ]
                            if gpu_arch_type == "cpu" and os == "macos-arm64"
                            else ""
                        ),
                    }
                )
                if gpu_arch_version == ROCM_PREVIEW.arch:
                    # Tests install from, and uploads land in, the same index.
                    ret[-1]["upload_subfolder"] = ROCM_PREVIEW.channel

    return ret


def generate_libtorch_extraction_configs(
    os: str,
    wheel_configs: list[dict[str, str]],
) -> list[dict[str, str]]:
    """Generate libtorch extraction configs from existing wheel build configs.

    For each unique arch variant in wheel_configs, find the config for the
    oldest built Python and produce a config that the CI template uses to add
    an extraction job that depends on that wheel's build job.

    NB: the oldest built Python is per arch (py3.11 for most, later for lanes
    such as preview that skip it), so no arch silently loses its libtorch.
    """
    arch = "arm64" if os == "windows-arm64" else "x86_64"

    def python_rank(config: dict[str, str]) -> int:
        version = config.get("python_version", "")
        if version in FULL_PYTHON_VERSIONS:
            return FULL_PYTHON_VERSIONS.index(version)
        return len(FULL_PYTHON_VERSIONS)

    # Group wheel configs by (gpu_arch_type, gpu_arch_version)
    arch_to_config: dict[tuple[str, str], dict[str, str]] = {}
    for config in wheel_configs:
        key = (config["gpu_arch_type"], config.get("gpu_arch_version", ""))
        if key not in arch_to_config or python_rank(config) < python_rank(
            arch_to_config[key]
        ):
            arch_to_config[key] = config

    ret: list[dict[str, str]] = []
    for (gpu_arch_type, gpu_arch_version), source_config in arch_to_config.items():
        # No libtorch for XPU
        if gpu_arch_type == "xpu":
            continue

        desired_cuda = source_config["desired_cuda"]
        libtorch_variant = "shared-with-deps"
        # Include arch in the build name so windows x86_64 and arm64 libtorch
        # packages don't share a name and overwrite each other on upload.
        arch_tag = f"{arch}-" if os == "windows-arm64" else ""
        build_name = f"libtorch-{arch_tag}{gpu_arch_type}{gpu_arch_version}-{libtorch_variant}-release".replace(
            ".", "_"
        )

        lt_config: dict[str, str] = {
            "source_wheel_build_name": source_config["build_name"],
            "build_name": build_name,
            "package_type": "libtorch",
            "libtorch_variant": libtorch_variant,
            "libtorch_config": RELEASE,
            "desired_cuda": desired_cuda,
            "gpu_arch_type": gpu_arch_type,
            "gpu_arch_version": gpu_arch_version,
            "arch": arch,
        }
        if "container_image" in source_config:
            lt_config["container_image"] = source_config["container_image"]
            lt_config["container_image_tag_prefix"] = source_config[
                "container_image_tag_prefix"
            ]
        if source_config.get("upload_subfolder"):
            lt_config["upload_subfolder"] = source_config["upload_subfolder"]
        ret.append(lt_config)

    return ret


arch_version = ""
for arch_version in CUDA_ARCHES:
    validate_nccl_dep_consistency(arch_version)
    validate_cudnn_version_consistency(arch_version)
del arch_version
validate_runtime_release_table_consistency()


if __name__ == "__main__":
    # Used by tools/nightly.py
    (SCRIPT_DIR / "nightly_source_matrix.json").write_text(
        json.dumps(NIGHTLY_SOURCE_MATRIX, indent=4) + "\n"
    )