# Run benchmarks on a permanent HPU instance and return parsed results to Slab CI bot.
name: benchmark_hpu_common

on:
  workflow_call:
    inputs:
      command: # Use a comma separated values to generate an array
        type: string
        required: true
      op_flavor: # Use a comma separated values to generate an array
        type: string
        default: default
      bench_type:
        type: string
        default: latency
      precisions_set:
        type: string
        default: fast
      v80_pcie_dev:
        type: string
        default: 24
      v80_serial_number:
        type: string
        default: XFL12NWY3ZKG
    secrets:
      REPO_CHECKOUT_TOKEN:
        required: true
      SLAB_ACTION_TOKEN:
        required: true
      SLAB_BASE_URL:
        required: true
      SLAB_URL:
        required: true
      JOB_SECRET:
        required: true
      SLACK_CHANNEL:
        required: true
      BOT_USERNAME:
        required: true
      SLACK_WEBHOOK:
        required: true
      SSH_PRIVATE_KEY:
        required: true

env:
  CARGO_TERM_COLOR: always
  RESULTS_FILENAME: parsed_benchmark_results_${{ github.sha }}.json
  ACTION_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
  RUST_BACKTRACE: "full"
  RUST_MIN_STACK: "8388608"

permissions: {}

# zizmor: ignore[concurrency-limits] caller workflow is responsible for the concurrency

