diff --git a/.github/script/ci/aie_image_hash.py b/.github/script/ci/aie_image_hash.py new file mode 100644 index 000000000..bd17b5750 --- /dev/null +++ b/.github/script/ci/aie_image_hash.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. +"""The toolchain hash: the tag of the dev kit's kernel build image. + + aie_image_hash.py [ ] + +Prints the first 16 hex digits of the sha256 of the two files' normalised +text, flm-dev-kit/FLM_Xclbin/toolchain.lock and docker/aie-build.Dockerfile +by default (paths relative to the current directory, the repository root in +CI). Each file is hashed on its own and the hash is that of the two +digests, so a line moved from one file to the other is a new hash. +devkit-aie-image.yml tags ghcr.io/rocm/fastflowlm/aie-build +: with it, and devkit-xclbins.yml looks that tag up, so both +must compute it here. + +Normalised: line endings made "\\n", trailing whitespace stripped, and blank +lines and comment lines (first non-blank character "#") dropped, so an edit +to the comments of either file keeps the tag; devkit-aie-image.yml then +finds the tag published and neither rebuilds nor republishes the image (it +still runs the kernel check in it). Docker ignores those lines, and every +toolchain.lock line that is not KEY=VALUE is one of them. The exception is a +Dockerfile's parser directives (# syntax=, # escape=, # check=) at the top of +the file: they are comment-shaped but change the build, so they are kept. +Any other change, a value, an instruction, a directive, changes the hash. + +Two limits keep that true. A Dockerfile with a heredoc (RUN < list[str]: + return text.replace("\r\n", "\n").replace("\r", "\n").split("\n") + + +def has_heredoc(text: str) -> bool: + return any(HEREDOC.search(line) for line in lines_of(text) + if not line.lstrip().startswith("#")) + + +def check_lock(text: str) -> None: + """Raises ValueError naming the first line of that is not a "#" + comment at column 0, blank, or KEY=VALUE with no whitespace.""" + for n, line in enumerate(lines_of(text), 1): + if not LOCK_LINE.fullmatch(line): + raise ValueError(f"line {n} is not KEY=VALUE, a comment at column 0 or blank: {line!r}") + + +def normalise(text: str, directives: bool = False) -> str: + """ without blank and comment lines, each kept line stripped at its + end and ended by "\\n". With , the parser directives at the top + are kept.""" + out = [] + in_header = directives + for line in lines_of(text): + line = line.rstrip() + stripped = line.lstrip() + if not stripped: + continue + if stripped.startswith("#"): + if in_header and DIRECTIVE.match(stripped): + out.append(stripped) + continue + in_header = False + continue + in_header = False + out.append(line) + return "".join(f"{line}\n" for line in out) + + +def sha256(text: str) -> bytes: + return hashlib.sha256(text.encode("utf-8")).digest() + + +def toolchain_hash(lock_text: str, dockerfile_text: str) -> str: + """The first HASH_LEN hex digits of sha256(sha256(normalised lock) + + sha256(normalised Dockerfile)). Raises ValueError for a bad lock.""" + check_lock(lock_text) + if has_heredoc(dockerfile_text): + dockerfile = "\n".join(lines_of(dockerfile_text)) + else: + dockerfile = normalise(dockerfile_text, directives=True) + return hashlib.sha256(sha256(normalise(lock_text)) + sha256(dockerfile)).hexdigest()[:HASH_LEN] + + +def read(path: str) -> str: + return Path(path).read_bytes().decode("utf-8-sig") + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("lock", nargs="?", default=LOCK, help=f"default {LOCK}") + ap.add_argument("dockerfile", nargs="?", default=DOCKERFILE, help=f"default {DOCKERFILE}") + args = ap.parse_args(argv) + try: + print(toolchain_hash(read(args.lock), read(args.dockerfile))) + except (OSError, UnicodeDecodeError) as e: + print(f"aie_image_hash.py: {e}", file=sys.stderr) + return 1 + except ValueError as e: + print(f"::error file={args.lock}::{e}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/script/ci/test_aie_image_hash.py b/.github/script/ci/test_aie_image_hash.py new file mode 100644 index 000000000..8b5f805cc --- /dev/null +++ b/.github/script/ci/test_aie_image_hash.py @@ -0,0 +1,262 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. +"""Tests for aie_image_hash.py: python3 -m unittest discover -s ci -p 'test_*.py' -t ci""" + +from __future__ import annotations + +import io +import re +import sys +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import aie_image_hash as ah # noqa: E402 + +REPO = HERE.parents[2] + +LOCK = """\ +# Copyright header +# +# The toolchain, pinned. + +# Base image. +UBUNTU_IMAGE=ubuntu:24.04@sha256:00 +PEANO_VERSION=1.2.3 +""" + +DOCKERFILE = """\ +# syntax=docker/dockerfile:1 +# Copyright header +# +# What the image is. +ARG UBUNTU_IMAGE +FROM ${UBUNTU_IMAGE} AS build +ARG PEANO_VERSION +# Peano, by version. +RUN pip install llvm-aie==${PEANO_VERSION} \\ + && echo done +""" + + +def h(lock: str = LOCK, dockerfile: str = DOCKERFILE) -> str: + return ah.toolchain_hash(lock, dockerfile) + + +class HashFormat(unittest.TestCase): + def test_sixteen_hex(self): + self.assertRegex(h(), r"^[0-9a-f]{16}$") + + def test_current_files(self): + lock, dockerfile = REPO / ah.LOCK, REPO / ah.DOCKERFILE + if not (lock.is_file() and dockerfile.is_file()): + self.skipTest("not in a FastFlowLM checkout") + out = io.StringIO() + with redirect_stdout(out): + self.assertEqual(ah.main([str(lock), str(dockerfile)]), 0) + self.assertRegex(out.getvalue(), r"^[0-9a-f]{16}\n$") + + +class SameHash(unittest.TestCase): + def test_comment_edit(self): + self.assertEqual(h(LOCK.replace("pinned.", "pinned, with care."), + DOCKERFILE.replace("# Peano, by version.", "# Peano, the AIE compiler.")), h()) + + def test_comment_added_and_removed(self): + self.assertEqual(h(LOCK + "# A trailing note.\n", + DOCKERFILE.replace("# Peano, by version.\n", "")), h()) + + def test_indented_comment(self): + self.assertEqual(h(dockerfile=DOCKERFILE.replace("ARG PEANO_VERSION\n", + "ARG PEANO_VERSION\n # note\n")), h()) + + def test_blank_lines(self): + self.assertEqual(h(LOCK.replace("\n", "\n\n"), "\n" + DOCKERFILE + "\n \n"), h()) + + def test_trailing_whitespace(self): + self.assertEqual(h(LOCK.replace("pinned.\n", "pinned. \t\n"), + DOCKERFILE.replace("AS build\n", "AS build \n")), h()) + + def test_line_endings(self): + self.assertEqual(h(LOCK.replace("\n", "\r\n"), DOCKERFILE.replace("\n", "\r\n")), h()) + self.assertEqual(h(LOCK.replace("\n", "\r"), DOCKERFILE), h()) + + def test_no_final_newline(self): + self.assertEqual(h(LOCK.rstrip("\n"), DOCKERFILE.rstrip("\n")), h()) + + def test_blank_line_between_directives(self): + base = "# syntax=docker/dockerfile:1\n# check=error=true\nFROM x\n" + self.assertEqual(h(dockerfile=base.replace("\n# check", "\n\n# check")), h(dockerfile=base)) + + +class DifferentHash(unittest.TestCase): + def test_value_change(self): + self.assertNotEqual(h(LOCK.replace("1.2.3", "1.2.4")), h()) + + def test_key_added(self): + self.assertNotEqual(h(LOCK + "XRT_VERSION=2\n"), h()) + + def test_instruction_change(self): + self.assertNotEqual(h(dockerfile=DOCKERFILE.replace("echo done", "echo ok")), h()) + + def test_indentation_inside_instruction(self): + self.assertNotEqual(h(dockerfile=DOCKERFILE.replace(" && echo", " && echo")), h()) + + def test_directive_change(self): + self.assertNotEqual(h(dockerfile=DOCKERFILE.replace("dockerfile:1", "dockerfile:1.7")), h()) + + def test_directive_added_or_removed(self): + self.assertNotEqual(h(dockerfile="# escape=`\n" + DOCKERFILE), h()) + self.assertNotEqual(h(dockerfile="# check=error=true\n" + DOCKERFILE), h()) + self.assertNotEqual(h(dockerfile=DOCKERFILE.replace("# syntax=docker/dockerfile:1\n", "")), h()) + + def test_directive_spelling(self): + self.assertNotEqual(h(dockerfile=DOCKERFILE.replace("# syntax=", "# SYNTAX = ")), h()) + + def test_lock_and_dockerfile_kept_apart(self): + # The same line moved from one file to the other is a different input. + self.assertNotEqual(h(LOCK + "X=1\n", DOCKERFILE), h(LOCK, "X=1\n" + DOCKERFILE)) + self.assertNotEqual(h(LOCK.replace("PEANO_VERSION=1.2.3\n", ""), "PEANO_VERSION=1.2.3\n" + DOCKERFILE), + h()) + + +HEREDOC = """\ +# syntax=docker/dockerfile:1 +FROM x +COPY < list[str]: + """The "Read toolchain.lock" steps of a workflow, each up to the next step.""" + blocks = re.split(r"(?m)^\s*- name: ", text) + return [b for b in blocks if b.startswith("Read toolchain.lock")] + + def test_read_steps_call_the_script(self): + for name, count in self.EXPECTED.items(): + path = REPO / ".github" / "workflows" / name + if not path.is_file(): + self.skipTest("not in a FastFlowLM checkout") + text = path.read_text(encoding="utf-8") + with self.subTest(workflow=name): + self.assertIn(f"LOCK: {ah.LOCK}\n", text.replace("\r\n", "\n")) + self.assertIn(f"DOCKERFILE: {ah.DOCKERFILE}\n", text.replace("\r\n", "\n")) + steps = self.steps(text) + self.assertEqual(len(steps), count) + for step in steps: + self.assertIn(self.CALL, step) + self.assertNotIn("sha256sum", step) + + def test_steps_split(self): + text = (" steps:\n - name: Read toolchain.lock\n run: a\n" + " - name: Other\n run: sha256sum\n") + self.assertEqual(self.steps(text), ["Read toolchain.lock\n run: a\n"]) + + +class Cli(unittest.TestCase): + def test_files(self): + with tempfile.TemporaryDirectory() as d: + lock, dockerfile = Path(d) / "toolchain.lock", Path(d) / "Dockerfile" + lock.write_bytes(("\ufeff" + LOCK.replace("\n", "\r\n")).encode("utf-8")) + dockerfile.write_text(DOCKERFILE, encoding="utf-8", newline="\n") + out = io.StringIO() + with redirect_stdout(out): + self.assertEqual(ah.main([str(lock), str(dockerfile)]), 0) + self.assertEqual(out.getvalue(), h() + "\n") + + def test_missing_file(self): + with tempfile.TemporaryDirectory() as d: + err = io.StringIO() + with redirect_stderr(err): + self.assertEqual(ah.main([str(Path(d) / "nope"), str(Path(d) / "nope2")]), 1) + self.assertTrue(re.search(r"nope", err.getvalue())) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/devkit-aie-image.yml b/.github/workflows/devkit-aie-image.yml index 59ae3fc05..fa2c23f2d 100644 --- a/.github/workflows/devkit-aie-image.yml +++ b/.github/workflows/devkit-aie-image.yml @@ -13,16 +13,26 @@ name: Dev-kit AIE build image # (docker/aie-build-check.sh) and requires each one's PDI to be the # one the original toolchain made, byte for byte. A pull request that # changes the toolchain shows whether it still makes the shipped -# kernels +# kernels. If : is already published (and public), +# it skips the build and runs the kernel check in that image: a +# comment-only edit costs a pull, and a change to the check or the +# PDI list, which the hash does not cover, is still tested # publish main only (push, or workflow_dispatch run on main): builds again # (from the build job's cache) and pushes by digest with no tag, # pulls that digest and runs the same kernel check in it, and only # then tags it : and :latest. A cache miss that # makes a different image is checked like the one the build job -# tested, and an image that fails stays untagged. The toolchain -# hash is the first 16 hex digits of sha256(toolchain.lock + -# Dockerfile): a new tag for every change to either, an unchanged -# tag otherwise +# tested, and an image that fails stays untagged. On a push it +# first looks : up and stops if it exists: the +# same hash is the same build, so the tag is not moved to a new +# digest. workflow_dispatch always republishes (and moves the tag) +# +# The toolchain hash (.github/script/ci/aie_image_hash.py) covers +# toolchain.lock and the Dockerfile with their blank and comment lines dropped +# (the Dockerfile's parser directives kept): a new tag for every change to a +# value, an instruction or a directive, an unchanged tag for a comment-only or +# blank-line edit of either file. It covers every input of the build only +# while the Dockerfile copies nothing from the build context (docker/). # # Pull the image by digest, not by tag, wherever its output matters; the # digest goes in flm-dev-kit/FLM_Xclbin/toolchain.image (not toolchain.lock, @@ -43,12 +53,14 @@ on: - docker/aie-build* - flm-dev-kit/FLM_Xclbin/toolchain.lock - .github/workflows/devkit-aie-image.yml + - .github/script/ci/aie_image_hash.py push: branches: [main] paths: - docker/aie-build* - flm-dev-kit/FLM_Xclbin/toolchain.lock - .github/workflows/devkit-aie-image.yml + - .github/script/ci/aie_image_hash.py workflow_dispatch: # Read-only token; only publish, which runs on main only, adds packages: write. @@ -106,7 +118,7 @@ jobs: echo "::error file=${LOCK}::repeated: ${dups:-none}; ARGs with no value: ${missing:-none}; keys no ARG reads: ${unused:-none}" exit 1 fi - hash="$(cat "$LOCK" "$DOCKERFILE" | sha256sum | cut -c1-16)" + hash="$(python3 -I .github/script/ci/aie_image_hash.py "$LOCK" "$DOCKERFILE")" echo "hash=${hash}" >> "$GITHUB_OUTPUT" { echo 'build-args< + id: published + if: github.event_name != 'workflow_dispatch' + env: + HASH: ${{ steps.lock.outputs.hash }} + run: | + set -euo pipefail + if digest="$(docker buildx imagetools inspect "${IMAGE}:${HASH}" --format '{{json .Manifest}}' 2>/dev/null | jq -r '.digest // empty')" \ + && [[ "$digest" == sha256:* ]]; then + echo "ref=${IMAGE}@${digest}" >> "$GITHUB_OUTPUT" + echo "Already published: \`${IMAGE}@${digest}\`; the kernel check runs in it, no build." >> "$GITHUB_STEP_SUMMARY" + else + echo "${IMAGE}:${HASH} is not published (or not public): building it" + fi + - name: Build image + if: steps.published.outputs.ref == '' uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: docker @@ -135,7 +165,16 @@ jobs: # Each one's PDI must match docker/aie-build.pdi.sha256; the xclbin # around it differs on every build, so its hash is not compared. - name: Build the pinned kernels in the image - run: bash docker/aie-build-check.sh aie-build:ci + env: + PUBLISHED: ${{ steps.published.outputs.ref }} + run: | + set -euo pipefail + if [[ -n "$PUBLISHED" ]]; then + docker pull -q "$PUBLISHED" + bash docker/aie-build-check.sh "$PUBLISHED" + else + bash docker/aie-build-check.sh aie-build:ci + fi publish: needs: build @@ -153,17 +192,13 @@ jobs: with: persist-credentials: false - - name: Free disk space - run: | - sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup /opt/hostedtoolcache/CodeQL - df -h / - # The build job checked the file; this only reads it. - name: Read toolchain.lock id: lock run: | set -euo pipefail - echo "hash=$(cat "$LOCK" "$DOCKERFILE" | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT" + hash="$(python3 -I .github/script/ci/aie_image_hash.py "$LOCK" "$DOCKERFILE")" + echo "hash=${hash}" >> "$GITHUB_OUTPUT" { echo 'build-args</dev/null | jq -r '.digest // empty')" \ + && [[ "$digest" == sha256:* ]]; then + echo "ref=${IMAGE}@${digest}" >> "$GITHUB_OUTPUT" + { + echo "Unchanged toolchain hash \`${HASH}\`, already published; nothing pushed or tagged:" + echo + echo "\`${IMAGE}@${digest}\`" + } >> "$GITHUB_STEP_SUMMARY" + else + echo "${IMAGE}:${HASH} is not published: publishing it" + fi + + - name: Free disk space + if: steps.published.outputs.ref == '' + run: | + sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup /opt/hostedtoolcache/CodeQL + df -h / + # By digest, untagged: nothing points at it until the check below # passes. The labels are the Dockerfile's own (no metadata-action, whose # description label would be the repository's). - name: Push image by digest id: push + if: steps.published.outputs.ref == '' uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: docker @@ -197,6 +262,7 @@ jobs: # The pushed image itself, not the build job's: if the cache did not # make the same image, this is the one that has to build the kernels. - name: Build the pinned kernels in the pushed image + if: steps.published.outputs.ref == '' env: DIGEST: ${{ steps.push.outputs.digest }} run: | @@ -206,6 +272,7 @@ jobs: bash docker/aie-build-check.sh "${IMAGE}@${DIGEST}" - name: Tag : and :latest + if: steps.published.outputs.ref == '' env: DIGEST: ${{ steps.push.outputs.digest }} HASH: ${{ steps.lock.outputs.hash }} @@ -225,6 +292,7 @@ jobs: # without a token. A new package is private until someone changes it # (see the top of this file); this fails until then. - name: Check the image is public + if: steps.published.outputs.ref == '' env: DIGEST: ${{ steps.push.outputs.digest }} run: | diff --git a/.github/workflows/devkit-xclbins.yml b/.github/workflows/devkit-xclbins.yml index 00328c1e2..66822df73 100644 --- a/.github/workflows/devkit-xclbins.yml +++ b/.github/workflows/devkit-xclbins.yml @@ -25,9 +25,11 @@ name: Dev-kit xclbins # the job into its own limit before the shard uploads # image the image to build in: the digest in # flm-dev-kit/FLM_Xclbin/toolchain.image when that file exists; -# else ghcr.io/rocm/fastflowlm/aie-build: (the -# first 16 hex digits of sha256(toolchain.lock + Dockerfile), the -# tag devkit-aie-image.yml publishes) when the registry has it; +# else ghcr.io/rocm/fastflowlm/aie-build: +# (.github/script/ci/aie_image_hash.py: 16 hex digits of a sha256 +# of toolchain.lock and the Dockerfile, comments and blank lines +# left out; the tag devkit-aie-image.yml publishes) when the +# registry has it; # else built here from the same Dockerfile and build args, reading # devkit-aie-image.yml's layer cache (GitHub Actions cache scope # aie-build; only devkit-aie-image.yml writes it), and handed to @@ -158,7 +160,8 @@ jobs: id: lock run: | set -euo pipefail - echo "hash=$(cat "$LOCK" "$DOCKERFILE" | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT" + hash="$(python3 -I .github/script/ci/aie_image_hash.py "$LOCK" "$DOCKERFILE")" + echo "hash=${hash}" >> "$GITHUB_OUTPUT" { echo 'build-args<