{% import 'common.yml.j2' as common %}
{% import 'upload.yml.j2' as upload %}

{%- block name -%}
# Template is at:    .github/templates/linux_binary_build_workflow.yml.j2
# Generation script: .github/scripts/generate_ci_workflows.py
name: !{{ build_environment }}
{%- endblock %}

{#- Pre-filter build_configs by gpu_arch_type so each matrix.include only carries
    the entries it needs. Tests for ROCm/XPU run inline (they use setup-* host
    actions and custom GPU device passthrough); everything else delegates to
    _binary-test-linux.yml. -#}
{%- set all_rocm_configs = build_configs | selectattr('gpu_arch_type', 'equalto', 'rocm') | list %}
{#- The preview lane tracks a moving SDK, so it gets its own build/test/upload
    chain; a red preview leg must not block the supported ROCm uploads. -#}
{%- set rocm_preview_configs = all_rocm_configs | selectattr('gpu_arch_version', 'equalto', 'preview') | list %}
{%- set rocm_configs = all_rocm_configs | rejectattr('gpu_arch_version', 'equalto', 'preview') | list %}
{%- set xpu_configs = build_configs | selectattr('gpu_arch_type', 'equalto', 'xpu') | list %}
{%- set test_standard_configs = build_configs | rejectattr('gpu_arch_type', 'in', ['rocm', 'xpu']) | list %}

{#- gpu_arch_types listed here are grouped into a single runner that loops over
    CPython versions, reusing build/ across iterations (cmake.py cache
    invalidation handles the per-Python ABI bits). Everything else still runs
    on the per-Python matrix below. Add more arch types here as their inline
    build job is wired up. -#}
{%- set unified_arch_types = ['cpu', 'cpu-aarch64', 'cuda', 'cuda-aarch64', 'xpu'] %}
{%- set unified_build_configs = build_configs | selectattr('gpu_arch_type', 'in', unified_arch_types) | list %}
{%- set matrix_build_configs = build_configs | rejectattr('gpu_arch_type', 'in', unified_arch_types) | rejectattr('gpu_arch_version', 'equalto', 'preview') | list %}

{#- Standard (non-ROCm/XPU) configs that are built by the manywheel-build matrix
    rather than an inline unified job (e.g. cpu-s390x). manywheel-test consumes
    these, so it must wait on manywheel-build only when such configs exist. -#}
{%- set matrix_standard_configs = matrix_build_configs | rejectattr('gpu_arch_type', 'in', ['rocm', 'xpu']) | list %}

{#- Group unified configs by (gpu_arch_type, desired_cuda). Containers differ
    per CUDA version, so each (arch, cuda) needs its own job; within a group
    only the Python version varies. -#}
{%- set ns = namespace(groups=[]) %}
{%- for cfg in unified_build_configs %}
  {%- set existing = ns.groups | selectattr('arch_type', 'equalto', cfg['gpu_arch_type']) | selectattr('desired_cuda', 'equalto', cfg['desired_cuda']) | list %}
  {%- if existing %}
    {%- set _ = existing[0]['configs'].append(cfg) %}
  {%- else %}
    {%- set _ = ns.groups.append({'arch_type': cfg['gpu_arch_type'], 'desired_cuda': cfg['desired_cuda'], 'configs': [cfg]}) %}
  {%- endif %}
{%- endfor %}

{#- Per-OS values that shape the build/test runner labels.
    s390x runners are self-hosted, register only with the bare `linux.s390x`
    label (no `lf.` prefix), and lack a host-level `docker` CLI compatible
    with GHA's native `container:` directive. They share the same reusable
    workflows but pass `use_container_directive: false` so the build/test
    container is launched via `docker run` from a step instead. -#}
{%- set release_runner_if = "(github.ref == 'refs/heads/main' || github.ref == 'refs/heads/nightly' || startsWith(github.ref, 'refs/heads/release/') || startsWith(github.ref, 'refs/tags/v'))" %}
{%- if "aarch64" in build_environment %}
  {%- set build_runs_on = "${{ " ~ release_runner_if ~ " && 'rel-l-arm64g3-44-340' || 'l-arm64g3-61-463' }}" %}
  {%- set alpine_image  = "arm64v8/alpine" %}
  {%- set timeout_minutes = 420 %}
  {%- set runner_prefix = "${{ needs.get-label-type.outputs.label-type }}" %}
  {%- set use_container_directive = true %}
{%- elif "s390x" in build_environment %}
  {%- set build_runs_on = "linux.s390x" %}
  {%- set alpine_image  = "docker.io/s390x/alpine" %}
  {%- set timeout_minutes = 420 %}
  {%- set runner_prefix = "" %}
  {%- set use_container_directive = false %}
{%- else %}
  {%- set build_runs_on = "${{ " ~ release_runner_if ~ " && 'rel-l-x86iavx512-44-340' || 'l-x86iavx512-48-384' }}" %}
  {%- set alpine_image  = "308535385114.dkr.ecr.us-east-1.amazonaws.com/tool/alpine" %}
  {%- set timeout_minutes = common.timeout_minutes %}
  {%- set runner_prefix = "${{ needs.get-label-type.outputs.label-type }}" %}
  {%- set use_container_directive = true %}
{%- endif %}

{#- On release-candidate tag builds the manylinux builder image is pinned to the
    .ci/docker tree hash (computed at runtime by the get-docker-tag job below) so
    the release uses the reproducible image binary-docker-build published as
    ${prefix}-${CI_FOLDER_SHA}, instead of main's floating tag. Doing this at
    runtime means .ci/docker changes on a release branch need no workflow
    regeneration. s390x is intentionally excluded. -#}
{%- set pin_docker_image = "s390x" not in build_environment %}
{%- if pin_docker_image %}
  {%- set docker_image_suffix = "${{ needs.get-docker-tag.outputs.docker_image_suffix }}" %}
  {#- Registry host prefix (with trailing slash) for the builder image. Blank
      (-> Docker Hub) on nightly/release and on ciflow/binaries PR test runs
      whose .ci/docker tree main has already published; get-docker-tag sets it
      to the ECR host only when the tree is one the PR's own ciflow/docker run
      built. A skipped get-docker-tag reads blank, preserving the Docker Hub
      floating tag. -#}
  {%- set docker_registry_host = "${{ needs.get-docker-tag.outputs.docker_registry_host }}" %}
  {#- get-docker-tag only runs on tag pushes, so jobs that need it must tolerate
      it being skipped (a skipped need skips dependents by default). !failure()
      keeps the real build->test ordering; a skipped get-docker-tag is not a
      failure, and its output reads as blank, giving the floating tag. -#}
  {%- set owner_if = "${{ !failure() && !cancelled() && github.repository_owner == 'pytorch' }}" %}
{%- else %}
  {%- set docker_image_suffix = "" %}
  {%- set docker_registry_host = "" %}
  {%- set owner_if = "${{ github.repository_owner == 'pytorch' }}" %}
{%- endif %}
{#- Every preview lane needs get-preview-docker-tag, which only exists with
    pinned images; drop the lanes otherwise. -#}
{%- set preview_enabled = pin_docker_image and rocm_preview_configs|length > 0 %}
{%- if not preview_enabled %}
  {%- set rocm_preview_configs = [] %}
{%- endif %}
{%- set preview_docker_image_suffix = "${{ needs.get-preview-docker-tag.outputs.docker_image_suffix }}" %}
{%- set preview_docker_registry_host = "${{ needs.get-preview-docker-tag.outputs.docker_registry_host }}" %}
{%- set preview_if = "${{ !failure() && !cancelled() && github.repository_owner == 'pytorch' && !startsWith(github.ref, 'refs/tags/v') && needs.get-preview-docker-tag.outputs.image_available == 'true' }}" %}
{%- set preview_test_if = "${{ !failure() && !cancelled() && github.repository_owner == 'pytorch' && !startsWith(github.ref, 'refs/tags/v') && needs.get-preview-docker-tag.outputs.test_available == 'true' }}" %}

on:
  push:
    {%- if branches == "nightly" %}
    # NOTE: Meta Employees can trigger new nightlies using: https://fburl.com/trigger_pytorch_nightly_build
    {%- endif %}
    branches:
      - !{{ branches }}
    {%- if branches == "nightly" %}
    tags:
      # NOTE: Binary build pipelines should only get triggered on release candidate builds
      # Release candidate tags look like: v1.11.0-rc1
      - v[0-9]+.[0-9]+.[0-9]+-rc[0-9]+
    {%- endif %}
{%- for label in ciflow_config.labels | sort %}
    {%- if loop.first and branches != "nightly" %}
    tags:
    {%- endif %}
      - '!{{ label }}/*'
{%- endfor %}
  workflow_dispatch:

permissions:
  id-token: write
  contents: read

env:
  ALPINE_IMAGE: "!{{ alpine_image }}"
  AWS_DEFAULT_REGION: us-east-1
  BINARY_ENV_FILE: /tmp/env
  BUILD_ENVIRONMENT: !{{ build_environment }}
  GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  PR_NUMBER: ${{ github.event.pull_request.number }}
  PYTORCH_FINAL_PACKAGE_DIR: /artifacts
  PYTORCH_ROOT: /pytorch
  SHA1: ${{ github.event.pull_request.head.sha || github.sha }}
  SKIP_ALL_TESTS: 0
!{{ common.concurrency(build_environment) }}

jobs:
  get-label-type:
    if: github.repository_owner == 'pytorch'
    name: get-label-type
    uses: pytorch/pytorch/.github/workflows/_runner-determinator.yml@main
    with:
      triggering_actor: ${{ github.triggering_actor }}
      issue_owner: ${{ github.event.pull_request.user.login || github.event.issue.user.login }}
      curr_branch: ${{ github.head_ref || github.ref_name }}
      curr_ref_type: ${{ github.ref_type }}
      opt_out_experiments: lf
{%- if pin_docker_image %}

  # Computes the manylinux builder image tag suffix + registry host at runtime,
  # feeding the job-level `container:` directives (resolved before any step runs):
  #   - release-candidate tag (v1.2.3-rc4): suffix = "-<.ci/docker tree hash>",
  #     host = "" -> the reproducible image binary-docker-build pinned on Docker
  #     Hub.
  #   - ciflow/binaries PR test: suffix = "-<hash>". Main publishes every
  #     .ci/docker tree it builds to Docker Hub under that tag, so a PR that
  #     leaves .ci/docker untouched finds its image there and host = "". A PR
  #     that changes .ci/docker has a tree only its own ciflow/docker run has
  #     built, pushed to ECR by binary-docker-build, so host = the ECR host.
  #     Because build-manywheel-images runs in parallel on the same PR, this
  #     job then WAITS (polls ECR) until those images are pushed before the
  #     build/test jobs start pulling them.
  #   - otherwise (nightly branch, etc.): skipped; outputs read blank -> Docker
  #     Hub floating tag, unchanged.
  get-docker-tag:
    needs: get-label-type
    # Runs on tag pushes only (release candidates + ciflow/binaries). On branch
    # (nightly) runs it is skipped and its outputs read blank, so the floating
    # Docker Hub tag is used.
    if: ${{ github.repository_owner == 'pytorch' && github.ref_type == 'tag' }}
    name: get-docker-tag
    runs-on: ubuntu-24.04
    permissions:
      id-token: write
      contents: read
    outputs:
      docker_image_suffix: ${{ steps.calc.outputs.docker_image_suffix }}
      docker_registry_host: ${{ steps.calc.outputs.docker_registry_host }}
    steps:
      - name: Checkout PyTorch
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
          fetch-depth: 1
          submodules: false
          show-progress: false
      - name: Calculate docker image suffix and registry host
        id: calc
        env:
          REF_TYPE: ${{ github.ref_type }}
          REF_NAME: ${{ github.ref_name }}
          GITHUB_REF: ${{ github.ref }}
        shell: bash
        run: |
          set -euo pipefail
          suffix=""
          registry_host=""
          if [[ "${GITHUB_REF}" == refs/tags/ciflow/binaries* ]]; then
            # PR test run: content-addressed image, from Docker Hub if main has
            # published this tree, else from ECR via the PR's ciflow/docker run.
            suffix="-$(git rev-parse HEAD:.ci/docker)"
            registry_host="308535385114.dkr.ecr.us-east-1.amazonaws.com/"
{%- if ns.groups %}
            # build-manywheel-images builds and pushes all variants together, so
            # probe a single representative image. The tag API needs no login;
            # any failure (404, outage) keeps the ECR path.
            repo="pytorch/!{{ ns.groups[0]['configs'][0]['container_image'] }}"
            tag="!{{ ns.groups[0]['configs'][0]['container_image_tag_prefix'] }}${suffix}"
            if git ls-remote --exit-code --tags origin "refs/tags/ciflow/docker/${GITHUB_REF##*/}" >/dev/null; then
              echo "ciflow/docker is attached to this PR, so its images are rebuilt; using ECR"
            elif curl -fsS --retry 3 -o /dev/null "https://hub.docker.com/v2/repositories/${repo}/tags/${tag}"; then
              echo "docker.io/${repo}:${tag} exists; using Docker Hub"
              registry_host=""
            else
              echo "docker.io/${repo}:${tag} not on Docker Hub; using ECR"
            fi
{%- endif %}
          elif [[ "${REF_TYPE}" == "tag" && "${REF_NAME}" == v* ]]; then
            # Release candidate: pin the Docker Hub image.
            suffix="-$(git rev-parse HEAD:.ci/docker)"
          fi
          echo "docker_image_suffix=${suffix}" >> "${GITHUB_OUTPUT}"
          echo "docker_registry_host=${registry_host}" >> "${GITHUB_OUTPUT}"
      # ciflow/binaries with a tree Docker Hub lacks: the builder images are
      # pushed to ECR by build-manywheel-images / build-almalinux-images, which
      # run concurrently on the same PR. Log in (read-only) and wait for the
      # content-addressed tags to appear before the build/test jobs try to pull
      # them.
      - name: Login to ECR
        if: ${{ startsWith(github.ref, 'refs/tags/ciflow/binaries') && steps.calc.outputs.docker_registry_host != '' }}
        uses: pytorch/pytorch/.github/actions/ecr-login@main
{%- if ns.groups %}
      - name: Wait for content-addressed builder image in ECR
        if: ${{ startsWith(github.ref, 'refs/tags/ciflow/binaries') && steps.calc.outputs.docker_registry_host != '' }}
        env:
          DOCKER_IMAGE_SUFFIX: ${{ steps.calc.outputs.docker_image_suffix }}
        shell: bash
        run: |
          set -euo pipefail
          # Drop the leading dash: "-<hash>" -> "<hash>".
          tree_hash="${DOCKER_IMAGE_SUFFIX#-}"
          # build-manywheel-images builds and pushes all variants together, so
          # wait on a single representative image as the readiness signal.
          repo="pytorch/!{{ ns.groups[0]['configs'][0]['container_image'] }}"
          tag="!{{ ns.groups[0]['configs'][0]['container_image_tag_prefix'] }}-${tree_hash}"
          echo "Waiting for ${repo}:${tag} to be pushed to ECR by build-manywheel-images..."
          # Poll every 5 min, up to 60 min.
          deadline=$(( SECONDS + 60 * 60 ))
          until aws ecr describe-images \
              --region us-east-1 \
              --repository-name "${repo}" \
              --image-ids imageTag="${tag}" >/dev/null 2>&1; do
            if (( SECONDS > deadline )); then
              echo "ERROR: timed out (60 min) waiting for ${repo}:${tag} in ECR." >&2
              echo "Is build-manywheel-images / build-almalinux-images still running or did it fail?" >&2
              exit 1
            fi
            echo "  not in ECR yet (build-manywheel-images still running); retrying in 5 min..."
            sleep 300
          done
          echo "Found ${repo}:${tag}"
{%- endif %}
{%- endif %}

{%- if preview_enabled %}
  # A missing preview image must not redirect or block the stable lanes. PRs
  # that change .ci/docker (e.g. pin bumps) build and extract from their own
  # ECR image; ROCm test runners cannot pull ECR, so preview tests are skipped.
  get-preview-docker-tag:
    needs: get-label-type
    if: ${{ github.repository_owner == 'pytorch' && !startsWith(github.ref, 'refs/tags/v') }}
    name: get-preview-docker-tag
    runs-on: ubuntu-24.04
    permissions:
      id-token: write
      contents: read
    outputs:
      docker_image_suffix: ${{ steps.calc.outputs.docker_image_suffix }}
      docker_registry_host: ${{ steps.ecr.outputs.docker_registry_host }}
      image_available: ${{ steps.ecr.outputs.image_available || steps.calc.outputs.image_available }}
      test_available: ${{ steps.ecr.outputs.test_available || steps.calc.outputs.test_available }}
    steps:
      - name: Checkout PyTorch
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
          fetch-depth: 1
          submodules: false
          show-progress: false
      - name: Check preview builder availability
        id: calc
        env:
          REF_TYPE: ${{ github.ref_type }}
          GITHUB_REF: ${{ github.ref }}
          GITHUB_EVENT_NAME: ${{ github.event_name }}
          PREVIEW_IMAGE_WAIT_SECONDS: 3600
          PREVIEW_IMAGE_POLL_SECONDS: 300
        shell: bash
        run: |
          set -euo pipefail
          suffix=""
          if [[ "${REF_TYPE}" == "tag" || "${GITHUB_REF}" == "refs/heads/nightly" || "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
            suffix="-$(git rev-parse HEAD:.ci/docker)"
          fi
          tag="!{{ rocm_preview_configs[0]['container_image_tag_prefix'] }}${suffix}"
          repo="pytorch/!{{ rocm_preview_configs[0]['container_image'] }}"
          url="https://hub.docker.com/v2/repositories/${repo}/tags/${tag}"
          deadline=$((SECONDS + PREVIEW_IMAGE_WAIT_SECONDS))
          while true; do
            request_timeout=60
            if [[ "${GITHUB_REF}" == "refs/heads/nightly" ]]; then
              remaining=$((deadline - SECONDS))
              if ((remaining < request_timeout)); then
                request_timeout=$((remaining > 0 ? remaining : 1))
              fi
            fi
            if ! status=$(curl -sS --retry 3 --retry-all-errors \
                --max-time "${request_timeout}" --retry-max-time "${request_timeout}" \
                -o /dev/null -w '%{http_code}' "${url}"); then
              echo "::error::Failed to query preview builder ${repo}:${tag}."
              exit 1
            fi
            if [[ "${status}" == "200" ]]; then
              echo "docker.io/${repo}:${tag} exists"
              available=true
              break
            fi
            if [[ "${status}" == "404" && "${GITHUB_REF}" == refs/tags/ciflow/* ]]; then
              echo "docker.io/${repo}:${tag} not on Docker Hub; checking ECR"
              available=false
              use_ecr=true
              break
            fi
            remaining=$((deadline - SECONDS))
            if [[ "${status}" == "404" && "${GITHUB_REF}" == "refs/heads/nightly" && "${remaining}" -gt 0 ]]; then
              delay="${PREVIEW_IMAGE_POLL_SECONDS}"
              if ((delay > remaining)); then
                delay="${remaining}"
              fi
              echo "Preview builder ${repo}:${tag} is not published yet; retrying in ${delay}s..."
              sleep "${delay}"
              continue
            fi
            if [[ "${status}" == "404" && "${GITHUB_REF}" == "refs/heads/nightly" ]]; then
              echo "::warning::Preview builder ${repo}:${tag} was not published in time; skipping preview jobs."
              available=false
              break
            fi
            echo "::error::Preview builder probe returned HTTP ${status} for ${repo}:${tag}."
            exit 1
          done
          echo "docker_image_suffix=${suffix}" >> "${GITHUB_OUTPUT}"
          echo "image_available=${available}" >> "${GITHUB_OUTPUT}"
          echo "test_available=${available}" >> "${GITHUB_OUTPUT}"
          echo "use_ecr=${use_ecr:-false}" >> "${GITHUB_OUTPUT}"
      - name: Login to ECR
        if: ${{ steps.calc.outputs.use_ecr == 'true' }}
        uses: pytorch/pytorch/.github/actions/ecr-login@main
      - name: Wait for preview builder image in ECR
        id: ecr
        if: ${{ steps.calc.outputs.use_ecr == 'true' }}
        env:
          DOCKER_IMAGE_SUFFIX: ${{ steps.calc.outputs.docker_image_suffix }}
        shell: bash
        run: |
          set -euo pipefail
          repo="pytorch/!{{ rocm_preview_configs[0]['container_image'] }}"
          tag="!{{ rocm_preview_configs[0]['container_image_tag_prefix'] }}${DOCKER_IMAGE_SUFFIX}"
          # Only the PR's ciflow/docker run pushes this tag; skip preview without it.
          deadline=$(( SECONDS + 60 * 60 ))
          until aws ecr describe-images \
              --region us-east-1 \
              --repository-name "${repo}" \
              --image-ids imageTag="${tag}" >/dev/null 2>&1; do
            if (( SECONDS > deadline )); then
              echo "::warning::Preview builder ${repo}:${tag} is not in Docker Hub or ECR; skipping preview jobs."
              echo "image_available=false" >> "${GITHUB_OUTPUT}"
              echo "test_available=false" >> "${GITHUB_OUTPUT}"
              exit 0
            fi
            echo "  ${repo}:${tag} not in ECR yet; retrying in 5 min..."
            sleep 300
          done
          echo "Found ${repo}:${tag} in ECR; preview tests are skipped (no ECR access on ROCm runners)."
          echo "docker_registry_host=308535385114.dkr.ecr.us-east-1.amazonaws.com/" >> "${GITHUB_OUTPUT}"
          echo "image_available=true" >> "${GITHUB_OUTPUT}"
          echo "test_available=false" >> "${GITHUB_OUTPUT}"
{%- endif %}

{#- One inline build job per (gpu_arch_type, desired_cuda) group. Each loops
    over all CPython versions in the group on a single runner, reusing build/
    across iterations. libtorch_cpu/libtorch_cuda are Python-ABI-free; only
    libtorch_python + _C are recompiled per interpreter via the cmake.py cache
    invalidation. -#}
{#- Carries each group's build job name, so the test and upload jobs below can
    each depend on just their own group. -#}
{%- set unified_upload_groups = [] %}
{%- for g in ns.groups %}
  {%- set group = g['configs'] %}
  {%- set arch_type = g['arch_type'] %}
  {%- set desired_cuda = g['desired_cuda'] %}
  {%- set first = group[0] %}
  {#- Job name: keep cpu/cpu-aarch64 names stable; for cuda, include the
      desired_cuda variant so cu126/cu130/cu132 each get a distinct job. -#}
  {%- if desired_cuda == 'cpu' or desired_cuda == arch_type %}
    {%- set job_name = "manywheel-" ~ arch_type ~ "-build" %}
  {%- else %}
    {%- set job_name = "manywheel-" ~ arch_type ~ "-" ~ desired_cuda ~ "-build" %}
  {%- endif %}
  {#- BUILD_NAME_SUFFIX = the part of build_name after "manywheel-py{X_Y}".
      E.g. "manywheel-py3_10-cuda-aarch64-12_6" -> "-cuda-aarch64-12_6". -#}
  {%- set py_dotless = first['python_version'] | replace('.', '_') %}
  {%- set build_name_suffix = first['build_name'] | replace('manywheel-py' ~ py_dotless, '') %}
  {%- if arch_type != 'xpu' %}
  {%- set _ = unified_upload_groups.append({
        'job_name': job_name,
        'test_name': job_name | replace('-build', '-test'),
        'configs': group}) %}
  {%- endif %}

  !{{ job_name }}:
    name: !{{ job_name }}
    if: !{{ owner_if }}
    needs: [get-label-type{%- if pin_docker_image %}, get-docker-tag{%- endif %}]
    runs-on: "!{{ runner_prefix }}!{{ build_runs_on }}"
    timeout-minutes: !{{ 420 if arch_type == 'xpu' else timeout_minutes }}
    container:
      image: !{{ docker_registry_host }}pytorch/!{{ first['container_image'] }}:!{{ first['container_image_tag_prefix'] }}!{{ docker_image_suffix }}
    env:
      PYTORCH_ROOT: ${{ github.workspace }}
      PACKAGE_TYPE: !{{ first['package_type'] }}
      DESIRED_CUDA: !{{ desired_cuda }}
      GPU_ARCH_VERSION: "!{{ first['gpu_arch_version'] | default('') }}"
      GPU_ARCH_TYPE: !{{ arch_type }}
      DOCKER_IMAGE: !{{ docker_registry_host }}pytorch/!{{ first['container_image'] }}:!{{ first['container_image_tag_prefix'] }}!{{ docker_image_suffix }}
      SKIP_ALL_TESTS: 1
      DESIRED_PYTHONS: "!{{ group | map(attribute='python_version') | join(' ') }}"
      BUILD_NAME_PREFIX: "manywheel-py"
      BUILD_NAME_SUFFIX: "!{{ build_name_suffix }}"
      {%- if first.pytorch_extra_install_requirements is defined and first.pytorch_extra_install_requirements|d('')|length > 0 %}
      PYTORCH_EXTRA_INSTALL_REQUIREMENTS: "!{{ first['pytorch_extra_install_requirements'] }}"
      {%- endif %}
    steps:
      - name: Configure git safe directory
        run: git config --global --add safe.directory "$GITHUB_WORKSPACE"
      - name: Checkout PyTorch
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
          # Full fetch on tag pushes so the release tag is visible to
          # `git describe --tags --exact`; nightlies stay shallow for speed.
          fetch-depth: ${{ github.ref_type != 'tag' && 2 || 0 }}
          fetch-tags: ${{ github.ref_type == 'tag' }}
          submodules: recursive
          show-progress: false
      - name: Populate binary env
        shell: bash
        run: |
          export PYTORCH_FINAL_PACKAGE_DIR="${RUNNER_TEMP}/artifacts"
          mkdir -p "${PYTORCH_FINAL_PACKAGE_DIR}"
          echo "PYTORCH_FINAL_PACKAGE_DIR=${PYTORCH_FINAL_PACKAGE_DIR}" >> "${GITHUB_ENV}"
          bash .ci/pytorch/binary_populate_env.sh
      - name: Build all wheels
        shell: bash
        run: |
          # shellcheck disable=SC1090,SC1091
          source "${BINARY_ENV_FILE}"
          bash .ci/wheel/linux/build_all.sh
      # One artifact per built Python -- names must match what the test/upload
      # matrix below downloads.
  {%- for config in group %}
      - uses: !{{ common.upload_artifact_action }}
        with:
          name: !{{ config['build_name'] }}
          if-no-files-found: error
          path: ${{ runner.temp }}/artifacts/!{{ config['build_name'] }}/*
  {%- endfor %}
  {%- if arch_type == 'cuda-aarch64' %}
      # LLVM BOLT keeps the unoptimized libraries in build/lib/prebolt, with a
      # libtorch_python.so per interpreter under prebolt/<SOABI>/ (see
      # build_all.sh). Publish them with a short retention for profiling
      # (#199067). Optional, so it must not fail the build.
      - uses: !{{ common.upload_artifact_action }}
        if: ${{ github.ref == 'refs/heads/nightly' || startsWith(github.ref, 'refs/tags/ciflow/binaries') }}
        continue-on-error: true
        with:
          name: prebolt!{{ build_name_suffix }}
          path: build/lib/prebolt/
          if-no-files-found: warn
          retention-days: 7
          compression-level: 1
  {%- endif %}
{%- endfor %}

{%- set build_lanes = [] %}
{%- set build_needs = "[get-label-type, get-docker-tag]" if pin_docker_image else "get-label-type" %}
{%- if matrix_build_configs %}
  {%- set _ = build_lanes.append({
        'job_name': 'manywheel-build',
        'configs': matrix_build_configs,
        'if': owner_if,
        'needs': build_needs,
        'image_suffix': docker_image_suffix,
        'image_registry_host': docker_registry_host}) %}
{%- endif %}
{%- if rocm_preview_configs %}
  {%- set _ = build_lanes.append({
        'job_name': 'manywheel-build-rocm-preview',
        'configs': rocm_preview_configs,
        'if': preview_if,
        'needs': '[get-label-type, get-preview-docker-tag]',
        'image_suffix': preview_docker_image_suffix,
        'image_registry_host': preview_docker_registry_host}) %}
{%- endif %}
{%- for lane in build_lanes %}

  !{{ lane['job_name'] }}:
    name: ${{ matrix.build_name }}-build
    if: !{{ lane['if'] }}
    uses: ./.github/workflows/_binary-build-linux.yml
    needs: !{{ lane['needs'] }}
    strategy:
      fail-fast: false
      matrix:
        include:
        {%- for config in lane['configs'] %}
          - desired_python: "!{{ config['python_version'] }}"
            desired_cuda: "!{{ config['desired_cuda'] }}"
            gpu_arch_version: "!{{ config['gpu_arch_version'] | default('') }}"
            gpu_arch_type: "!{{ config['gpu_arch_type'] }}"
            docker_image: "!{{ config['container_image'] }}"
            docker_image_tag_prefix: "!{{ config['container_image_tag_prefix'] }}"
            build_name: "!{{ config['build_name'] }}"
            {%- if config['gpu_arch_type'] == 'rocm' %}
            timeout_minutes: 420
            {%- else %}
            timeout_minutes: !{{ timeout_minutes }}
            {%- endif %}
            {%- if config.pytorch_extra_install_requirements is defined and config.pytorch_extra_install_requirements|d('')|length > 0 %}
            pytorch_extra_install_requirements: "!{{ config['pytorch_extra_install_requirements'] }}"
            {%- else %}
            pytorch_extra_install_requirements: ""
            {%- endif %}
        {%- endfor %}
    with:
      PYTORCH_ROOT: /pytorch
      PACKAGE_TYPE: !{{ lane['configs'][0]['package_type'] }}
      DESIRED_CUDA: ${{ matrix.desired_cuda }}
      GPU_ARCH_VERSION: ${{ matrix.gpu_arch_version }}
      GPU_ARCH_TYPE: ${{ matrix.gpu_arch_type }}
      DOCKER_IMAGE: ${{ matrix.docker_image }}
      DOCKER_IMAGE_TAG_PREFIX: ${{ matrix.docker_image_tag_prefix }}!{{ lane['image_suffix'] }}
      DOCKER_IMAGE_REGISTRY_HOST: "!{{ lane['image_registry_host'] }}"
      DESIRED_PYTHON: ${{ matrix.desired_python }}
      runner_prefix: "!{{ runner_prefix }}"
      runs_on: !{{ build_runs_on }}
      use_container_directive: !{{ use_container_directive | string | lower }}
      ALPINE_IMAGE: "!{{ alpine_image }}"
      PYTORCH_EXTRA_INSTALL_REQUIREMENTS: ${{ matrix.pytorch_extra_install_requirements }}
      timeout-minutes: ${{ matrix.timeout_minutes }}
      build_name: ${{ matrix.build_name }}
      build_environment: !{{ build_environment }}
    secrets:
      github-token: ${{ secrets.GITHUB_TOKEN }}
{%- endfor %}

{%- if test_standard_configs %}
{#- One test job per arch group, matching the build jobs, so each group runs
    build -> test -> upload independently. A single shared test job would make
    every group's upload wait on the slowest group's tests, since `needs` is
    evaluated per job rather than per matrix leg.

    ROCm/XPU already have their own test jobs below. -#}
{%- set standard_test_jobs = [] %}
{%- for u in unified_upload_groups %}
  {%- set _ = standard_test_jobs.append({
        'name': u['test_name'],
        'needs': [u['job_name']],
        'configs': u['configs']}) %}
{%- endfor %}
{%- if matrix_standard_configs %}
  {#- Standard configs built by the manywheel-build matrix (e.g. cpu-s390x)
      keep the manywheel-test name. -#}
  {%- set _ = standard_test_jobs.append({
        'name': 'manywheel-test',
        'needs': ['manywheel-build'],
        'configs': matrix_standard_configs}) %}
{%- endif %}
{%- for test_job in standard_test_jobs %}

  !{{ test_job['name'] }}:
    name: ${{ matrix.build_name }}-test
    if: !{{ owner_if }}
    needs: [get-label-type{%- if pin_docker_image %}, get-docker-tag{%- endif %}, !{{ test_job['needs'] | join(', ') }}]
    uses: ./.github/workflows/_binary-test-linux.yml
    strategy:
      fail-fast: false
      matrix:
        include:
        {%- for config in test_job['configs'] %}
          {%- if "aarch64" in build_environment %}
          {%- set _runs_on = "l-arm64g3-16-62" %}
          {%- elif "s390x" in build_environment %}
          {%- set _runs_on = "linux.s390x" %}
          {%- elif config['gpu_arch_type'] == "cuda" %}
          {%- set _runs_on = "l-x86iavx512-29-115-t4" %}
          {%- else %}
          {%- set _runs_on = "l-x86iavx512-16-128" %}
          {%- endif %}
          - desired_python: "!{{ config['python_version'] }}"
            desired_cuda: "!{{ config['desired_cuda'] }}"
            gpu_arch_version: "!{{ config['gpu_arch_version'] | default('') }}"
            gpu_arch_type: "!{{ config['gpu_arch_type'] }}"
            docker_image: "!{{ config['container_image'] }}"
            docker_image_tag_prefix: "!{{ config['container_image_tag_prefix'] }}"
            build_name: "!{{ config['build_name'] }}"
            runs_on: "!{{ _runs_on }}"
        {%- endfor %}
    with:
      PYTORCH_ROOT: /pytorch
      PACKAGE_TYPE: !{{ build_configs[0]['package_type'] }}
      DESIRED_CUDA: ${{ matrix.desired_cuda }}
      GPU_ARCH_VERSION: ${{ matrix.gpu_arch_version }}
      GPU_ARCH_TYPE: ${{ matrix.gpu_arch_type }}
      DOCKER_IMAGE: ${{ matrix.docker_image }}
      DOCKER_IMAGE_TAG_PREFIX: ${{ matrix.docker_image_tag_prefix }}!{{ docker_image_suffix }}
      DOCKER_IMAGE_REGISTRY_HOST: "!{{ docker_registry_host }}"
      DESIRED_PYTHON: ${{ matrix.desired_python }}
      build_name: ${{ matrix.build_name }}
      build_environment: !{{ build_environment }}
      runner_prefix: "!{{ runner_prefix }}"
      runs_on: ${{ matrix.runs_on }}
      use_container_directive: !{{ use_container_directive | string | lower }}
      ALPINE_IMAGE: "!{{ alpine_image }}"
    secrets:
      github-token: ${{ secrets.GITHUB_TOKEN }}
{%- endfor %}
{%- endif %}

{%- set rocm_test_lanes = [] %}
{%- if rocm_configs %}
  {%- set _ = rocm_test_lanes.append({
        'job_name': 'manywheel-test-rocm',
        'build_job': 'manywheel-build',
        'configs': rocm_configs,
        'if': owner_if,
        'needs': '[get-label-type' ~ (', get-docker-tag' if pin_docker_image else '') ~ ', manywheel-build]',
        'image_suffix': docker_image_suffix,
        'image_registry_host': docker_registry_host}) %}
{%- endif %}
{%- if rocm_preview_configs %}
  {%- set _ = rocm_test_lanes.append({
        'job_name': 'manywheel-test-rocm-preview',
        'build_job': 'manywheel-build-rocm-preview',
        'configs': rocm_preview_configs,
        'if': preview_test_if,
        'needs': '[get-label-type, get-preview-docker-tag, manywheel-build-rocm-preview]',
        'image_suffix': preview_docker_image_suffix,
        'image_registry_host': preview_docker_registry_host}) %}
{%- endif %}
{%- for lane in rocm_test_lanes %}

  !{{ lane['job_name'] }}:
    name: ${{ matrix.build_name }}-test
    if: !{{ lane['if'] }}
    needs: !{{ lane['needs'] }}
    uses: ./.github/workflows/_binary-test-rocm-linux.yml
    strategy:
      fail-fast: false
      matrix:
        include:
        {%- for config in lane['configs'] %}
          - desired_python: "!{{ config['python_version'] }}"
            desired_cuda: "!{{ config['desired_cuda'] }}"
            gpu_arch_version: "!{{ config['gpu_arch_version'] | default('') }}"
            gpu_arch_type: "!{{ config['gpu_arch_type'] }}"
            docker_image: "!{{ config['container_image'] }}"
            docker_image_tag_prefix: "!{{ config['container_image_tag_prefix'] }}"
            build_name: "!{{ config['build_name'] }}"
        {%- endfor %}
    with:
      PYTORCH_ROOT: /pytorch
      PACKAGE_TYPE: !{{ build_configs[0]['package_type'] }}
      DESIRED_CUDA: ${{ matrix.desired_cuda }}
{%- if lane['configs'][0].get('upload_subfolder') %}
      INDEX_SUBFOLDER: "!{{ lane['configs'][0]['upload_subfolder'] }}"
{%- endif %}
      GPU_ARCH_VERSION: ${{ matrix.gpu_arch_version }}
      GPU_ARCH_TYPE: ${{ matrix.gpu_arch_type }}
      DOCKER_IMAGE: ${{ matrix.docker_image }}
      DOCKER_IMAGE_TAG_PREFIX: ${{ matrix.docker_image_tag_prefix }}!{{ lane['image_suffix'] }}
      DOCKER_IMAGE_REGISTRY_HOST: "!{{ lane['image_registry_host'] }}"
      DESIRED_PYTHON: ${{ matrix.desired_python }}
      build_name: ${{ matrix.build_name }}
{%- endfor %}

{%- if xpu_configs %}

  manywheel-test-xpu:
    name: ${{ matrix.build_name }}-test
    if: !{{ owner_if }}
    needs: [get-label-type{%- if pin_docker_image %}, get-docker-tag{%- endif %}, manywheel-xpu-build]
    uses: ./.github/workflows/_binary-test-xpu-linux.yml
    strategy:
      fail-fast: false
      matrix:
        include:
        {%- for config in xpu_configs %}
          - desired_python: "!{{ config['python_version'] }}"
            desired_cuda: "!{{ config['desired_cuda'] }}"
            gpu_arch_type: "!{{ config['gpu_arch_type'] }}"
            docker_image: "!{{ config['container_image'] }}"
            docker_image_tag_prefix: "!{{ config['container_image_tag_prefix'] }}"
            build_name: "!{{ config['build_name'] }}"
        {%- endfor %}
    with:
      PYTORCH_ROOT: /pytorch
      PACKAGE_TYPE: !{{ build_configs[0]['package_type'] }}
      DESIRED_CUDA: ${{ matrix.desired_cuda }}
      GPU_ARCH_TYPE: ${{ matrix.gpu_arch_type }}
      DOCKER_IMAGE: ${{ matrix.docker_image }}
      # XPU test runners have no ECR pull credentials, so XPU stays on the
      # Docker Hub image (excluded from the content-addressed ECR path).
      DOCKER_IMAGE_TAG_PREFIX: ${{ matrix.docker_image_tag_prefix }}
      DESIRED_PYTHON: ${{ matrix.desired_python }}
      build_name: ${{ matrix.build_name }}
{%- endif %}

{%- if branches == "nightly" and build_configs %}
{#- One upload job per arch group rather than a single job over every config.
    `needs` is evaluated per job, not per matrix leg, so a single upload job
    cannot start until the slowest group in the whole workflow has finished --
    an XPU test waiting hours on a scarce runner held up the CPU and CUDA
    wheels behind it. Split by group, each set of wheels publishes as soon as
    its own build and test are done.

    The groups below partition build_configs exactly: unified groups (cpu /
    cuda per version), the standard configs built by the manywheel-build matrix
    (e.g. cpu-s390x), then rocm, rocm preview and xpu. -#}
{%- set upload_jobs = [] %}
{%- for u in unified_upload_groups %}
  {%- set _ = upload_jobs.append({
        'name': u['job_name'] | replace('-build', '-upload'),
        'if': owner_if,
        'needs': '[' ~ ('get-docker-tag, ' if pin_docker_image else '') ~
          (([u['job_name']] + ([u['test_name']] if test_standard_configs else [])) | join(', ')) ~ ']',
        'image_suffix': docker_image_suffix,
        'configs': u['configs']}) %}
{%- endfor %}
{%- if matrix_standard_configs %}
  {%- set _ = upload_jobs.append({
        'name': 'manywheel-upload',
        'if': owner_if,
        'needs': '[' ~ ('get-docker-tag, ' if pin_docker_image else '') ~
          ((['manywheel-build'] + (['manywheel-test'] if test_standard_configs else [])) | join(', ')) ~ ']',
        'image_suffix': docker_image_suffix,
        'configs': matrix_standard_configs}) %}
{%- endif %}
{%- if rocm_configs %}
  {%- set _ = upload_jobs.append({
        'name': 'manywheel-rocm-upload',
        'if': owner_if,
        'needs': '[' ~ ('get-docker-tag, ' if pin_docker_image else '') ~
          ('manywheel-build, manywheel-test-rocm') ~ ']',
        'image_suffix': docker_image_suffix,
        'configs': rocm_configs}) %}
{%- endif %}
{%- if rocm_preview_configs %}
  {%- set _ = upload_jobs.append({
        'name': 'manywheel-rocm-preview-upload',
        'if': preview_test_if,
        'needs': '[get-preview-docker-tag, manywheel-build-rocm-preview, manywheel-test-rocm-preview]',
        'image_suffix': preview_docker_image_suffix,
        'configs': rocm_preview_configs}) %}
{%- endif %}
{%- if xpu_configs %}
  {%- set _ = upload_jobs.append({
        'name': 'manywheel-xpu-upload',
        'if': owner_if,
        'needs': '[' ~ ('get-docker-tag, ' if pin_docker_image else '') ~
          ('manywheel-xpu-build, manywheel-test-xpu') ~ ']',
        'image_suffix': docker_image_suffix,
        'configs': xpu_configs}) %}
{%- endif %}
{%- for job in upload_jobs %}

  !{{ job['name'] }}:
    name: ${{ matrix.build_name }}-upload
    if: !{{ job['if'] }}
    permissions:
      id-token: write
      contents: read
    needs: !{{ job['needs'] }}
    uses: ./.github/workflows/_binary-upload.yml
    strategy:
      fail-fast: false
      matrix:
        include:
        {%- for config in job['configs'] %}
          - desired_python: "!{{ config['python_version'] }}"
            desired_cuda: "!{{ config['desired_cuda'] }}"
            gpu_arch_version: "!{{ config['gpu_arch_version'] | default('') }}"
            gpu_arch_type: "!{{ config['gpu_arch_type'] }}"
            docker_image: "!{{ config['container_image'] }}"
            docker_image_tag_prefix: "!{{ config['container_image_tag_prefix'] }}"
            build_name: "!{{ config['build_name'] }}"
        {%- endfor %}
    with:
      PYTORCH_ROOT: /pytorch
      PACKAGE_TYPE: !{{ build_configs[0]['package_type'] }}
      DESIRED_CUDA: ${{ matrix.desired_cuda }}
{%- if job['configs'][0].get('upload_subfolder') %}
      UPLOAD_SUBFOLDER: "!{{ job['configs'][0]['upload_subfolder'] }}"
{%- endif %}
      GPU_ARCH_VERSION: ${{ matrix.gpu_arch_version }}
      GPU_ARCH_TYPE: ${{ matrix.gpu_arch_type }}
      DOCKER_IMAGE: ${{ matrix.docker_image }}
      DOCKER_IMAGE_TAG_PREFIX: ${{ matrix.docker_image_tag_prefix }}!{{ job['image_suffix'] }}
      DESIRED_PYTHON: ${{ matrix.desired_python }}
      build_name: ${{ matrix.build_name }}
    secrets:
      github-token: ${{ secrets.GITHUB_TOKEN }}
      R2_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
      R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
      R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
{%- endfor %}
{%- endif %}

{%- set libtorch_lanes = [] %}
{%- set lt_main_configs = libtorch_extraction_configs | rejectattr('gpu_arch_version', 'equalto', 'preview') | list %}
{%- set lt_preview_configs = (libtorch_extraction_configs | selectattr('gpu_arch_version', 'equalto', 'preview') | list) if preview_enabled else [] %}
{%- if lt_main_configs %}
  {%- set _ = libtorch_lanes.append({
        'suffix': '',
        'build_job': 'manywheel-build',
        'configs': lt_main_configs,
        'if': owner_if,
        'needs': '[manywheel-build]',
        'image_suffix': '',
        'image_registry_host': ''}) %}
{%- endif %}
{%- if lt_preview_configs %}
  {%- set _ = libtorch_lanes.append({
        'suffix': '-rocm-preview',
        'build_job': 'manywheel-build-rocm-preview',
        'configs': lt_preview_configs,
        'if': preview_if,
        'needs': '[get-preview-docker-tag, manywheel-build-rocm-preview]',
        'image_suffix': preview_docker_image_suffix,
        'image_registry_host': preview_docker_registry_host}) %}
{%- endif %}
{%- for lane in libtorch_lanes %}

  libtorch-extract!{{ lane['suffix'] }}:
    name: ${{ matrix.build_name }}-extract
    if: !{{ lane['if'] }}
    needs: !{{ lane['needs'] }}
    runs-on: "mt-l-x86iavx512-16-128"
    container:
      image: !{{ lane['image_registry_host'] }}pytorch/${{ matrix.container_image }}:${{ matrix.container_image_tag_prefix }}!{{ lane['image_suffix'] }}
    timeout-minutes: 60
    strategy:
      fail-fast: false
      matrix:
        include:
        {%- for lt_config in lane['configs'] %}
          - desired_cuda: "!{{ lt_config['desired_cuda'] }}"
            gpu_arch_type: "!{{ lt_config['gpu_arch_type'] }}"
            gpu_arch_version: "!{{ lt_config['gpu_arch_version'] }}"
            libtorch_variant: "!{{ lt_config['libtorch_variant'] }}"
            libtorch_config: "!{{ lt_config['libtorch_config'] }}"
            source_wheel_build_name: "!{{ lt_config['source_wheel_build_name'] }}"
            build_name: "!{{ lt_config['build_name'] }}"
          {%- if 'container_image' in lt_config %}
            container_image: "!{{ lt_config['container_image'] }}"
            container_image_tag_prefix: "!{{ lt_config['container_image_tag_prefix'] }}"
          {%- endif %}
        {%- endfor %}
    env:
      DESIRED_CUDA: ${{ matrix.desired_cuda }}
      LIBTORCH_VARIANT: ${{ matrix.libtorch_variant }}
    steps:
      - name: Configure git safe directory
        run: git config --global --add safe.directory "$GITHUB_WORKSPACE"
      - name: Checkout PyTorch
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
          sparse-checkout: .ci/libtorch/
          show-progress: false
      - uses: !{{ common.download_artifact_action }}
        name: Download Wheel Artifact
        with:
          name: ${{ matrix.source_wheel_build_name }}
          path: "${{ github.workspace }}/wheel_artifact/"
      - name: Extract libtorch from wheel
        run: |
          set -eux
          # In container jobs the github.workspace context is the host path; the
          # mount is at $GITHUB_WORKSPACE. Use the env var so run steps and the
          # translated download/upload action paths resolve to the same dir.
          mkdir -p "${GITHUB_WORKSPACE}/libtorch_output"
          python3 .ci/libtorch/extract_libtorch_from_wheel.py \
            --wheel-dir "${GITHUB_WORKSPACE}/wheel_artifact" \
            --output-dir "${GITHUB_WORKSPACE}/libtorch_output" \
            --platform linux \
            --desired-cuda "$DESIRED_CUDA" \
            --libtorch-variant "$LIBTORCH_VARIANT"
      - name: Smoke test extracted libtorch
        run: |
          python3 .ci/libtorch/smoke_test_extract_libtorch.py \
            --output-dir "${GITHUB_WORKSPACE}/libtorch_output"
      - uses: !{{ common.upload_artifact_action }}
        if: always()
        with:
          name: ${{ matrix.build_name }}
          retention-days: 14
          if-no-files-found: error
          path: "${{ github.workspace }}/libtorch_output/"

{%- if branches == "nightly" %}

  libtorch-upload!{{ lane['suffix'] }}:
    name: ${{ matrix.build_name }}-upload
    if: !{{ lane['if'] }}
    permissions:
      id-token: write
      contents: read
{%- if lane['suffix'] == '-rocm-preview' %}
    needs: [get-preview-docker-tag, libtorch-extract!{{ lane['suffix'] }}]
{%- else %}
    needs: libtorch-extract!{{ lane['suffix'] }}
{%- endif %}
    uses: ./.github/workflows/_binary-upload.yml
    strategy:
      fail-fast: false
      matrix:
        include:
        {%- for lt_config in lane['configs'] %}
          - desired_cuda: "!{{ lt_config['desired_cuda'] }}"
            gpu_arch_type: "!{{ lt_config['gpu_arch_type'] }}"
            gpu_arch_version: "!{{ lt_config['gpu_arch_version'] }}"
            libtorch_variant: "!{{ lt_config['libtorch_variant'] }}"
            libtorch_config: "!{{ lt_config['libtorch_config'] }}"
            build_name: "!{{ lt_config['build_name'] }}"
        {%- endfor %}
    with:
      PYTORCH_ROOT: /pytorch
      PACKAGE_TYPE: libtorch
      DESIRED_CUDA: ${{ matrix.desired_cuda }}
{%- if lane['configs'][0].get('upload_subfolder') %}
      UPLOAD_SUBFOLDER: "!{{ lane['configs'][0]['upload_subfolder'] }}"
{%- endif %}
      GPU_ARCH_VERSION: ${{ matrix.gpu_arch_version }}
      GPU_ARCH_TYPE: ${{ matrix.gpu_arch_type }}
      LIBTORCH_CONFIG: ${{ matrix.libtorch_config }}
      LIBTORCH_VARIANT: ${{ matrix.libtorch_variant }}
      build_name: ${{ matrix.build_name }}
    secrets:
      github-token: ${{ secrets.GITHUB_TOKEN }}
      R2_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
      R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
      R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
{%- endif %}
{%- endfor %}