jobs:
  prepare-matrix:
    name: benchmark_hpu_common/prepare-matrix
    runs-on: ubuntu-latest
    outputs:
      command: ${{ steps.set_matrix_args.outputs.command }}
      op_flavor: ${{ steps.set_matrix_args.outputs.op_flavor }}
      bench_type: ${{ steps.set_matrix_args.outputs.bench_type }}
    env:
      INPUTS_COMMAND: ${{ inputs.command }}
      INPUTS_OP_FLAVOR: ${{ inputs.op_flavor }}
    steps:
      - name: Parse user inputs
        shell: python
        env:
          INPUTS_COMMAND: ${{ inputs.command }}
          INPUTS_OP_FLAVOR: ${{ inputs.op_flavor }}
          INPUTS_BENCH_TYPE: ${{ inputs.bench_type }}
        run: |
          import os

          inputs_command = os.environ["INPUTS_COMMAND"]
          inputs_op_flavor = os.environ["INPUTS_OP_FLAVOR"]
          inputs_bench_type = os.environ["INPUTS_BENCH_TYPE"]
          env_file = os.environ["GITHUB_ENV"]

          split_command = inputs_command.replace(" ", "").split(",")
          split_op_flavor = inputs_op_flavor.replace(" ", "").split(",")

          if inputs_bench_type == "both":
            bench_type = ["latency", "throughput"]
          else:
            bench_type = [inputs_bench_type, ]

          with open(env_file, "a") as f:
            for env_name, values_to_join in [
              ("COMMAND", split_command),
              ("OP_FLAVOR", split_op_flavor),
              ("BENCH_TYPE", bench_type),
            ]:
              f.write(f"""{env_name}=["{'", "'.join(values_to_join)}"]\n""")

      - name: Set martix arguments outputs
        id: set_matrix_args
        run: | # zizmor: ignore[template-injection] these env variable are safe
          {
            echo "command=${{ toJSON(env.COMMAND) }}";
            echo "op_flavor=${{ toJSON(env.OP_FLAVOR) }}";
            echo "bench_type=${{ toJSON(env.BENCH_TYPE) }}";
          } >> "${GITHUB_OUTPUT}"

  hpu-benchmarks:
    name: benchmark_hpu_common/hpu-benchmarks
    needs: prepare-matrix
    runs-on: v80-marais
    concurrency:
      group: ${{ github.workflow }}_${{ github.ref }}
      cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
    timeout-minutes: 1440  # 24 hours
    strategy:
      max-parallel: 1
      matrix:
        command: ${{ fromJSON(needs.prepare-matrix.outputs.command) }}
        op_flavor: ${{ fromJSON(needs.prepare-matrix.outputs.op_flavor) }}
        bench_type: ${{ fromJSON(needs.prepare-matrix.outputs.bench_type) }}
    steps:
      # Needed as long as hw_regmap repository is private
      - name: Configure SSH
        uses: webfactory/ssh-agent@a6f90b1f127823b31d4d4a8d96047790581349bd # v0.9.1
        with:
          ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}

      - name: Checkout tfhe-rs repo with tags
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8
        with:
          fetch-depth: 0
          persist-credentials: 'false'
          lfs: true
          token: ${{ secrets.REPO_CHECKOUT_TOKEN }}

      - name: Get benchmark details
        run: |
          COMMIT_DATE=$(git --no-pager show -s --format=%cd --date=iso8601-strict "${SHA}");
          {
            echo "BENCH_DATE=$(date --iso-8601=seconds)";
            echo "COMMIT_DATE=${COMMIT_DATE}";
            echo "COMMIT_HASH=$(git describe --tags --dirty)";
          } >> "${GITHUB_ENV}"
        env:
          SHA: ${{ github.sha }}

      - name: Install rust
        uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 # zizmor: ignore[stale-action-refs] this action doesn't create releases
        with:
          toolchain: nightly

      - name: Select HPU board
        run: |
          echo "V80_PCIE_DEV=${PCIE_DEV}" >> "${GITHUB_ENV}"
          echo "V80_SERIAL_NUMBER=${SERIAL_NUMBER}" >> "${GITHUB_ENV}"
        env:
          PCIE_DEV: ${{ inputs.v80_pcie_dev }}
          SERIAL_NUMBER: ${{ inputs.v80_serial_number }}

      - name: Run benchmarks
        run: |
          echo "${V80_PCIE_DEV} ${V80_SERIAL_NUMBER}"
          make pull_hpu_files
          make BIT_SIZES_SET="${PRECISIONS_SET}" BENCH_OP_FLAVOR="${OP_FLAVOR}" BENCH_TYPE="${BENCH_TYPE}" BENCH_PARAM_TYPE="${BENCH_PARAMS_TYPE}" bench_"${BENCH_COMMAND}"_hpu
        env:
          OP_FLAVOR: ${{ matrix.op_flavor }}
          BENCH_TYPE: ${{ matrix.bench_type }}
          BENCH_COMMAND: ${{ matrix.command }}
          PRECISIONS_SET: ${{ inputs.precisions_set }}

      - name: Parse results
        run: |
          python3 ./ci/benchmark_parser.py target/criterion "${RESULTS_FILENAME}" \
          --database tfhe_rs \
          --hardware "hpu_x1" \
          --backend hpu \
          --project-version "${COMMIT_HASH}" \
          --branch "${REF_NAME}" \
          --commit-date "${COMMIT_DATE}" \
          --bench-date "${BENCH_DATE}" \
          --walk-subdirs \
          --bench-type "${BENCH_TYPE}"
        env:
          REF_NAME: ${{ github.ref_name }}
          BENCH_TYPE: ${{ matrix.bench_type }}

      - name: Upload parsed results artifact
        uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
        with:
          name: ${{ github.sha }}_${{ matrix.bench_type }}_integer_benchmarks
          path: ${{ env.RESULTS_FILENAME }}

      - name: Checkout Slab repo
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8
        with:
          repository: zama-ai/slab
          path: slab
          persist-credentials: 'false'
          token: ${{ secrets.REPO_CHECKOUT_TOKEN }}

      - name: Send data to Slab
        shell: bash
        run: |
          python3 slab/scripts/data_sender.py "${RESULTS_FILENAME}" "${JOB_SECRET}" \
          --slab-url "${SLAB_URL}"
        env:
          JOB_SECRET: ${{ secrets.JOB_SECRET }}
          SLAB_URL: ${{ secrets.SLAB_URL }}
