diff --git a/.github/qualify-rocm/FEED.md b/.github/qualify-rocm/FEED.md new file mode 100644 index 0000000000..480b42e4b2 --- /dev/null +++ b/.github/qualify-rocm/FEED.md @@ -0,0 +1,447 @@ +# Qualification feed — published contract + +Every release run publishes its ROCm qualification records to the +**`qualification-data`** branch of this repository, in a fixed layout an +external dashboard can poll. This file is that contract. A copy is kept on the +branch as `qualification/SCHEMA.md`, refreshed on every publish, so the data and +its description never drift apart. Treat it as versioned (`schema_version`). + +The layout and field names match the +[lemonade-sdk/llama.cpp feed](https://github.com/lemonade-sdk/llama.cpp/blob/qualification-data/qualification/SCHEMA.md), +so one dashboard can read both. Where the two repositories' archives really +differ, the values differ too; +[Differences from the llama.cpp feeds](#differences-from-the-llamacpp-feeds) +lists every one. + +## Why a branch and not the releases + +The records are already attached to each release, but that copy cannot serve a +dashboard: + +- A release only holds what shipped. The dashboard needs every run, including + the ones whose ROCm archives were withheld. +- Reading history out of releases means one API call per release, and the + Releases API allows only 60 unauthenticated requests an hour. + +A file on a branch is one plain HTTP GET with no authentication and no rate +limit. The branch is only the transport; the contract below would hold +unchanged if the files moved to GitHub Pages, a bucket or a database. + +The branch is created by the first run that publishes; nothing has to be set up +by hand. + +## Layout + +``` +qualification/ + index.json # the feed: one compact row per archive per run + reports/.json # the full record for that row (drill-down) + latest/-rocm-.json # the newest full record for each archive + SCHEMA.md # a copy of this file +``` + +Public raw base URL (no authentication, about 5 minutes of CDN caching): + +``` +https://raw.githubusercontent.com/lemonade-sdk/stable-diffusion.cpp/qualification-data/qualification/ +``` + +The dashboard's one regular fetch is `.../qualification/index.json`. + +## One row per archive + +A release run builds six ROCm archives — Windows and Linux for each of ROCm +10.0, 10.1 and 10.2 (`ROCM_VERSIONS` in `build.yml`) — and each is qualified on +its own. Each one gets its own row, because an archive is what a user downloads +and what a bug report names. Rows from the same run share `run_id`; group on it +to show a run as a whole. + +Every archive the run was meant to build gets a row, including one whose build +failed (see [Placeholder rows](#placeholder-rows)). A run that built anything +therefore always has six rows. + +## `build_id` and re-runs + +``` +build_id = "--rocm-" e.g. 45012345678-win-rocm-10.1 +build_id = ".--rocm-" e.g. 45012345678.2-win-rocm-10.1 +``` + +The second form is used only for a re-run that built a different tag than the +rows already in the feed for that run (see below). + +Unique per archive per run. Publishing is an upsert keyed on `build_id`. A +re-run of a run keeps its `run_id`, so it replaces that run's rows and its +`reports/` files instead of adding new ones; the latest attempt's values win, +except one: when an earlier attempt of the run already shipped an archive for +the same tag and the re-run did not upload it again (it cannot replace a +published asset), the earlier attempt's row and report are kept, because they +describe the bytes users actually download. This needs the earlier attempt's +own feed publish to have succeeded; if it did not, the re-run's row is +published with `published: false`. + +"Re-run all jobs" resolves upstream again, so if upstream moved in the +meantime the re-run builds a different tag (and, if it passes, a new release). +Its rows then use `.-…` instead of replacing the rows of the +tag the earlier attempt built, so both stay in `index.json`. "Re-run failed +jobs" keeps the earlier attempt's resolved commit, so it never changes the tag. +`run_attempt` records which attempt published the rows. A new run has a new +`run_id` and adds new rows. + +## Which runs appear + +Runs of `.github/workflows/build.yml` whose `release` job runs: the scheduled +nightly runs, and manual runs with `create_release` ticked. Pass or fail, every +one of them is published. The records normally come from the `release` job; if +it stopped before writing them, `publish-qualification` builds them from the +Tier 0 and Tier 1 reports instead. + +A nightly whose release tag is already fully published builds nothing (see +[`last_check`](#last_check)). It adds no rows, but it does update `last_check`, +so "nothing changed upstream" can be told apart from "the nightly did not run". + +Not in the feed: + +- **Pull requests**, and manual runs without `create_release`. +- **A run that was cancelled.** +- **A run whose `resolve-upstream` job failed.** No upstream commit was + pinned, so nothing was built. + +## Example `index.json` + +```jsonc +{ + "schema_version": 2, + "repo": "lemonade-sdk/stable-diffusion.cpp", + "updated_at": "2026-11-23T14:52:10Z", // the most recent generated_at of any row + "last_check": { // what the most recent run decided + "status": "unchanged", // built | unchanged + "tag": "master-1106-abc1234", + "upstream_sha": "532d2c15c430a785a712b2d94281f04e733008a4", + "run_id": "45099999999", + "run_attempt": 1, + "run_url": "https://github.com/lemonade-sdk/stable-diffusion.cpp/actions/runs/45099999999", + "event": "schedule", + "checked_at": "2026-11-24T12:18:40Z" + }, + "builds": [ // newest run (highest run_id) first + // ... the other rows of run 45012345678 ... + + // A placeholder: this archive's build failed, so there was nothing to check. + { + "build_id": "45012345678-win-rocm-10.2", + "tag": "master-1106-abc1234", // the release tag; set even though nothing shipped + "upstream_sha": "532d2c15c430a785a712b2d94281f04e733008a4", + "artifact": "sd-master-abc1234-bin-win-rocm-10.2.0-x64.zip", // the name it would have had + "os": "win", + "rocm_version": "10.2", + "gfx_target": null, + "hardware_validated": false, + "gfx": { "requested": 0, "present": 0, "missing": [] }, // no archive, so nothing was audited + "generated_at": "2026-11-23T14:52:10Z", + "run_id": "45012345678", + "run_attempt": 1, + "run_url": "https://github.com/lemonade-sdk/stable-diffusion.cpp/actions/runs/45012345678", + "event": "schedule", + "build_result": "fail", // the windows-latest-rocm (10.2.0) job failed + "tests": { "passed": 0, "failed": 0, "warned": 0, "skipped": 0, "missing": 17, "not_applicable": 1, "total": 18 }, + "qualified": false, + "version_qualified": false, + "published": false, + "overall": "fail", + "tier0": "missing", // should have run, but there was no archive + "tier1": "missing", + "blocked_by": ["build failed"], + "blocking_tests": [], + "results": { + "T0.1": "missing", "T0.2": "missing", "T0.3": "missing", "T0.4": "missing", + "T0.5": "missing", "T0.6": "missing", "T0.7": "missing", "T0.8": "missing", + "T0.9": "missing", "T0.10": "missing", "T0.11": "missing", "T0.12": "not_applicable", + "T1.1": "missing", "T1.2": "missing", "T1.3": "missing", "T1.4": "missing", + "T1.5": "missing", "T1.6": "missing" + }, + "report_url": "reports/45012345678-win-rocm-10.2.json" + }, + + // The Linux archive of the same version, from the same run: it passed every + // check, but did not ship, because its Windows counterpart above never built. + { + "build_id": "45012345678-ubuntu-rocm-10.2", + "tag": "master-1106-abc1234", + "upstream_sha": "532d2c15c430a785a712b2d94281f04e733008a4", + "artifact": "sd-master-abc1234-bin-Linux-Ubuntu-24.04-x86_64-rocm-10.2.0.zip", + "os": "ubuntu", + "rocm_version": "10.2", + "gfx_target": "gfx1151", + "hardware_validated": true, + "gfx": { "requested": 24, "present": 24, "missing": [] }, + "generated_at": "2026-11-23T14:52:10Z", + "run_id": "45012345678", + "run_attempt": 1, + "run_url": "https://github.com/lemonade-sdk/stable-diffusion.cpp/actions/runs/45012345678", + "event": "schedule", + "build_result": "pass", + "tests": { "passed": 16, "failed": 0, "warned": 0, "skipped": 1, "missing": 0, "not_applicable": 1, "total": 18 }, + "qualified": false, // dropped before the final-archive check, which the + // release job requires, so it was never cleared to ship + "version_qualified": false, // its Windows counterpart has no record + "published": false, // so ROCm 10.2 was withheld from master-1106-abc1234 + "overall": "fail", + "tier0": "pass", + "tier1": "pass", + "blocked_by": ["T0.12 missing"], + "blocking_tests": [], + "results": { + "T0.1": "pass", "T0.2": "pass", "T0.3": "pass", "T0.4": "pass", + "T0.5": "pass", "T0.6": "pass", "T0.7": "pass", "T0.8": "pass", + "T0.9": "pass", "T0.10": "pass", "T0.11": "skip", + "T0.12": "not_applicable", // dropped before the final-archive check + "T1.1": "pass", "T1.2": "pass", "T1.3": "pass", "T1.4": "pass", + "T1.5": "pass", "T1.6": "pass" + }, + "report_url": "reports/45012345678-ubuntu-rocm-10.2.json" + }, + + // ... the rows of earlier runs ... + + // An archive that passed and shipped. + { + "build_id": "44999999999-win-rocm-10.1", + "tag": "master-1106-abc1234", // the release it was attached to + "upstream_sha": "532d2c15c430a785a712b2d94281f04e733008a4", + "artifact": "sd-master-abc1234-bin-win-rocm-10.1.0-x64.zip", + "os": "win", // win | ubuntu + "rocm_version": "10.1", // currently 10.0 | 10.1 | 10.2 + "gfx_target": "gfx1151", // the one gfx target Tier 1 ran on; null when Tier 1 did not run + "hardware_validated": true, // Tier 1 confirmed it ran on a gfx_target GPU + "gfx": { "requested": 20, "present": 20, "missing": [] }, + "generated_at": "2026-11-22T14:47:31Z", // ISO-8601 UTC, when this row's record was written + "run_id": "44999999999", + "run_attempt": 1, // the attempt that published this row + "run_url": "https://github.com/lemonade-sdk/stable-diffusion.cpp/actions/runs/44999999999", + "event": "schedule", // schedule | workflow_dispatch + "build_result": "pass", // pass | fail | cancelled | skipped | unknown + "tests": { "passed": 15, "failed": 0, "warned": 0, "skipped": 3, "missing": 0, "not_applicable": 0, "total": 18 }, + "qualified": true, // passed every gating check required of it: Tier 0, + // Tier 1 and T0.12. Not whether it shipped. + "version_qualified": true, // both archives of ROCm 10.1 exist and qualified + "published": true, // this run attached it to the release + "overall": "pass", // pass | warn | fail; fail exactly when qualified is false + "tier0": "pass", // pass | warn | fail | missing + "tier1": "pass", // pass | warn | fail | missing + "blocked_by": [], // why it did not qualify, e.g. ["tier1 missing"] + "blocking_tests": [], // the gating tests that failed, e.g. ["T1.2"] + "results": { + "T0.1": "pass", "T0.2": "pass", "T0.3": "pass", "T0.4": "skip", + "T0.5": "pass", "T0.6": "skip", "T0.7": "skip", "T0.8": "pass", + "T0.9": "pass", "T0.10": "pass", "T0.11": "pass", "T0.12": "pass", + "T1.1": "pass", "T1.2": "pass", "T1.3": "pass", "T1.4": "pass", + "T1.5": "pass", "T1.6": "pass" + }, + "report_url": "reports/44999999999-win-rocm-10.1.json" + } + ] +} +``` + +### Field notes + +- **`results`** has one entry per test: T0.1–T0.12 and T1.1–T1.6, as listed in + [README.md](README.md). A test id added to the suite later appears here as + soon as it runs, so the failure-frequency and heatmap views can be built from + `index.json` alone. A retired test stops appearing in new rows and keeps its + value in older ones; its id is never reused. The values: + - `pass`: the check ran and passed. + - `fail`: the check ran and found a problem. It blocks the archive only if + the test is gating; T1.5 never blocks. + - `warn`: the check ran and found something worth recording that does not + block, e.g. upstream test programs shipped in the archive (T0.1). + - `skip`: the check ran but could not apply, e.g. T0.4, T0.6 and T0.7 on + Windows, and T0.11 on Linux, which bundles no ROCm. + - `missing`: the check should have run for this archive and did not. It + blocks the archive (see `qualified`). + - `not_applicable`: the check was never going to run for this archive. + T0.12 checks the final archive inside the release job, and only runs on + archives still in the release at that point. An archive dropped before + then — because the other archive of its ROCm version was missing — or + never built has it `not_applicable`. +- **`tests`** counts the values in `results`, so + `passed + failed + warned + skipped + missing + not_applicable == total` + always holds. Use `qualified`, not the counts, to decide pass or fail. +- **`qualified`** is the verdict for this one archive: Tier 0 ran and no gating + Tier 0 check failed, Tier 1 ran and no gating Tier 1 check failed, and the + release job's final-archive check (T0.12) passed. A `warn` does not block, + and non-gating tests never affect it. It does not say whether the archive + shipped (`published`). +- **`version_qualified`** is `true` when both archives of this ROCm version — + Windows **and** Linux — exist and qualified. A version ships only as a pair, + so an archive can have `qualified: true` and `version_qualified: false` + because its counterpart failed a check or never built. `null` means the run + recorded no decision. +- **`published`** says whether this run attached this archive to the release + `tag`. It can be `false` even when `version_qualified` is `true`: an upload + can fail, and a nightly filling the gaps of an incomplete release never + replaces an archive that release already holds, so it reports `false` for + those. `published` describes what this run shipped, not what the release + holds today. +- **`overall`** is `fail` exactly when `qualified` is `false`. Otherwise it is + the worst result of the gating tests that ran: `warn` if any of them warned, + else `pass`. +- **`tier0` / `tier1`** are each tier's result: `pass`, `warn` or `fail` when + the tier ran, and `missing` when it did not. +- **`tag`** is the release tag this run pinned, `master--`. Every row of a run has it, whether or not anything + shipped. The asset names drop the count: `sd-master--…`. +- **`build_result`** is how the archive's build job (`ubuntu-latest-rocm` or + `windows-latest-rocm`) ended: `pass`, `fail` (including a timeout), + `cancelled`, `skipped`, or `unknown` when the run's job list could not be + read. Each build ends on its own: one ROCm version failing does not cancel + the others. +- **`run_attempt`** is the attempt of the run that published the row. Rows of + one run normally share it; a row kept from an earlier attempt that shipped + its archive keeps that attempt's number. For the run's latest attempt, read + `last_check.run_attempt`. +- **`generated_at`** is when the row's record was written. A re-run writes it + again, later than any run that started after it, so order runs by `run_id` + (rows are already newest-run-first) rather than by `generated_at`. +- **`blocked_by`** gives the reasons the archive did not qualify. It is empty + when it qualified. The values: + - `tier0=fail`: a gating Tier 0 check failed; + - `tier0 missing`: no Tier 0 report; + - `tier1=fail`: a gating Tier 1 check failed; + - `tier1 missing`: no Tier 1 report, e.g. the GPU runner was offline; + - `T0.12 missing`: the release job's final-archive check did not run on it; + - on placeholder rows only: `build failed`, `build cancelled`, `build skipped` + or `no report`. +- **`blocking_tests`** lists the gating tests that failed; empty when none did. +- **`gfx`** summarises the check that every gfx target was compiled into the + GPU code (T0.3): how many were requested, how many are present, and the + names of any that are missing. +- **`gfx_target`** is the gfx target Tier 1 ran on, and `null` when Tier 1 did + not run. **`hardware_validated`** is `true` only when Tier 1 confirmed the GPU + it ran on is that target (T1.3). Every other target in `gfx.requested` was + only checked for presence, never run. Don't present those as tested. +- **`report_url`** is relative to the base URL; it holds every check's + `status`, `gating`, `error` and `details`. + +### Placeholder rows + +An archive with no record at all gets a placeholder row. This happens when its +build failed, so there was nothing to check, or when no check reported on it. +In a placeholder row: + +- every test is `missing` except T0.12, which is `not_applicable` (or + `missing` in the rare case the archive reached the release job's final-archive + check but the check itself could not run, e.g. its metadata was lost); + `tier0` and `tier1` are `missing`; `qualified`, `version_qualified` and + `published` are `false`; and `overall` is `fail`; +- `blocked_by` follows `build_result`: `build failed`, `build cancelled`, + `build skipped`, or `no report` when the build passed or its result is + `unknown`; +- `gfx` is all zero and empty: there is no binary, and the target list lives in + the build job; +- `gfx_target` is `null` and `hardware_validated` is `false`; `tag` and + `artifact` are the ones the archive would have had. + +The first row of the [`index.json`](#example-indexjson) example is a placeholder. + +### `last_check` + +A top-level object, not a row: what the most recent nightly or release run +decided. + +- **`status`** is `built` when the run built and qualified archives (its rows + are in `builds`), and `unchanged` when a nightly found the release for its tag + already holding every backend family and built nothing. The tag only changes + when upstream stable-diffusion.cpp or this repository changes, so a run of + `unchanged` nights means nothing new has landed upstream. +- **`tag`** and **`upstream_sha`** are what that run resolved — for an + `unchanged` night, the release that was already complete. +- **`run_id`**, **`run_attempt`**, **`run_url`**, **`event`** identify the run; + **`checked_at`** is when it published. + +Like `latest/`, `last_check` never moves back: re-running an older run leaves a +newer run's `last_check` in place. + +The freshest row in `builds` can therefore be days old while `last_check` is +from this morning; that is the normal state when upstream is quiet. + +## `reports/.json` + +The `qualification-.json` record exactly as `aggregate.py` wrote it (`kind: "qualification_record"`): +- the `build` metadata (archive, `os`, `rocm_version`, `sdcpp_tag`, + `upstream_sha`, `gfx_target`, `hardware_validated`, the run, and for Tier 1 + `runner_env`: the machine's driver versions, kernel, and any HIP runtime + found in System32 or system ROCm), +- `overall`, +- `promoted`, +- `promotion.blocked_by` (why this archive did not qualify) and + `promotion.version_blocked_by` (why its ROCm version was withheld because of + the other archive, e.g. `["win: tier1=fail"]` or `["win: no report"]`, so an + archive that passed its own checks but did not ship still says why), +- raw `counts`, +- the `gfx` audit, and +- `tiers` with every test. + +The same content is attached to the release. Its own `build.build_id` (`@`) differs from the feed's `build_id`; use the feed's. + +For a placeholder row it is a placeholder (`kind: "qualification_placeholder"`) with the same top-level fields: +- `build` metadata, +- `overall: "fail"`, +- `promoted: false`, +- `promotion.blocked_by`, +- `build_result` (in the feed's vocabulary), +- the empty `gfx` block, +- zero `counts` and +- empty `tiers`. + +## `latest/-rocm-.json` + +The newest full record for one archive (for example `latest/win-rocm-10.1.json`), +for status tiles that want the current state without scanning the index. A +placeholder is written here too, so a tile shows a failing build instead of the +last good one. It is replaced only by a record from the same run or a newer one +(a higher `run_id`), so re-running an old run cannot move it backwards. + +## Differences from the llama.cpp feeds + +This feed has one archive per ROCm version, like lemonade-sdk/llama.cpp's, with +ROCm's math libraries installed separately by the user. Everything else in a row +means the same as there, except: + +| Field | this repository | lemonade-sdk/llama.cpp | lemonade-sdk/llamacpp-rocm | +|---|---|---|---| +| `schema_version` | `2` | `2` | `1` (same row shape) | +| `build_id` | `--rocm-` | same | `--rocm-` | +| rows per run | 6 | 8 | 20 | +| `tag` | `master--`; set on every row | llama.cpp build number; set on every row | its own release tag; `null` unless `published` | +| `artifact` | the release asset name (`sd-master--…`) | the release name | the untagged CI name unless `published` | +| `os` | `win` \| `ubuntu` | `win` \| `ubuntu` | `windows` \| `ubuntu` | +| `rocm_version` | `10.0` \| `10.1` \| `10.2` | `7.14` \| `10.0` \| `10.1` \| `10.2` | full nightly, e.g. `10.3.0a20261102` | +| `results` keys | T0.1–T0.12, T1.1–T1.6 — this repository's own ids | T0.1–T0.8, T0.11, T0.12, T1.1–T1.5 | T0.1–T0.3, T0.5–T0.9, T0.11, T0.13, T1.1–T1.6 | +| missing Tier 1 | blocks (`tier1 missing`) | does not block | blocks | +| final-archive check | T0.12; missing blocks | T0.11; missing does not block | T0.11; missing blocks | +| `hardware_validated` | `true` only when T1.3 confirmed the GPU | `true` whenever Tier 1 ran | `true` whenever Tier 1 ran | +| `last_check` | yes | — | — | +| placeholder `gfx` | all zero | all zero | requested targets, all in `missing` | + +Test ids are per repository: the same id names different checks in different +feeds (T0.11 is the final-archive check in llama.cpp and the bundled HIP runtime +check here). Compare checks across repositories by name, not by id. + +## Versioning and growth + +Bump `schema_version` on any breaking change to `index.json` or the row shape. +Adding a field is not breaking (`last_check` was added without a bump). The +dashboard should read `schema_version` and show a notice, rather than break, on +a version it does not know. + +The `schema_version` inside each record under `reports/` and `latest/` is a +separate number. It versions the record written by `aggregate.py` (`report.py` +sets it), not `index.json`, so the two do not have to match and change +independently. + +`index.json` grows by six rows per run that builds, and by nothing on a night +when upstream did not change. That is comfortable to poll for a long time, +especially compressed. If it ever is not, older rows will move into per-month +files under a new `schema_version`. diff --git a/.github/qualify-rocm/README.md b/.github/qualify-rocm/README.md new file mode 100644 index 0000000000..51b32d8fe1 --- /dev/null +++ b/.github/qualify-rocm/README.md @@ -0,0 +1,364 @@ +# ROCm build qualification + +Verification of the ROCm archives this repository publishes. Driven from +`.github/workflows/build.yml`, but every script here can be run by hand +against a downloaded release asset, which is the easiest way to understand what +any of them does. + +The design follows [lemonade-sdk/llama.cpp](https://github.com/lemonade-sdk/llama.cpp/tree/lemonade/.github/qualify-rocm) +so both repositories behave the same way and feed the same dashboard. Test ids +are this repository's own, numbered from T0.1 and T1.1; they do not share +meanings with llama.cpp's. + +## Why this exists + +A broken ROCm build does not look broken. + +stable-diffusion.cpp treats a GPU it cannot use as a non-event: it writes a line +to the log saying no ROCm device was found, and carries on with the CPU. So a +build whose GPU support is completely broken still starts, still answers every +request, and still returns a perfectly good image. It is simply ten times +slower, with no error anywhere. On a Strix Halo the same 512x512 image takes +about 4 seconds on the GPU and about 35 on the CPU. + +The same quietness applies further up. If the compiler produces GPU code for +only some of the gfx targets it was asked to cover, nothing reports an error — +the output file is still created, with the expected name and a plausible size. +And packaging mistakes — a leaked build-machine path, a missing licence, a HIP +runtime from the wrong ROCm version — are invisible until a user's machine +trips over them. + +All of those ship green unless something deliberately looks inside the +archive. That is what this suite is for. + +## What the archives contain + +| | Windows (`sd-<…>-bin-win-rocm--x64.zip`) | Linux (`sd-<…>-bin-Linux-Ubuntu-24.04-x86_64-rocm-.zip`) | +|---|---|---| +| Layout | flat | `build/bin/`, versioned `.so` names stored as symlinks | +| GPU code | linked into `stable-diffusion.dll` | `libggml-hip.so`, a plug-in ggml loads at run time | +| CPU code | linked into `stable-diffusion.dll` | `libggml-cpu-*.so`, one per CPU generation | +| HIP runtime | bundled: `amdhip64_7.dll`, `amd_comgr.dll`, `rocm_kpack.dll` | not bundled | +| ROCm math libraries (hipBLAS, hipBLASLt, rocBLAS) | not bundled | not bundled | + +The math libraries come from the user's ROCm install, which Lemonade sets up +automatically (`rocm[libraries,device-]`), exactly as for +lemonade-sdk/llama.cpp. Without them sd-server cannot start at all: on Windows +it exits with `0xC0000135` ("DLL not found") before printing a line. + +The Windows HIP runtime is bundled because Windows searches a program's own +folder for DLLs before anything else, so the bundled copy wins over the older +`amdhip64_7.dll` the AMD display driver puts in System32 (TheRock#7691). Running +sd-server against that driver copy instead crashes it with an access violation +(`0xC0000005`) before it serves anything. + +## Tiers + +| Tier | Runs on | Blocks a release? | +|---|---|---| +| Tier 0 — static checks | standard GitHub runners (`ubuntu-24.04`, `windows-2025`) | yes, affected ROCm version only | +| Tier 1 — GPU inference | self-hosted Strix Halo (gfx1151) machines, Windows and Linux | yes, affected ROCm version only | + +Both tiers run on every trigger — the nightly schedule, manual runs and pull +requests. The one exception is that Tier 1 is skipped for a pull request opened +from a fork, so code from outside this repository never runs on the self-hosted +machines. + +Each tier runs one job per published archive — two operating systems by three +ROCm versions — so a failure is reported against the exact archive it affects. + +Each ROCm version is treated as an independent product. A consumer downloads +exactly one of them, so a failure in one version removes only that version's +Windows and Linux pair; the other versions, and every non-ROCm backend (CPU, +Vulkan, CUDA, Metal), publish as normal. The release job then exits non-zero so +the gap is noticed. + +A version ships only when, for both of its archives, Tier 0 and Tier 1 both +reported and neither failed, and the final-archive check (T0.12) passed. Unlike +lemonade-sdk/llama.cpp, a Tier 1 that never reported — the GPU runner was +offline, or ROCm failed to install — blocks the version rather than letting it +ship untested. A `warn` never blocks. + +On a pull request nothing is published at all, so there is no aggregate step to +pass judgement. Each job therefore fails on its own as soon as a check fails — +otherwise a pull request would report success no matter what the checks found. + +### Tier 0 — `tier0_static.py`, `check_final.py` + +Runs against the archive as it will be published, not against the build +directory, because most of what it looks for only exists once the files have +been packaged. + +| ID | Check | Blocks release | +|---|---|---| +| T0.1 | every file a user needs is present: sd-cli, sd-server, the stable-diffusion and ggml libraries, both licence files, and on Windows the bundled HIP runtime | yes | +| T0.2 | the file holding the GPU code exists and is big enough to hold it | yes | +| T0.3 | that file really contains code for every gfx target the build asked for (on Linux, `libstable-diffusion.so`'s own GPU code too) | yes | +| T0.4 | the CPU backend variants are present (Linux; Windows links the CPU backend in) | yes | +| T0.5 | every library the archive needs is either inside it, part of the OS, or a ROCm library | yes | +| T0.6 | the archive still runs on the oldest Linux release we support | yes | +| T0.7 | no build-machine folder left in the Linux binaries' library search path (RUNPATH): only `$ORIGIN` | yes | +| T0.8 | `sd-server` still accepts the flags Lemonade launches it with | yes | +| T0.9 | `sd-server` reports the upstream commit this run pinned | yes | +| T0.10 | the ROCm libraries the archive needs exist in the ROCm a user installs | yes | +| T0.11 | the bundled HIP runtime is byte-identical to that ROCm version's own copy | yes | +| T0.12 | the finished archive reads back intact and is the one the build job produced and the qualify jobs tested | yes | + +T0.12 comes from `check_final.py`, which runs in the release job on the archives +about to be uploaded. It compares each archive's SHA-256 with the one its build +job recorded, so the bytes that ship are the bytes every other check and Tier 1 +ran on. The release job never repacks or merges an archive; it uploads it under +the name the build job gave it, which is also the name Lemonade downloads. + +T0.7 exists because the HIP link writes the build machine's pip-installed ROCm +folder (`…/_rocm_sdk_devel/lib`) into every Linux binary's library search path. +The build job now resets it to `$ORIGIN` with `patchelf`; every Linux ROCm zip +published before that carried the leaked path. + +### Tier 1 — `tier1_gpu.py` + +Starts `sd-server` from the archive with the flags Lemonade uses, loads the +model Lemonade validates stable-diffusion.cpp with (SD-Turbo-GGUF), and asks it +for one 512x512 image over the same OpenAI-style endpoint Lemonade calls. + +| ID | Check | Blocks release | +|---|---|---| +| T1.1 | the server starts and serves its web page | yes | +| T1.2 | the GPU actually did the work | yes | +| T1.3 | the GPU sd-server found is the gfx target this runner validates | yes | +| T1.4 | the image is a PNG of the requested size that decodes and is not blank | yes | +| T1.5 | the same request again gives identical bytes | no | +| T1.6 | the running server loaded the bundled HIP runtime from the archive and every other ROCm library from the user's ROCm install | yes | + +**T1.2 is the one that matters.** Every other check in this tier passes +perfectly well when the GPU was never used at all — the image is simply slower +to arrive. How it avoids being fooled is described below. + +T1.3 is what makes a record say `hardware_validated`. Only gfx1151 has test +hardware today; the target comes from the workflow, so adding a runner with +another GPU is one more Tier 1 leg, not a change to the scripts. + +T1.5 is recorded but never blocks a release. On the gfx1151 runners sd-server +is in fact bit-for-bit repeatable, so a difference is worth a look, but GPUs do +not promise it and treating it as a release gate would block good builds. + +T1.6 catches the case behind Lemonade #3718: a HIP runtime from somewhere else — +the display driver's copy in System32, a system ROCm under `/opt/rocm` — mixed +with this archive's ROCm, which made the GPU invisible and sent every request to +the CPU. + +## How some of this works + +### Counting the gfx targets inside the GPU code + +`binfmt.py` searches the file holding the GPU code for the short text labels the +compiler writes next to each gfx target's code, rather than asking an AMD tool to +list them. + +The reason is that the GPU code lives in a named block inside the file, and +Windows shortens those names to eight characters once a program is linked — so +a block Linux calls `.hip_fatbin` is called `.hip_fat` there. Any tool asked to +find the block by name comes back empty on Windows. Searching the file's bytes +does not care what the block is called, so one implementation covers both +operating systems and needs no AMD tooling installed, which in turn means the +check can run on an ordinary runner against the archive we actually ship. + +Two deliberate behaviours: + +- Finding **no** gfx targets at all is a failure, not a pass. A check that can + silently come up empty is worse than no check. +- The number of entries per target is reported, not just which targets are + present. The compiler writes one entry per source file, so in a healthy build + every target has the same count (141 in `libggml-hip.so`, 150 in the Windows + `stable-diffusion.dll`); a target with a lower count was built into only part + of the project, which a present/absent check would miss. + +The expected list is each build job's own `gpu_targets`, carried in the +`qualify-meta--rocm-.json` it uploads next to the archive, so each +operating system is audited against exactly what it was compiled for. + +### Proving the GPU was used + +Two things make this harder than it looks, and both have to be handled or T1.2 +reports the wrong answer. + +**The server leaves out most of the evidence by default.** At its default log +level sd-server reports which device it found, but none of the weight-buffer and +compute-buffer lines T1.2 requires (older upstream versions also printed a +weight-placement summary at that level, newer ones do not). That is why Tier 1 launches it with `-v`, which +Lemonade itself passes only in debug mode (as its CI runs it). Without that +flag T1.2 finds no evidence and fails a perfectly good build — and says so, +naming the missing flag. T0.8 checks every night that `-v` still exists. + +**The obvious evidence is not evidence.** stable-diffusion.cpp prints: + +``` +[V] Initializing backend: ROCm0 +``` + +It is the line Lemonade's own validator looks for, but it is printed *before* +the device is started, so it also appears when the device then fails to +initialise and everything falls back to the CPU. + +So T1.2 requires all three of these, each naming a ROCm device or VRAM, which +cannot appear unless a ROCm device was found and used: + +``` + Device 0: AMD Radeon(TM) 8060S Graphics, gfx1151 (0x1151), VMM: no, ... +[V] model manager prepared params backend buffers (1411.07 MB, 686 tensors, 2 blocks, VRAM) on ROCm0 +[V] unet compute buffer size: 87.86 MB(VRAM) on ROCm0 (peak across 1 segment) +``` + +The weights must be in VRAM on a ROCm device with none of them left on the CPU, +and the compute buffer must be larger than zero. The patterns match any device +index (`ROCm0`, `ROCm1`, …), so a machine with two GPUs passes as long as all +the work landed on GPUs. + +These three were picked because upstream kept them while it changed its other +logging. Upstream also prints a per-component placement summary, but has +already renamed it once — `total params memory size = … (VRAM …, RAM …)` up to +master-1106, `load_unet: 1411.02 MiB params -> ROCm0` from master-1117 — and a +check that required it failed every good build the night it changed. So that +summary is only extra evidence: recorded when present, and a failure only if it +shows a component on the CPU. + +The same sd-server with the GPU hidden prints instead: + +``` +ggml_cuda_init: failed to initialize ROCm: no ROCm-capable device is detected +[V] model manager prepared params backend buffers (1411.02 MB, 686 tensors, 1 blocks, RAM) on CPU +[V] unet compute buffer size: 1.93 MB(RAM) on CPU (peak across 1 segment) +``` + +and still returns a valid image. T1.2 fails it on every count. + +### Which ROCm the checks verify against + +The archives do not contain ROCm's math libraries. A user installs them +separately, and stable-diffusion.cpp loads them at run time. So "are this +archive's libraries available?" depends entirely on what the user installed. + +Checking against the ROCm used to *build* the archive would always pass — those +are the exact files it was compiled against. `install_rocm.py` therefore +installs the components an end user gets (the kernels for their GPU) rather +than the components a build needs (compilers), and T0.10, T0.11 and Tier 1 all +verify against that. Everything goes into a throwaway virtual environment under +the runner's temporary directory; nothing is installed system-wide. + +### Which Linux versions the archive runs on + +Every Linux program records the newest version of the system C library it +relied on, and refuses to start on a machine with an older one. Newer Linux +releases ship newer versions of that library, so building on a newer Linux +silently narrows who can run the result — nothing warns about it at build time. + +T0.6 reads that number out of the archive and compares it against +`SUPPORTED_GLIBC` in `tier0_static.py`, which is set to what the oldest Linux +release we support provides (Ubuntu 24.04, glibc 2.39). The check passes today +and would fail if the build job's runner image moved to a newer Linux without +that decision being made deliberately. + +### Nightlies with nothing new + +The release tag is `master--`, so it only +changes when upstream stable-diffusion.cpp or this repository changes. A nightly +first checks whether the release for its tag already holds every backend family +and `checksums.txt`; if it does, the whole run is skipped, and only a +`last_check` of `"unchanged"` is written to the feed. If the release is missing +anything — say ROCm 10.2 was withheld the night before — the nightly rebuilds, +re-qualifies, and uploads only the archives that are missing. An archive already +in a release is never replaced, because Lemonade may already be pinned to it. +`checksums.txt` is rebuilt from GitHub's own digests on every run. When the run +re-qualifies an archive that is still withheld, its qualification record is +replaced with the new one (an archive whose build produced no report this run +keeps its previous record); the record of an archive that shipped is never +touched. + +## Running by hand + +Everything here works against a downloaded release asset on a normal machine, +which is the quickest way to check a CI result yourself. + +```bash +# Static checks on a downloaded release asset +python3 .github/qualify-rocm/install_rocm.py --version 10.1.0 --arch gfx1151 +python3 .github/qualify-rocm/tier0_static.py \ + --archive sd-master-abc1234-bin-win-rocm-10.1.0-x64.zip \ + --os win --rocm-version 10.1.0 \ + --gpu-targets "gfx1010;gfx1011;...;gfx1201" \ + --upstream-sha --run-binaries \ + --rocm-dirs "" \ + --output tier0.json + +# Combine reports into one record per archive and decide what may ship +python3 .github/qualify-rocm/aggregate.py \ + --fragments-dir ./fragments --tag master-1106-abc1234 \ + --records-dir ./qualification --fail-on-no-promote +``` + +To run the GPU checks on a machine with a supported AMD GPU, install a +user-style ROCm first — it goes into a throwaway folder and changes nothing +system-wide — then point the inference check at the archive. The model is +downloaded and verified automatically if it is not already cached. + +```bash +python3 .github/qualify-rocm/install_rocm.py --version 10.1.0 --arch gfx1151 +# install_rocm.py prints the runtime directories; pass them through --rocm-dirs, +# or let the workflow's exported ROCM_RUNTIME_DIRS be picked up automatically. + +python3 .github/qualify-rocm/tier1_gpu.py \ + --archive sd-master-abc1234-bin-win-rocm-10.1.0-x64.zip \ + --rocm-version 10.1.0 --rocm-dirs "" \ + --output tier1.json +``` + +A useful sanity check on T1.2 itself is to start sd-server by hand the same way +(the ROCm folders first on `PATH` or `LD_LIBRARY_PATH`, `-v`) with +`HIP_VISIBLE_DEVICES=-1` set: it still returns an image, but its log has none of +the three lines above. Setting the variable around `tier1_gpu.py` does nothing, +because the script deliberately removes it (and the other settings listed in +`FOREIGN_ROCM_ENV`) before starting sd-server. + +Each run writes a `qualification-.json` record that is attached to the +release. It lists which gfx targets the archive contains code for, which of them +were actually tested on hardware, and the result of every check — so questions +like "was this gfx target ever verified in that build?" stay answerable long after +the CI logs have expired. + +## Published feed + +The release job's records are also published, pass or fail, to the +`qualification-data` branch by `publish_qualification.py`, so a dashboard can +follow the history of every run without reading each release. An archive whose +build failed gets a placeholder row, so a missing archive shows up as a failure +rather than a gap, and a nightly skipped for lack of changes is recorded too. +The layout and every field are described in [FEED.md](FEED.md). + +## Files + +| File | Role | +|---|---| +| `tier0_static.py` | Tier 0 checks T0.1–T0.11 | +| `check_final.py` | T0.12, in the release job | +| `tier1_gpu.py` | Tier 1 checks T1.1–T1.6 | +| `install_rocm.py` | installs a user-style ROCm runtime for Tier 0 and Tier 1 | +| `binfmt.py` | reads gfx targets, imports, RUNPATH and glibc out of ELF and PE files | +| `archive.py` | unpacks an archive the way a user's unzip would | +| `report.py` | the fragment and record format every tier writes | +| `aggregate.py` | merges fragments per archive and decides which ROCm versions ship | +| `release_assets.py` | which assets make up each backend family; used to drop incomplete families and to skip unchanged nightlies | +| `release_notes.py` | renders the release notes from the attached assets | +| `publish_qualification.py` | writes the `qualification-data` feed | + +## Out of scope + +- **Performance.** Tracked downstream against these same artifacts; a second + set of numbers here would split the history. +- **Image quality.** T1.4 covers "the output is a real picture", which is what + catches a backend producing NaNs or a blank image. Judging whether an image + is *good* is a separate problem needing a different kind of test. +- **Other backends.** CPU, Vulkan, CUDA and Metal archives get the release + job's family completeness check only. +- **Other gfx targets on hardware.** Every compiled target is checked for + presence (T0.3), but only gfx1151 is run. Records say so explicitly rather + than implying the rest were tested too. diff --git a/.github/qualify-rocm/aggregate.py b/.github/qualify-rocm/aggregate.py new file mode 100644 index 0000000000..708b8352ff --- /dev/null +++ b/.github/qualify-rocm/aggregate.py @@ -0,0 +1,341 @@ +#!/usr/bin/env python3 +""" +Merge tier reports into one qualification record per published archive, decide +which ROCm versions may be published, and write the job summary. + +Reports are grouped by (OS, ROCm version), because that pair identifies exactly +one release asset -- the unit a user downloads and the unit a bug report names. + +A ROCm version is publishable when BOTH its archives (Windows and Linux) pass. +Versions are judged independently of each other: they are separate products and +a consumer installs exactly one of them, so a problem in one is no reason to +withhold another. + +With --operating-systems and --rocm-versions, an archive that should exist but +has no report at all (usually because its build failed) also blocks its version: +the version cannot ship without it, so its other archive must not be reported +as publishable either. + +Within one archive, both tiers must have reported and neither may have failed: + - the static checks (Tier 0) must be present and must pass. The release + job's own final-archive check (T0.12) is filed under Tier 0 too, but on its + own it does not count as Tier 0 having reported: the Tier 0 job must have. + - the GPU checks (Tier 1) must be present and must pass. Unlike + lemonade-sdk/llama.cpp, a missing Tier 1 blocks: an offline GPU runner + withholds the ROCm version rather than shipping it untested. + - with --require-final, the final-archive check (T0.12) must be present too, + so an archive whose bytes were never compared with the tested ones cannot + ship. +Each build covers 20 or more gfx targets and only one of them has test +hardware; the record states which is which instead of implying they are all +equal. An archive that is not promoted always has overall "fail", even when the +reason is a tier that never reported rather than a failed check. + +With --fail-on-no-promote the exit code is non-zero if any version failed. The +release job uses that to drop only the affected ROCm versions, leaving every +other backend untouched. + +Usage: + python3 aggregate.py --fragments-dir ./fragments --tag master-1106-abc1234 \ + --records-dir ./qualification --output-summary summary.json \ + --operating-systems ubuntu,win --rocm-versions 10.0,10.1,10.2 \ + --require-final --fail-on-no-promote +""" + +import argparse +import glob +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import report # noqa: E402 + + +def load_fragments(fragments_dir): + fragments = [] + for path in sorted(glob.glob(os.path.join(fragments_dir, "*.json"))): + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError) as exc: + print(f"::warning::skipping unreadable fragment {path}: {exc}") + continue + if data.get("kind") == "tier_fragment": + fragments.append(data) + return fragments + + +def split_list(text): + """Split a comma or whitespace separated list into clean names.""" + return [name for part in (text or "").split(",") for name in part.split() if name] + + +def group_key(fragment): + build = fragment.get("build", {}) + return (build.get("os") or "?", build.get("rocm_version") or "?") + + +def published_name(tag, os_name, rocm_version): + """The release asset filename for this (os, rocm) pair. + + The tag is master--, but the asset names + drop the count -- sd-master--... -- which is also how Lemonade + builds the names it downloads. The version in the name is the full X.Y.0. + """ + parts = (tag or "").split("-") + if len(parts) != 3: + return None + prefix = f"sd-{parts[0]}-{parts[2]}" + if os_name == "win": + return f"{prefix}-bin-win-rocm-{rocm_version}.0-x64.zip" + if os_name == "ubuntu": + return f"{prefix}-bin-Linux-Ubuntu-24.04-x86_64-rocm-{rocm_version}.0.zip" + return None + + +def tier_reported(record, tier): + """Whether a tier's own job reported on this archive. + + The release job's final-archive check (T0.12) is filed under tier0 too, so a + tier0 bucket holding nothing else means the Tier 0 job itself never ran. + The gate, the job summary and the feed all use this one rule. + """ + bucket = record.get("tiers", {}).get(tier) + if not bucket: + return False + if tier == "tier0": + return bool({t.get("id") for t in bucket.get("tests", [])} - {"T0.12"}) + return True + + +def decide(record, require_final=False): + """Return (publishable, reasons) for one archive's merged record.""" + reasons = [] + tiers = record.get("tiers", {}) + tier0_ids = {t.get("id") for t in tiers.get("tier0", {}).get("tests", [])} + + for tier in ("tier0", "tier1"): + if not tier_reported(record, tier): + reasons.append(f"{tier} missing") + elif tiers[tier]["status"] == report.STATUS_FAIL: + reasons.append(f"{tier}=fail") + + if require_final and "T0.12" not in tier0_ids: + reasons.append("T0.12 missing") + + return not reasons, reasons + + +def gfx_summary(record): + """Pull the gfx audit result out of T0.3 for the record's top level. + + This is the field that answers "was my GPU ever verified?" -- present in + the binary is not the same claim as validated on hardware, and the record + should not blur them. + """ + tests = record.get("tiers", {}).get("tier0", {}).get("tests", []) + audit = next((t for t in tests if t.get("id") == "T0.3"), None) + details = (audit or {}).get("details", {}) + validated = [] + if record.get("build", {}).get("hardware_validated"): + target = record.get("build", {}).get("gfx_target") + if target: + validated = [target] + expected = details.get("expected", []) + # T0.3 also audits other binaries with GPU code of their own + # (libstable-diffusion.so); a target any of them lacks is missing too. + missing = set(details.get("missing", [])) + for other in (details.get("other_binaries") or {}).values(): + if other.get("present_count"): + missing.update(other.get("missing", [])) + present = details.get("present", []) + if missing - set(details.get("missing", [])): + present = [t for t in present if t not in missing] + return { + "requested": expected, + "present_in_binary": present, + "missing_from_binary": [t for t in expected if t in missing] + sorted(missing - set(expected)), + "hardware_validated": validated, + } + + +def write_step_summary(records, promote_all, missing=()): + path = os.environ.get("GITHUB_STEP_SUMMARY") + if not path: + return + lines = ["## ROCm build qualification", "", + f"**ROCm family publishable: {'YES' if promote_all else 'NO'}**", "", + "| Artifact | Tier 0 | Tier 1 | gfx in binary | HW validated | Promote |", + "|---|---|---|---|---|---|"] + for record in records: + build = record["build"] + tiers = record.get("tiers", {}) + gfx = record["gfx"] + t0 = (tiers["tier0"]["status"] if tier_reported(record, "tier0") else "missing").upper() + t1 = (tiers["tier1"]["status"] if tier_reported(record, "tier1") else "missing").upper() + hw = ", ".join(gfx["hardware_validated"]) or "none" + lines.append( + f"| `{build.get('artifact')}` | {t0} | {t1} | " + f"{len(gfx['present_in_binary'])}/{len(gfx['requested'])} | {hw} | " + f"{'yes' if record['promoted'] else 'NO'} |") + for os_name, rocm_version in missing: + lines.append(f"| {os_name} ROCm {rocm_version} | no report | | | | NO |") + + problems = [] + for record in records: + for tier in sorted(record.get("tiers", {})): + for test in record["tiers"][tier].get("tests", []): + if test["status"] in (report.STATUS_FAIL, report.STATUS_WARN): + gate = "" if test.get("gating") else " _(non-gating)_" + problems.append( + f"- `{record['build'].get('artifact')}` `{test['id']}` " + f"**{test['status']}**{gate} — {test['name']}: " + f"{test.get('error') or ''}") + if problems: + lines += ["", "### Findings", *problems] + + with open(path, "a", encoding="utf-8") as handle: + handle.write("\n".join(lines) + "\n") + + +def main(): + parser = argparse.ArgumentParser(description="Aggregate ROCm tier fragments") + parser.add_argument("--fragments-dir", required=True) + parser.add_argument("--tag", default=None, help="release tag, master--") + parser.add_argument("--records-dir", default=None, + help="write one qualification-.json per archive here") + parser.add_argument("--output-summary", default=None, + help="write the combined decision here") + parser.add_argument("--operating-systems", default=None, + help="the operating systems every ROCm version is built for, e.g. ubuntu,win") + parser.add_argument("--rocm-versions", default=None, + help="the ROCm versions this run builds, e.g. 10.0,10.1,10.2") + parser.add_argument("--require-final", action="store_true", + help="block an archive the release job's final-archive check (T0.12) did not run on") + parser.add_argument("--fail-on-no-promote", action="store_true") + args = parser.parse_args() + + # Every archive the run should have produced. Without the lists, only the archives that reported can be judged. + expected = [] + if args.operating_systems and args.rocm_versions: + expected = [(o, v) for v in split_list(args.rocm_versions) + for o in split_list(args.operating_systems)] + + fragments = load_fragments(args.fragments_dir) + if not fragments: + print(f"::error::No tier fragments found in {args.fragments_dir}. The " + "qualification jobs produced nothing, so nothing can be vouched for.") + # With no expected list there is no verdict to write, and the release job then withholds every ROCm version. + if not expected: + if args.fail_on_no_promote: + sys.exit(1) + return + + grouped = {} + for fragment in fragments: + grouped.setdefault(group_key(fragment), []).append(fragment) + + records = [] + for (os_name, rocm_version), group in sorted(grouped.items()): + record = report.merge_fragments(group, extra_meta={ + "sdcpp_tag": args.tag, + "artifact": published_name(args.tag, os_name, rocm_version), + }) + promote, reasons = decide(record, args.require_final) + record["promoted"] = promote + record["promotion"] = {"blocked_by": reasons} + # A tier that never reported fails no test, so the test rollup alone could still say "pass". + if not promote: + record["overall"] = report.STATUS_FAIL + record["gfx"] = gfx_summary(record) + records.append(record) + + # A ROCm version is publishable only when every archive carrying it passed. + # Versions are independent, so one bad version never withholds the others. + by_version = {} + for record in records: + version = record["build"].get("rocm_version") or "?" + by_version.setdefault(version, []).append(record) + blocked = {v for v, group in by_version.items() + if not all(r["promoted"] for r in group)} + # An archive with no report at all cannot ship, so neither can its version. + missing = [(o, v) for o, v in expected if (o, v) not in grouped] + for os_name, rocm_version in missing: + print(f"::error::No qualification report at all for {os_name} ROCm {rocm_version}.") + blocked.add(rocm_version) + blocked = sorted(blocked) + promote_all = bool(records) and not blocked + + for record in records: + build = record["build"] + version = build.get("rocm_version") or "?" + # Why the version as a whole was withheld, so the record of an archive + # that passed its own checks still says why it did not ship. + record["promotion"]["version_blocked_by"] = [ + f"{other['build'].get('os')}: {reason}" + for other in by_version.get(version, []) if other is not record + for reason in other["promotion"]["blocked_by"] + ] + [f"{o}: no report" for o, v in missing if v == version] + + for record in records: + os_name = record["build"].get("os") + rocm_version = record["build"].get("rocm_version") + promote = record["promoted"] + reasons = record["promotion"]["blocked_by"] + artifact = record["build"].get("artifact") or f"{os_name}-rocm-{rocm_version}" + if args.records_dir: + os.makedirs(args.records_dir, exist_ok=True) + stem = artifact + for suffix in (".zip",): + if stem.endswith(suffix): + stem = stem[: -len(suffix)] + break + out = os.path.join(args.records_dir, f"qualification-{stem}.json") + with open(out, "w", encoding="utf-8") as handle: + json.dump(record, handle, indent=2) + handle.write("\n") + print(f"Wrote {out}") + + print(f"{artifact}: overall={record['overall']} promote={promote} " + f"blocked_by={reasons} " + f"gfx={len(record['gfx']['present_in_binary'])}/" + f"{len(record['gfx']['requested'])} " + f"hw_validated={record['gfx']['hardware_validated'] or 'none'}") + + write_step_summary(records, promote_all, missing) + + if args.output_summary: + os.makedirs(os.path.dirname(os.path.abspath(args.output_summary)), exist_ok=True) + with open(args.output_summary, "w", encoding="utf-8") as handle: + json.dump({ + "tag": args.tag, + "all_versions_publishable": promote_all, + "blocked_rocm_versions": blocked, + "missing_archives": [f"{o}-rocm-{v}" for o, v in missing], + "artifacts": [{"artifact": r["build"].get("artifact"), + "rocm_version": r["build"].get("rocm_version"), + "publishable": r["promoted"], + "overall": r["overall"], + "blocked_by": r["promotion"]["blocked_by"]} + for r in records], + }, handle, indent=2) + handle.write("\n") + + github_output = os.environ.get("GITHUB_OUTPUT") + if github_output: + with open(github_output, "a", encoding="utf-8") as handle: + handle.write(f"promote_rocm={'true' if promote_all else 'false'}\n") + handle.write(f"blocked_rocm_versions={' '.join(blocked)}\n") + + if blocked: + print(f"::error::ROCm {', '.join(blocked)} did not qualify and will be " + "dropped from this release. Other ROCm versions and every other " + "backend are unaffected.") + if args.fail_on_no_promote and blocked: + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/.github/qualify-rocm/archive.py b/.github/qualify-rocm/archive.py new file mode 100644 index 0000000000..de063bd5e4 --- /dev/null +++ b/.github/qualify-rocm/archive.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +""" +Unpack a published ROCm archive the way a user's unzip would. + +Both Tier 0 and Tier 1 need the archive's files on disk, and the two operating +systems pack them differently: the Windows zip is flat, while the Linux zip +holds build/bin/ with its versioned library names stored as symlinks. Rather +than encode either layout, extract() returns whichever folder sd-server landed +in -- the same thing Lemonade does when it searches the extracted folder for +sd-server. Without sd-server it returns the folder holding the rest of the +build, so the caller can report what is missing. + +Every entry is checked to stay inside the destination, so a damaged or hostile +archive cannot write anywhere else. +""" + +import os +import stat +import zipfile + +SERVER = {"ubuntu": "sd-server", "win": "sd-server.exe"} +CLI = {"ubuntu": "sd-cli", "win": "sd-cli.exe"} +# Files that mark the archive's binary folder when sd-server itself is missing. +MARKERS = ("stable-diffusion.dll", "libstable-diffusion.so", "ggml.txt", + "stable-diffusion.cpp.txt", "sd-cli", "sd-cli.exe") + + +def extract(archive, dest): + """Extract `archive` into `dest` and return the folder holding sd-server. + + Without sd-server, return the folder holding the rest of the build (one of + MARKERS), or else `dest`; callers check that sd-server exists. + + Raises ValueError for a non-.zip archive or an entry or symlink that would + land outside `dest`, and whatever zipfile raises for a damaged zip + (BadZipFile, zlib.error, EOFError, NotImplementedError, ...). + + The Linux zip is made with `zip -y`, so its versioned .so names are stored as + symlinks. zipfile.extractall would write them out as small text files the + loader cannot use, so they are recreated as symlinks here. + """ + if not archive.endswith(".zip"): + raise ValueError(f"unsupported archive type: {archive}") + dest = os.path.abspath(dest) + os.makedirs(dest, exist_ok=True) + with zipfile.ZipFile(archive) as zf: + for info in zf.infolist(): + target = os.path.abspath(os.path.join(dest, info.filename)) + if os.path.commonpath([dest, target]) != dest: + raise ValueError(f"{archive}: entry escapes the archive: {info.filename}") + mode = info.external_attr >> 16 + if stat.S_ISLNK(mode) and os.name != "nt": + link = zf.read(info).decode("utf-8") + if os.path.isabs(link) or ".." in link.split("/"): + raise ValueError(f"{archive}: symlink leaves its folder: {info.filename} -> {link}") + os.makedirs(os.path.dirname(target), exist_ok=True) + if os.path.lexists(target): + os.remove(target) + os.symlink(link, target) + continue + zf.extract(info, dest) + if mode and not info.is_dir() and os.name != "nt": + os.chmod(target, stat.S_IMODE(mode) | stat.S_IRUSR) + + # Without sd-server (say upstream renamed it) fall back to the folder holding + # the rest of the build, so Tier 0's T0.1 can report exactly what is missing. + for markers in (set(SERVER.values()), set(MARKERS)): + for dirpath, _dirs, files in os.walk(dest): + if markers & set(files): + return dirpath + return dest diff --git a/.github/qualify-rocm/binfmt.py b/.github/qualify-rocm/binfmt.py new file mode 100644 index 0000000000..11b8d49f34 --- /dev/null +++ b/.github/qualify-rocm/binfmt.py @@ -0,0 +1,427 @@ +#!/usr/bin/env python3 +""" +Read-only inspection of compiled binaries: which gfx targets they support, +which libraries they need, and which version of the C library they require. + +Background, because none of this is obvious from the outside. + +A compiled program is stored in a structured file format. Linux uses ELF (.so +shared libraries, and executables); Windows uses PE (.dll and .exe). They hold +the same kinds of information -- machine code, data, and a list of the other +libraries the program needs -- just arranged differently. Both divide the file +into named blocks called "sections". + +AMD GPUs come in different architectures, called gfx targets -- gfx1151, +gfx1030, and so on. Each one needs machine code built specifically for it. When +stable-diffusion.cpp's HIP code is compiled it is asked to produce code for a whole list +of gfx targets at once, and the result is a single "fat binary": one file with a +stack of per-target builds inside it. That is why the file holding the HIP code +(libggml-hip.so on Linux, stable-diffusion.dll on Windows) is around a +gigabyte while every other library is a few megabytes. + +The problem this module exists to solve: if the compiler produces code for only +some of the requested gfx targets, NOTHING reports an error. The file is still +created, the build still succeeds, and the file still has the expected name. A +user whose gfx target was dropped then runs sd-server, which looks for code for +their GPU, does not find it, and quietly falls back to the CPU -- much slower, +with no error message anywhere. So the only way to know is to open the fat +binary and count what is actually inside it. + +Everything here uses the Python standard library only, so it can run on any +runner without installing a GPU toolchain. +""" + +import os +import re +import struct + +# --------------------------------------------------------------------------- +# Counting the gfx targets inside a fat binary +# --------------------------------------------------------------------------- + +# Each per-target build inside the fat binary is labelled with a plain readable +# tag, stored as ordinary text right in the file. The tags look like this: +# +# hip-amdgcn-amd-amdhsa--gfx1151 +# | | | +# | | the gfx target this build is for +# | the AMD GPU platform the code was built for +# the kind of GPU offloading +# +# So finding every gfx target is simply a matter of searching the file's bytes +# for that pattern and collecting the names. The double dash is not a typo -- +# it is an intentionally empty field in the middle of the platform name. +# +# Two details the pattern handles deliberately: +# * The leading word is matched loosely ("hip", "hipv4", ...) because +# different compiler versions spell it differently. +# * Requiring "amdgcn-amd-amdhsa" means only GPU builds match. The same file +# also contains a regular CPU build labelled with an Intel/AMD CPU platform +# name, and we do not want to count that as a gfx target. +BUNDLE_ENTRY_RE = re.compile(rb"[a-z0-9_]+-amdgcn-amd-amdhsa-[-0-9a-zA-Z_.:+]*") + +# Marker text that begins each group of per-target builds. Counted purely as a +# sanity signal, so the report can show how many groups were found. +BUNDLE_MAGIC = b"__CLANG_OFFLOAD_BUNDLE__" + +# gfx target names look like gfx1151, gfx90a, gfx1030. +_GFX_RE = re.compile(r"(gfx[0-9a-fA-F]+)") + +# The fat binary is around a gigabyte, so read it in pieces instead of loading +# the whole thing into memory at once. +_CHUNK = 64 << 20 +# When reading in pieces, a tag could land half in one piece and half in the +# next. Carrying this many bytes over to the next piece guarantees every tag is +# seen whole. It comfortably exceeds the length of any tag. +_OVERLAP = 256 +# Bytes a tag's leading word ("hip", "hipv4", ...) is made of. A piece is never +# cut inside such a word: the carried-over half would otherwise match again on +# its own ("ip-amdgcn-...") and the tag would be counted twice. +_WORD_BYTES = frozenset(b"abcdefghijklmnopqrstuvwxyz0123456789_") + + +def strip_target_id(entry_id): + """Pull the gfx target name out of a tag. + + Some builds append extra hardware options after the name, separated by a + colon, e.g. 'gfx90a:xnack+'. Those describe optional features, not a + different target, so everything from the colon onward is discarded. + + 'hip-amdgcn-amd-amdhsa--gfx90a:xnack+' -> 'gfx90a' + """ + match = _GFX_RE.search(entry_id.split(":", 1)[0]) + return match.group(1) if match else None + + +def scan_offload_bundles(path): + """Search a binary for per-target build tags. + + Returns (how many times each tag appears, how many build groups were found, + how many bytes were read). + + This reads the file's raw bytes rather than asking a compiler tool to list + the contents, for two reasons. + + First, it works the same on Linux and Windows. The GPU code lives in a + section whose name is '.hip_fatbin' on Linux -- but Windows caps section + names at eight characters once a file is linked, so the very same section + is called '.hip_fat' there. Tools that are told to look up the section by + name therefore find nothing on Windows. Searching the bytes does not care + what the section is called, so one piece of code covers both. + + Second, it needs no AMD toolchain installed, which means this check can run + on an ordinary runner against the archive we actually publish, instead of + only on the machine that compiled it. + """ + counts = {} + magic = 0 + total = 0 + + def tally(window, limit): + """Count tags that begin before `limit`. + + The bytes from `limit` onward get carried into the next piece of the + file, where they will be examined then. That way each position in the + file is considered exactly once: nothing is counted twice, and no tag + is missed because it straddled a boundary. + """ + nonlocal magic + for match in BUNDLE_ENTRY_RE.finditer(window): + if match.start() >= limit: + break + entry = match.group(0).decode("ascii", "replace") + counts[entry] = counts.get(entry, 0) + 1 + start = 0 + while True: + found = window.find(BUNDLE_MAGIC, start) + if found < 0 or found >= limit: + break + magic += 1 + start = found + 1 + + tail = b"" + with open(path, "rb") as handle: + while True: + buf = handle.read(_CHUNK) + if not buf: + tally(tail, len(tail)) + break + total += len(buf) + window = tail + buf + safe = max(len(window) - _OVERLAP, 0) + floor = max(len(window) - 2 * _OVERLAP, 0) + while safe > floor and window[safe - 1] in _WORD_BYTES: + safe -= 1 + tally(window, safe) + tail = window[safe:] + return counts, magic, total + + +def audit_gfx_targets(path, expected): + """Check which gfx targets a fat binary actually contains code for. + + `expected` is the list of gfx targets the build was asked to produce, taken + from the build job itself so Linux and Windows are each compared against + their own list rather than a shared guess. + + The returned dict reports which targets are present, which are missing, and + how many times each one appears. That last number is useful on its own: the + compiler emits one entry per source file it compiles, so in a healthy build + every target has the SAME count. A target with a noticeably lower count was + built into only part of the project, which a simple present/absent check + would miss entirely. + """ + counts, magic, total = scan_offload_bundles(path) + per_target = {} + for entry, n in counts.items(): + target = strip_target_id(entry) + if target: + per_target[target] = per_target.get(target, 0) + n + + expected_set = {strip_target_id(t) or t for t in expected} + present = set(per_target) + uniform = len(set(per_target.values())) <= 1 + + return { + "binary": os.path.basename(path), + "bytes_scanned": total, + "bundle_magic_count": magic, + "expected_count": len(expected_set), + "present_count": len(present), + "expected": sorted(expected_set), + "present": sorted(present), + "missing": sorted(expected_set - present), + "extra": sorted(present - expected_set), + "entries_per_target": dict(sorted(per_target.items())), + "entry_count_uniform": uniform, + } + + +# --------------------------------------------------------------------------- +# ELF -- the Linux program file format +# --------------------------------------------------------------------------- + +def is_elf(path): + try: + with open(path, "rb") as handle: + return handle.read(4) == b"\x7fELF" + except OSError: + return False + + +def elf_sections(path): + """List the named blocks ("sections") an ELF file is divided into. + + Each entry gives the section's name, where it starts in the file, and how + big it is. The rest of this module uses it to find specific sections such + as the list of required libraries. + """ + with open(path, "rb") as handle: + header = handle.read(64) + if header[:4] != b"\x7fELF" or header[4] != 2: + raise ValueError(f"{path}: not ELF64") + e_shoff, = struct.unpack_from("-rocm-.json. + +This is what makes "what is built is what is tested" hold. Tier 0 and Tier 1 +download the build job's artifact by name; the release job downloads it again +and uploads it under the same name, never repacking or merging anything into +it. If any step in between ever changed the bytes -- a re-pack, a merge, a +corrupted transfer -- the SHA-256 would no longer match and the archive's ROCm +version would be withheld. (lemonade-sdk/llama.cpp calls the same check T0.11, +in check_post_merge.py.) + +The file is opened inside the check, so an archive that cannot be read is +recorded as a FAIL instead of crashing the script and leaving no result. + +Usage: + python3 check_final.py --archive artifact/sd-master-abc1234-bin-win-rocm-10.1.0-x64.zip \ + --meta meta/qualify-meta-win-rocm-10.1.json --output frag.json +""" + +import argparse +import hashlib +import json +import os +import sys +import zipfile + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import archive # noqa: E402 +import report # noqa: E402 +import tier0_static # noqa: E402 + + +def sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def check_integrity(path, os_name, expected_sha): + with zipfile.ZipFile(path) as zf: + bad = zf.testzip() + if bad is not None: + raise zipfile.BadZipFile(f"{bad} fails its CRC check") + names = [os.path.basename(i.filename) for i in zf.infolist() if not i.is_dir()] + required = [archive.SERVER[os_name], tier0_static.HIP_CODE[os_name]] + missing = [r for r in required if r not in names] + actual = sha256(path) + details = {"entries": len(names), "missing": missing, "bytes": os.path.getsize(path), + "sha256": actual, "expected_sha256": expected_sha} + if missing: + return (report.STATUS_FAIL, f"final archive is missing {', '.join(missing)}", details) + if not expected_sha: + return (report.STATUS_FAIL, "the build job recorded no SHA-256 for this archive", details) + if actual != expected_sha.lower(): + return (report.STATUS_FAIL, "this is not the archive the build job produced and " + "Tier 0/Tier 1 tested (SHA-256 mismatch)", details) + return (report.STATUS_PASS, None, details) + + +def main(): + parser = argparse.ArgumentParser(description="Final release-archive check (T0.12)") + parser.add_argument("--archive", required=True) + parser.add_argument("--meta", required=True) + parser.add_argument("--run-id", default=os.environ.get("GITHUB_RUN_ID")) + parser.add_argument("--run-attempt", default=os.environ.get("GITHUB_RUN_ATTEMPT")) + parser.add_argument("--output", required=True) + args = parser.parse_args() + + with open(args.meta, encoding="utf-8-sig") as handle: + info = json.load(handle) + tier = report.TierReport("tier0", report.build_meta( + artifact=os.path.basename(args.archive), os_name=info["os"], + rocm_version=info["rocm_version"], sdcpp_tag=info.get("tag"), + upstream_sha=info.get("upstream_sha"), run_id=args.run_id, run_attempt=args.run_attempt)) + tier.run("T0.12", "final archive integrity", + lambda: check_integrity(args.archive, info["os"], info.get("sha256"))) + tier.write(args.output) + tier.print_summary() + + +if __name__ == "__main__": + main() diff --git a/.github/qualify-rocm/install_rocm.py b/.github/qualify-rocm/install_rocm.py new file mode 100644 index 0000000000..79e2822637 --- /dev/null +++ b/.github/qualify-rocm/install_rocm.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +""" +Install a ROCm runtime into a throwaway virtual environment, matching the way +an end user's machine gets one. + +The archives this repo publishes do not contain ROCm's math libraries (hipBLAS, +hipBLASLt, rocBLAS) -- a user installs them separately, and Lemonade does so +automatically. So a qualification job that only unpacks the archive and runs it +is testing nothing: sd-server cannot even start without them (on Windows it +exits with 0xC0000135, "DLL not found", before printing a line). And with the +wrong ROCm, a GPU that cannot be used is not treated as an error: sd-server +logs it and quietly runs on the CPU, so a test passes while the thing it was +meant to verify is completely broken. + +What gets installed: + + pip install --index-url "rocm[libraries,device-]==" + +The part in brackets matters. A BUILD needs ROCm's compilers, so the build jobs +ask for the "devel" component. A USER needs the kernels for their own GPU, so +they get "device-" instead. Verifying against the build's own components +would be circular -- those are the exact files the binary was compiled against, +so of course they are present. Installing the user's set instead means the +checks answer the question that actually matters: will this archive find what +it needs on a real machine? + +Everything lands under --prefix and nothing is installed system-wide, so +repeated runs on a persistent machine stay isolated from each other. + +Usage: + python3 install_rocm.py --version 10.1.0 --arch gfx1151 +""" + +import argparse +import glob +import json +import os +import subprocess +import sys +import tempfile + +# AMD publishes ROCm wheels on different package indexes depending on the +# major version. Keep this in step with the index each build job installs from. +INDEX_BY_MAJOR = { + "7": "https://repo.amd.com/rocm/whl-multi-arch/", + "10": "https://stable.repo.amd.com/rocm/whl-next/", +} + + +def venv_python(venv_dir): + if os.name == "nt": + return os.path.join(venv_dir, "Scripts", "python.exe") + return os.path.join(venv_dir, "bin", "python") + + +def minimal_env(python): + """A copy of the environment with PATH cut down to what pip needs. + + pip reads every directory on PATH while it installs, to work out whether + the scripts it is placing will be reachable. A single unreadable entry + there is enough to abort the whole install -- a machine that has, say, a + package manager leaving a broken shortcut behind produces an error about + the thing being installed, which sends you looking in entirely the wrong + place. + + Nothing here needs anything from a user's personal tool directories, so + PATH is rebuilt from just the interpreter being used plus the operating + system's own directories. A broken entry elsewhere then cannot reach us. + """ + env = dict(os.environ) + parts = [os.path.dirname(os.path.abspath(python))] + + if os.name == "nt": + scripts = os.path.join(os.path.dirname(os.path.abspath(python)), "Scripts") + if os.path.isdir(scripts): + parts.append(scripts) + windir = env.get("SystemRoot") or r"C:\Windows" + parts += [os.path.join(windir, "system32"), windir, + os.path.join(windir, "system32", "Wbem"), + os.path.join(windir, "system32", "WindowsPowerShell", "v1.0")] + else: + parts += ["/usr/local/bin", "/usr/bin", "/bin", "/usr/local/sbin", + "/usr/sbin", "/sbin"] + + env["PATH"] = os.pathsep.join(p for p in parts if os.path.isdir(p)) + return env + + +def run(cmd, **kwargs): + print("+ " + " ".join(str(c) for c in cmd), flush=True) + return subprocess.run(cmd, check=False, **kwargs) + + +def site_packages(venv_dir): + if os.name == "nt": + matches = [os.path.join(venv_dir, "Lib", "site-packages")] + else: + matches = sorted(glob.glob(os.path.join(venv_dir, "lib", "python3*", "site-packages"))) + for path in matches: + if os.path.isdir(path): + return path + raise SystemExit(f"no site-packages under {venv_dir}") + + +def runtime_dirs(venv_dir): + """Every directory that has to be on the library search path. + + This returns a list, not a single root directory, because ROCm spreads its + runtime across several packages: the core HIP libraries live in one, and + the maths libraries (rocBLAS, hipBLAS and friends) live in another. Adding + only the first means the core loads and then the maths libraries cannot be + found, which surfaces as a confusing "DLL not found" on Windows or a + missing-library error on Linux. + """ + site = site_packages(venv_dir) + dirs = [] + for pkg in sorted(glob.glob(os.path.join(site, "_rocm_sdk_*"))): + # rocm_sysdeps holds TheRock's own copies of system libraries (libelf, + # libdrm, libnuma, ...) that the Linux HIP runtime loads through its + # RUNPATH. Listing it here is what lets Tier 1's T1.6 recognise them as + # part of the user's ROCm install. + for sub in ("bin", "lib", os.path.join("lib", "llvm", "bin"), + os.path.join("lib", "llvm", "lib"), + os.path.join("lib", "rocm_sysdeps", "lib")): + candidate = os.path.join(pkg, sub) + if os.path.isdir(candidate) and candidate not in dirs: + dirs.append(candidate) + return dirs + + +def main(): + parser = argparse.ArgumentParser( + description="Install a user-style ROCm runtime into a throwaway venv") + parser.add_argument("--version", required=True, help="e.g. 10.1.0") + parser.add_argument("--arch", required=True, help="e.g. gfx1151") + parser.add_argument("--prefix", default=None, + help="scratch directory for the virtual environment. " + "Defaults to a 'rocm-qual' folder inside the " + "runner's temporary directory, so callers never " + "have to spell out a shell variable.") + parser.add_argument("--index-url", default=None, + help="override the index chosen from the ROCm major version") + parser.add_argument("--output-json", default=None, + help="write the resolved runtime dirs here") + args = parser.parse_args() + + # Resolved here rather than by the caller so the command line stays free of + # shell variables, which are spelled differently in bash and PowerShell. + # Absolute, because the directories end up on the library search path of a + # program started from a different working directory. + prefix = os.path.abspath(args.prefix or os.path.join( + os.environ.get("RUNNER_TEMP") or tempfile.gettempdir(), "rocm-qual")) + + major = args.version.split(".")[0] + index = args.index_url or INDEX_BY_MAJOR.get(major) + if not index: + raise SystemExit( + f"No package index known for ROCm {args.version} (major {major}). " + f"Known: {sorted(INDEX_BY_MAJOR)}. Add it to INDEX_BY_MAJOR.") + + venv_dir = os.path.join(prefix, f"rocm-{args.version}-{args.arch}") + os.makedirs(prefix, exist_ok=True) + + if not os.path.exists(venv_python(venv_dir)): + if run([sys.executable, "-m", "venv", venv_dir], + env=minimal_env(sys.executable)).returncode != 0: + raise SystemExit(f"could not create venv at {venv_dir}") + + python = venv_python(venv_dir) + env = minimal_env(python) + run([python, "-m", "pip", "install", "--upgrade", "pip", "--quiet"], env=env) + + spec = f"rocm[libraries,device-{args.arch}]=={args.version}" + proc = run([python, "-m", "pip", "install", "--index-url", index, spec], env=env) + if proc.returncode != 0: + raise SystemExit( + f"\n::error::Could not install '{spec}' from {index}.\n" + f"::error::pip's output above says why. Check that {index} still " + f"carries both 'rocm' at version {args.version} and a " + f"'rocm-sdk-device-{args.arch}' wheel for it -- " + f"`pip index versions --index-url {index} rocm-sdk-device-{args.arch}` " + f"lists what is actually available there.") + + # pip only warns about an extra it does not know, so a missing device wheel + # would otherwise go unnoticed until sd-server finds no kernels for the GPU. + if run([python, "-m", "pip", "show", "--quiet", f"rocm-sdk-device-{args.arch}"], + env=env, capture_output=True).returncode != 0: + raise SystemExit(f"::error::'{spec}' did not install rocm-sdk-device-{args.arch}; " + "the index may not carry a device wheel for that gfx target.") + + dirs = runtime_dirs(venv_dir) + if not dirs: + raise SystemExit( + "::error::ROCm installed but no _rocm_sdk_*/{bin,lib} directories were " + f"found under {site_packages(venv_dir)} -- the wheel layout changed.") + + print(f"\nROCm {args.version} ({args.arch}) runtime directories:") + for directory in dirs: + print(f" {directory}") + + if args.output_json: + with open(args.output_json, "w", encoding="utf-8") as handle: + json.dump({"version": args.version, "arch": args.arch, + "index": index, "venv": venv_dir, + "runtime_dirs": dirs}, handle, indent=2) + + # Hand the search path to later steps through the workflow environment. + # Reading GITHUB_ENV here, instead of taking its path as an argument, keeps + # the caller from having to write $GITHUB_ENV (bash) or $env:GITHUB_ENV + # (PowerShell) and so lets one command line work under either shell. + github_env = os.environ.get("GITHUB_ENV") + if github_env: + with open(github_env, "a", encoding="utf-8") as handle: + handle.write(f"ROCM_RUNTIME_DIRS={os.pathsep.join(dirs)}\n") + handle.write(f"ROCM_VENV={venv_dir}\n") + print("\nROCm runtime ready.") + + +if __name__ == "__main__": + main() diff --git a/.github/qualify-rocm/publish_qualification.py b/.github/qualify-rocm/publish_qualification.py new file mode 100644 index 0000000000..6712002458 --- /dev/null +++ b/.github/qualify-rocm/publish_qualification.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +""" +Publish the qualification records from one release run to the dashboard feed on the `qualification-data` branch. + +Reads the records `aggregate.py` wrote (one qualification-.json per archive, plus qualification-summary.json) and upserts them into --data-dir, which is the `qualification/` folder of a checkout of that branch: + + index.json one compact row per archive per run, newest run first + reports/.json the full record, for drill-down + latest/-rocm-.json the newest full record for that archive + +build_id is "--rocm-". +Publishing the same run again (a re-run) replaces its rows and files rather than duplicating them, so this script is safe to run any number of times -- except a row an earlier attempt of the run already shipped for the same tag, and this attempt did not upload again, which is kept as it is. + +Every archive the run was meant to build gets a row. +An archive with no record (its build failed / no check ever reported on it) gets a placeholder row and a placeholder report saying so. Therefore, a failing build shows up in the feed instead of silently leaving a gap. + +A test the record does not contain is reported as either: + - "not_applicable": it is never run for this archive -- the final-archive check T0.12 on an archive that never reached it (it was dropped from the release before they ran); or + - "missing": it should have run and did not. +Neither is folded into "failed"; `qualified` is the verdict. + +A feed written by an older schema_version is not mixed with this one: the first publish starts a fresh index.json, reports/ and latest/. +The old files stay in the branch's git history. + +index.json also carries a top-level "last_check": what the most recent nightly or +release run decided. A nightly whose tag was already fully published builds +nothing and so adds no rows; with --mark-unchanged it records only last_check +(status "unchanged"), so the dashboard can tell "nothing changed upstream" apart +from "the nightly did not run". + +The contract this writes is FEED.md, copied to the branch as SCHEMA.md. + +Usage: + python3 publish_qualification.py --records-dir ./records \ + --data-dir ./data/qualification --operating-systems ubuntu,win \ + --rocm-versions 10.0,10.1,10.2 --tag master-1106-abc1234 --upstream-sha \ + --jobs-file jobs.jsonl --published-artifacts "" --final-checked "" + + # A nightly that found its release already complete: + python3 publish_qualification.py --mark-unchanged --data-dir ./data/qualification \ + --tag master-1106-abc1234 --upstream-sha +""" + +import argparse +import glob +import json +import os +import re +import shutil +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import aggregate # noqa: E402 +import report # noqa: E402 + +SCHEMA_VERSION = 2 + +# Every test the suite runs, in the order the README lists them. +# A test absent from a record shows up as "missing" or "not_applicable", so the dashboard always has the same columns to draw. +# A test id not listed here is still published, never dropped. +TIER_TESTS = { + "tier0": ["T0.1", "T0.2", "T0.3", "T0.4", "T0.5", "T0.6", "T0.7", "T0.8", + "T0.9", "T0.10", "T0.11", "T0.12"], + "tier1": ["T1.1", "T1.2", "T1.3", "T1.4", "T1.5", "T1.6"], +} +# Run by the release job on the archives still in the release after its completeness check. +FINAL_TESTS = {"T0.12"} + +STATUS_MISSING = "missing" +STATUS_NOT_APPLICABLE = "not_applicable" +SUMMARY_FILE = "qualification-summary.json" + +# build_result is GitHub's conclusion for the archive's build job, in the feed's own vocabulary. +# Any other conclusion (failure, timed_out, startup_failure, ...) is "fail". +BUILD_PASS = "pass" +BUILD_FAIL = "fail" +BUILD_UNKNOWN = "unknown" +BUILD_RESULTS = {"success": BUILD_PASS, "cancelled": "cancelled", "skipped": "skipped"} + +# Why a placeholder row has no record, by its build_result. +PLACEHOLDER_REASONS = { + BUILD_FAIL: "build failed", + "cancelled": "build cancelled", + "skipped": "build skipped", +} +PLACEHOLDER_NO_REPORT = "no report" + +# build_id becomes a filename on the data branch, so it may only contain characters that cannot escape the folder it is written to. +_SAFE_ID = re.compile(r"^[A-Za-z0-9._-]+$") + +# The ROCm build jobs in build.yml. GitHub names a matrix job after its matrix values, the ROCm version first: +# "windows-latest-rocm (10.1.0, gfx1010;...)". Long names are cut short with "...", so only the first value is read. +_BUILD_JOBS = {"ubuntu-latest-rocm": "ubuntu", "windows-latest-rocm": "win"} +_BUILD_JOB = re.compile(r"^(?P[a-z0-9-]+) \((?P[^,)]+)") + + +def _int(value): + try: + return int(value) + except (TypeError, ValueError): + return None + + +def _run_order(run_id): + """GitHub run ids only grow, so they order runs by when they started. + + generated_at cannot: a re-run writes its records later than a newer run did. + """ + number = _int(run_id) + return number if number is not None else -1 + + +def load_records(records_dir): + """Return (records, summary) from the folder aggregate.py wrote.""" + records = [] + summary = None + for path in sorted(glob.glob(os.path.join(records_dir, "*.json"))): + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError) as exc: + print(f"::warning::skipping unreadable record {path}: {exc}") + continue + if os.path.basename(path) == SUMMARY_FILE: + summary = data + elif data.get("kind") == "qualification_record": + records.append(data) + return records, summary + + +def load_build_results(jobs_file): + """Map (os, rocm_version) -> result of its build job. + + jobs_file holds one {"name": ..., "conclusion": ...} object per line, as + `gh api .../jobs --jq '.jobs[] | {name, conclusion}'` prints them. + """ + results = {} + if not jobs_file: + return results + try: + with open(jobs_file, encoding="utf-8") as handle: + lines = handle.read().splitlines() + except OSError as exc: + print(f"::warning::could not read {jobs_file}: {exc}; build_result will be {BUILD_UNKNOWN!r}") + return results + for line in lines: + line = line.strip() + if not line: + continue + try: + job = json.loads(line) + except ValueError: + print(f"::warning::skipping unreadable job line {line!r}") + continue + match = _BUILD_JOB.match(job.get("name") or "") + if not match or match.group("job") not in _BUILD_JOBS: + continue + # "10.1.0" -> "10.1", the form the records and the feed use. + version = report.short_version(match.group("first").strip()) + conclusion = job.get("conclusion") + results[(_BUILD_JOBS[match.group("job")], version)] = ( + BUILD_RESULTS.get(conclusion, BUILD_FAIL) if conclusion else BUILD_UNKNOWN) + return results + + +def make_build_id(run_id, os_name, rocm_version, attempt=None): + """"--rocm-", or ".-..." for a re-run that + built a different tag than the rows already published for that run.""" + if not (run_id and os_name and rocm_version): + raise SystemExit( + f"::error::cannot form a build_id from run_id={run_id!r} os={os_name!r} " + f"rocm_version={rocm_version!r}") + run = f"{run_id}.{attempt}" if attempt else str(run_id) + build_id = f"{run}-{os_name}-rocm-{rocm_version}" + if not _SAFE_ID.match(build_id): + raise SystemExit(f"::error::refusing unsafe build_id {build_id!r}") + return build_id + + +def absent_status(record, test_id, final_checked): + """What a test the record does not contain is reported as.""" + if test_id in FINAL_TESTS and record.get("build", {}).get("artifact") not in final_checked: + return STATUS_NOT_APPLICABLE + return STATUS_MISSING + + +def tier_status(record, tier): + """pass | warn | fail for a tier that reported, otherwise missing.""" + if not aggregate.tier_reported(record, tier): + return STATUS_MISSING + return record["tiers"][tier].get("status") + + +def collect_results(record, final_checked): + """Per-test status across the known suite, plus any test it does not list.""" + by_id = {} + for tier in record.get("tiers", {}).values(): + for test in tier.get("tests", []): + by_id.setdefault(test.get("id"), test) + + results = {test_id: by_id[test_id]["status"] if test_id in by_id + else absent_status(record, test_id, final_checked) + for ids in TIER_TESTS.values() for test_id in ids} + for test_id in sorted((t for t in by_id if t not in results), key=report.test_order): + results[test_id] = by_id[test_id]["status"] + + blocking = sorted((test_id for test_id, test in by_id.items() + if test.get("gating") and test.get("status") == "fail"), + key=report.test_order) + return results, blocking + + +def make_placeholder(os_name, rocm_version, build_result, tag, upstream_sha, + run_id, run_attempt, generated_at): + """A record-shaped stand-in for an archive that has no record.""" + build = report.build_meta( + artifact=aggregate.published_name(tag, os_name, rocm_version), + os_name=os_name, + rocm_version=rocm_version, + sdcpp_tag=tag, + upstream_sha=upstream_sha, + run_id=run_id, + run_attempt=str(run_attempt) if run_attempt is not None else None, + ) + return { + "schema_version": report.SCHEMA_VERSION, + "kind": "qualification_placeholder", + "generated_at": generated_at, + "build": build, + "overall": report.STATUS_FAIL, + "promoted": False, + "counts": {report.STATUS_PASS: 0, report.STATUS_FAIL: 0, + report.STATUS_WARN: 0, report.STATUS_SKIP: 0, "total": 0}, + "tiers": {}, + "promotion": {"blocked_by": [PLACEHOLDER_REASONS.get(build_result, PLACEHOLDER_NO_REPORT)]}, + "build_result": build_result, + # No archive, so nothing was audited. The gfx target list lives in the build job. + "gfx": { + "requested": [], + "present_in_binary": [], + "missing_from_binary": [], + "hardware_validated": [], + }, + } + + +def build_entry(record, build_id, build_result, version_qualified, published, + final_checked, run_url, event, run_attempt): + """Derive the compact, dashboard-facing index row from a full record.""" + build = record.get("build", {}) + results, blocking = collect_results(record, final_checked) + statuses = list(results.values()) + + gfx = record.get("gfx", {}) + return { + "build_id": build_id, + "tag": build.get("sdcpp_tag"), + "upstream_sha": build.get("upstream_sha"), + "artifact": build.get("artifact"), + "os": build.get("os"), + "rocm_version": build.get("rocm_version"), + "gfx_target": build.get("gfx_target"), + "hardware_validated": bool(build.get("hardware_validated")), + "gfx": { + "requested": len(gfx.get("requested", [])), + "present": len(gfx.get("present_in_binary", [])), + "missing": gfx.get("missing_from_binary", []), + }, + "generated_at": record.get("generated_at"), + "run_id": build.get("run_id"), + # The attempt that published this row (a kept shipped row keeps its own). + "run_attempt": run_attempt if run_attempt is not None else _int(build.get("run_attempt")), + "run_url": run_url, + "event": event, + "build_result": build_result, + "tests": { + "passed": statuses.count("pass"), + "failed": statuses.count("fail"), + "warned": statuses.count("warn"), + "skipped": statuses.count("skip"), + "missing": statuses.count(STATUS_MISSING), + "not_applicable": statuses.count(STATUS_NOT_APPLICABLE), + "total": len(statuses), + }, + "qualified": bool(record.get("promoted")), + "version_qualified": version_qualified, + "published": published, + "overall": record.get("overall"), + "tier0": tier_status(record, "tier0"), + "tier1": tier_status(record, "tier1"), + "blocked_by": record.get("promotion", {}).get("blocked_by", []), + "blocking_tests": blocking, + "results": results, + "report_url": f"reports/{build_id}.json", + } + + +def write_json(path, data): + with open(path, "w", encoding="utf-8") as handle: + json.dump(data, handle, indent=2) + handle.write("\n") + + +def start_fresh_if_older(data_dir): + """Drop a feed written by an older schema_version instead of mixing rows of two shapes.""" + index_path = os.path.join(data_dir, "index.json") + if not os.path.exists(index_path): + return + with open(index_path, encoding="utf-8") as handle: + version = json.load(handle).get("schema_version") + if (_int(version) or 0) >= SCHEMA_VERSION: + return + print(f"The feed holds schema_version {version}; starting a fresh schema_version " + f"{SCHEMA_VERSION} feed. The old files stay in the branch's git history.") + os.remove(index_path) + for folder in ("reports", "latest"): + shutil.rmtree(os.path.join(data_dir, folder), ignore_errors=True) + + +def update_latest(path, record): + """Write the record unless the file already holds one from a newer run. + + Re-running an old run must not roll the status tile back to an older + result; a re-run of the same run replaces it. + """ + if os.path.exists(path): + try: + with open(path, encoding="utf-8") as handle: + current = json.load(handle).get("build", {}).get("run_id") + except (OSError, ValueError, AttributeError): + current = None + if _run_order(current) > _run_order(record.get("build", {}).get("run_id")): + return False + write_json(path, record) + return True + + +def read_index(index_path): + if os.path.exists(index_path): + with open(index_path, encoding="utf-8") as handle: + return json.load(handle) + return {} + + +def last_check(status, args, run_attempt): + """What the most recent nightly or release run decided, for the dashboard. + + status is "built" when the run built and qualified archives, "unchanged" + when a nightly found its tag already fully published and built nothing. + """ + run_url = (f"{args.server_url}/{args.repo}/actions/runs/{args.run_id}" + if args.repo and args.run_id else None) + return { + "status": status, + "tag": args.tag, + "upstream_sha": args.upstream_sha, + "run_id": args.run_id, + "run_attempt": run_attempt, + "run_url": run_url, + "event": args.event, + "checked_at": report.now_iso(), + } + + +def upsert_index(index_path, repo, entries, check=None): + """Replace-or-append each entry by build_id, newest run first.""" + index = read_index(index_path) + + replaced = {entry["build_id"] for entry in entries} + builds = [b for b in index.get("builds", []) if b.get("build_id") not in replaced] + builds.extend(entries) + # Newest run first; the archives within one run in a fixed, readable order. + builds.sort(key=lambda b: b.get("build_id") or "") + builds.sort(key=lambda b: _run_order(b.get("run_id")), reverse=True) + + out = { + "schema_version": SCHEMA_VERSION, + "repo": repo or index.get("repo"), + "updated_at": max((b.get("generated_at") or "" for b in builds), default="") or None, + "builds": builds, + } + # Like latest/, last_check never moves back to an older run: re-running an + # old run must not make the dashboard report it as the newest decision. + previous = index.get("last_check") + if check and previous and _run_order(previous.get("run_id")) > _run_order(check.get("run_id")): + print(f"last_check kept: it already holds newer run {previous.get('run_id')}") + check = previous + if check or previous: + out["last_check"] = check or previous + return out + + +def main(): + parser = argparse.ArgumentParser(description="Publish qualification records to the dashboard feed") + parser.add_argument("--mark-unchanged", action="store_true", + help="record only last_check: a nightly whose release was already complete") + parser.add_argument("--records-dir", + help="folder holding the qualification-*.json records aggregate.py wrote") + parser.add_argument("--data-dir", required=True, + help="the qualification/ folder of the qualification-data branch") + parser.add_argument("--operating-systems", default="", + help="the operating systems every ROCm version is built for, e.g. ubuntu,win") + parser.add_argument("--rocm-versions", default="", + help="the ROCm versions this run builds, e.g. 10.0,10.1,10.2") + parser.add_argument("--tag", required=True, help="the release tag this run pinned, master--") + parser.add_argument("--upstream-sha", help="the stable-diffusion.cpp commit this run pinned") + parser.add_argument("--jobs-file", + help="this run's jobs, one {name, conclusion} JSON object per line") + parser.add_argument("--published-artifacts", default="", + help="the ROCm archives the release job uploaded, space separated") + parser.add_argument("--final-checked", default="", + help="the ROCm archives the final-archive check (T0.12) ran on, space separated") + parser.add_argument("--event", default=os.environ.get("GITHUB_EVENT_NAME"), + help="what triggered the run, e.g. schedule or workflow_dispatch") + parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY"), + help="owner/name, used to build run_url") + parser.add_argument("--server-url", default=os.environ.get("GITHUB_SERVER_URL", "https://github.com")) + parser.add_argument("--run-id", default=os.environ.get("GITHUB_RUN_ID")) + parser.add_argument("--run-attempt", default=os.environ.get("GITHUB_RUN_ATTEMPT")) + args = parser.parse_args() + run_attempt = _int(args.run_attempt) + index_path = os.path.join(args.data_dir, "index.json") + + if args.mark_unchanged: + start_fresh_if_older(args.data_dir) + os.makedirs(args.data_dir, exist_ok=True) + index = upsert_index(index_path, args.repo, [], last_check("unchanged", args, run_attempt)) + write_json(index_path, index) + print(f"Recorded an unchanged nightly for {args.tag}; {len(index['builds'])} build(s) in the index") + return + if not (args.records_dir and args.operating_systems and args.rocm_versions): + parser.error("--records-dir, --operating-systems and --rocm-versions are required") + + expected = [(o, v) for v in aggregate.split_list(args.rocm_versions) + for o in aggregate.split_list(args.operating_systems)] + published_artifacts = set(args.published_artifacts.split()) + final_checked = set(args.final_checked.split()) + + records, summary = load_records(args.records_dir) + if summary is None: + print(f"::warning::no {SUMMARY_FILE} in {args.records_dir}; version_qualified will be null") + blocked_versions = set((summary or {}).get("blocked_rocm_versions") or []) + build_results = load_build_results(args.jobs_file) + if args.jobs_file and not build_results: + print(f"::warning::no ROCm build jobs found in {args.jobs_file}; build_result will be {BUILD_UNKNOWN!r}") + + # Placeholders share the run's timestamp, so every row of a run shows the same time. + run_time = max((r.get("generated_at") or "" for r in records), default="") or report.now_iso() + + covered = set() + items = [] # (record, build_id, is_placeholder) + for record in records: + build = record.get("build", {}) + key = (build.get("os"), build.get("rocm_version")) + covered.add(key) + items.append((record, make_build_id(build.get("run_id") or args.run_id, *key), False)) + for os_name, rocm_version in expected: + if (os_name, rocm_version) in covered: + continue + build_result = build_results.get((os_name, rocm_version), BUILD_UNKNOWN) + record = make_placeholder(os_name, rocm_version, build_result, args.tag, args.upstream_sha, + args.run_id, run_attempt, run_time) + items.append((record, make_build_id(args.run_id, os_name, rocm_version), True)) + + if not items: + raise SystemExit(f"::error::no qualification records in {args.records_dir} and no " + "expected archives; nothing to publish") + + start_fresh_if_older(args.data_dir) + os.makedirs(os.path.join(args.data_dir, "reports"), exist_ok=True) + os.makedirs(os.path.join(args.data_dir, "latest"), exist_ok=True) + + # A re-run of the same run (same build_id) finds the archives an earlier attempt + # shipped already in the release and cannot replace them. Its own record then + # describes rebuilt bytes that never shipped, so the earlier attempt's row and + # report -- which describe what users actually download -- are kept instead. + existing = {b.get("build_id"): b for b in read_index(index_path).get("builds", [])} + shipped = {k: b for k, b in existing.items() if b.get("published")} + + entries = [] + for record, build_id, is_placeholder in items: + build = record["build"] + # "Re-run all jobs" re-resolves upstream, so a re-run can build a new tag + # under the same run_id. Its rows then get their own build_id, so the rows + # of the tag the earlier attempt built (and maybe shipped) are not lost. + previous = existing.get(build_id) + if previous and previous.get("tag") != build.get("sdcpp_tag") and run_attempt: + build_id = make_build_id(build.get("run_id") or args.run_id, build.get("os"), + build.get("rocm_version"), run_attempt) + print(f"{build_id}: re-run built tag {build.get('sdcpp_tag')}, not " + f"{previous.get('tag')}; published as separate rows") + # Same tag only: a re-run of all jobs re-resolves upstream, and a new tag + # is a different build whose result must not be hidden. + old = shipped.get(build_id) + if (old and old.get("tag") == build.get("sdcpp_tag") + and build.get("artifact") not in published_artifacts): + entries.append(shipped[build_id]) + print(f"{build_id}: kept the row of the attempt that shipped it " + f"(attempt {shipped[build_id].get('run_attempt')})") + continue + run_url = (f"{args.server_url}/{args.repo}/actions/runs/{build.get('run_id') or args.run_id}" + if args.repo else None) + build_result = build_results.get((build.get("os"), build.get("rocm_version")), BUILD_UNKNOWN) + # An archive without a record can never let its version qualify. + if is_placeholder: + version_qualified = False + elif summary is None: + version_qualified = None + else: + version_qualified = build.get("rocm_version") not in blocked_versions + published = not is_placeholder and build.get("artifact") in published_artifacts + entry = build_entry(record, build_id, build_result, version_qualified, published, + final_checked, run_url, args.event, run_attempt) + entries.append(entry) + + write_json(os.path.join(args.data_dir, "reports", f"{build_id}.json"), record) + latest = os.path.join(args.data_dir, "latest", + f"{build['os']}-rocm-{build['rocm_version']}.json") + moved = update_latest(latest, record) + + tests = entry["tests"] + print(f"{build_id}: {tests['passed']}/{tests['total']} passed, " + f"{tests['failed']} failed, {tests['missing']} missing, " + f"build={build_result} qualified={entry['qualified']} " + f"version_qualified={entry['version_qualified']} published={entry['published']}" + f"{' (placeholder: ' + ', '.join(entry['blocked_by']) + ')' if is_placeholder else ''}" + f"{'' if moved else ' (latest/ kept: it already holds a newer run)'}") + + index = upsert_index(index_path, args.repo, entries, last_check("built", args, run_attempt)) + write_json(index_path, index) + print(f"Published {len(entries)} row(s); {len(index['builds'])} build(s) in the index") + + +if __name__ == "__main__": + main() diff --git a/.github/qualify-rocm/release_assets.py b/.github/qualify-rocm/release_assets.py new file mode 100644 index 0000000000..6b2a8534e4 --- /dev/null +++ b/.github/qualify-rocm/release_assets.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +""" +Which release assets make up each backend family, and whether a family is complete. + +A family is a set of archives that only makes sense together: the eight CUDA +architectures on Linux x64 and Windows x64 plus the sm_121 (GB10) Linux arm64 +build, the CPU builds for Linux and Windows, and so on. Windows Vulkan and the +all-architecture Windows CUDA 12 build (with its runtime zip) are families of +their own, so a failure there never withholds the Linux builds. Each family ships as a complete set or not at all, so a consumer never +finds half of one. Families are independent of each other, and each ROCm +version is a family of its own -- a consumer downloads exactly one ROCm +version, so a gap in 10.2 is no reason to withhold a good 10.0. What must stay +together is the Windows + Linux pair within a version. + +The rules live here, in one place, because two jobs need them: + + check-dir the release job: drop every incomplete family from the folder + of built artifacts before anything is uploaded. Exits non-zero + only when nothing at all is left to publish. + check-release the resolve-upstream job, on a nightly: does the release for + this tag already hold every family (and checksums.txt)? If so, + the nightly has nothing to add and skips the whole build. + +Keep the lists in step with the build matrices in build.yml. + +Usage: + python3 release_assets.py check-dir --dir artifact --branch master \ + --short abc1234 --rocm-versions 10.0,10.1,10.2 + python3 release_assets.py check-release --names-file assets.txt --branch master \ + --short abc1234 --rocm-versions 10.0,10.1,10.2 +""" + +import argparse +import fnmatch +import os +import sys + +CUDA_ARCHS = ["sm_75", "sm_80", "sm_86", "sm_89", "sm_90", "sm_100", "sm_120", "sm_121"] + + +def families(branch, short, rocm_versions): + p = f"sd-{branch}-{short}" + cuda = [] + for sm in CUDA_ARCHS: + cuda += [f"{p}-ubuntu-cuda-{sm}-x64.tar.xz", f"{p}-windows-cuda-{sm}-x64.zip"] + cuda.append(f"{p}-ubuntu-cuda-sm_121-arm64.tar.xz") + out = {"cuda": cuda} + for version in rocm_versions: + out[f"rocm-{version}"] = [f"{p}-bin-win-rocm-{version}.0-x64.zip", + f"{p}-bin-Linux-Ubuntu-24.04-x86_64-rocm-{version}.0.zip"] + out["cpu"] = [f"{p}-bin-Linux-*-x86_64.zip", f"{p}-bin-win-cpu-x64.zip"] + out["vulkan"] = [f"{p}-bin-Linux-*-x86_64-vulkan.zip"] + # Separate from Linux Vulkan, so a failed Windows build does not withhold Linux. + out["vulkan-win"] = [f"{p}-bin-win-vulkan-x64.zip"] + # The all-architecture Windows CUDA 12 build and the CUDA runtime it needs. + out["cuda12-win"] = [f"{p}-bin-win-cuda12-x64.zip", "cudart-sd-bin-win-cu12-x64.zip"] + out["metal"] = [f"{p}-bin-Darwin-macOS-*-arm64.zip"] + return out + + +def missing_by_family(names, fams): + return {family: [pat for pat in patterns if not fnmatch.filter(names, pat)] + for family, patterns in fams.items()} + + +def write_outputs(**values): + path = os.environ.get("GITHUB_OUTPUT") + if path: + with open(path, "a", encoding="utf-8") as handle: + for key, value in values.items(): + handle.write(f"{key}={value}\n") + + +def check_dir(args, fams): + names = sorted(os.listdir(args.dir)) + missing, summary = 0, [] + for family, patterns in missing_by_family(names, fams).items(): + for pattern in patterns: + print(f"::error::[{family}] Missing artifact: {pattern}") + if not patterns: + continue + print(f"::warning::{family} family is incomplete ({len(patterns)} artifact(s) missing) " + f"- dropping all {family} artifacts from this release.") + for pattern in fams[family]: + for name in fnmatch.filter(names, pattern): + os.remove(os.path.join(args.dir, name)) + print(f"removed {name}") + missing += len(patterns) + summary.append(f"{family}: {len(patterns)} missing, family dropped") + + write_outputs(missing=missing, summary=", ".join(summary)) + left = [n for n in os.listdir(args.dir) if n.endswith((".zip", ".tar.xz"))] + if not left: + print(f"::error::No release artifacts left in {args.dir}; refusing to publish nothing.") + sys.exit(1) + print(f"{len(left)} artifact(s) ready to publish" + (f"; {', '.join(summary)}" if summary else "")) + + +def check_release(args, fams): + with open(args.names_file, encoding="utf-8") as handle: + names = [line.strip() for line in handle if line.strip()] + gaps = {f: m for f, m in missing_by_family(names, fams).items() if m} + if "checksums.txt" not in names: + gaps["checksums"] = ["checksums.txt"] + for family, patterns in gaps.items(): + print(f"[{family}] not yet published: {', '.join(patterns)}") + write_outputs(complete="false" if gaps else "true") + print("The release already holds every family." if not gaps else "The release is incomplete.") + + +def main(): + parser = argparse.ArgumentParser(description="Check which backend families are complete") + parser.add_argument("mode", choices=["check-dir", "check-release"]) + parser.add_argument("--branch", required=True) + parser.add_argument("--short", required=True, help="fork commit in the asset names") + parser.add_argument("--rocm-versions", required=True, help="X.Y, e.g. 10.0,10.1,10.2") + parser.add_argument("--dir", help="check-dir: folder of built artifacts") + parser.add_argument("--names-file", help="check-release: asset names, one per line") + args = parser.parse_args() + fams = families(args.branch, args.short, + [v for v in args.rocm_versions.replace(" ", "").split(",") if v]) + (check_dir if args.mode == "check-dir" else check_release)(args, fams) + + +if __name__ == "__main__": + main() diff --git a/.github/qualify-rocm/release_notes.py b/.github/qualify-rocm/release_notes.py new file mode 100644 index 0000000000..f2247471e7 --- /dev/null +++ b/.github/qualify-rocm/release_notes.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +""" +Write the release notes from the assets actually attached to the release, so a +family that was withheld gets no link and is listed under "Not in this release". + +The layout follows lemonade-sdk/llama.cpp's release notes: the summary in an +open
block, then a table per Linux architecture (package, the oldest +Ubuntu it starts on, download links), a list for Windows, and a list for macOS. + +The notes are written AFTER the upload, from the release's real asset list, +rather than from the files this run meant to upload. A nightly may be filling +the gaps of an earlier, incomplete run of the same tag, so the release can hold +files this run did not build; and a ROCm version is only linked when both its +Windows and Linux archives are attached, because it ships as a pair or not at +all. + +Usage: + python3 release_notes.py --tag master-1106-abc1234 --repo lemonade-sdk/stable-diffusion.cpp \ + --assets-file assets.txt --rocm-versions 10.0,10.1,10.2 --summary "..." --output notes.md +""" + +import argparse +import re + +# Oldest OS each package starts on, set by the runner image its build job uses. +LINUX_X64_RUNS_ON = "Ubuntu 24.04 or newer" +CUDA_X64_RUNS_ON = "Ubuntu 22.04 or newer" +CUDA_ARM64_RUNS_ON = "Ubuntu 24.04 or newer" + + +def render(tag, repo, names, rocm_versions, summary): + branch, _count, short = tag.split("-") + p = re.escape(f"sd-{branch}-{short}") + attached = set(names) + url = lambda name: f"https://github.com/{repo}/releases/download/{tag}/{name}" # noqa: E731 + link = lambda label, name: f"[{label}]({url(name)})" # noqa: E731 + + def first(pattern): + return next((n for n in sorted(names) if re.fullmatch(pattern, n)), None) + + def cuda(platform, suffix): + found = sorted(((int(m.group(1)), m.group(0)) for m in + (re.fullmatch(rf"{p}-{platform}-cuda-sm_(\d+)-{suffix}", n) for n in names) if m)) + return [link(f"sm_{sm}", name) for sm, name in found] + + rocm = {v: {"ubuntu": f"sd-{branch}-{short}-bin-Linux-Ubuntu-24.04-x86_64-rocm-{v}.0.zip", + "win": f"sd-{branch}-{short}-bin-win-rocm-{v}.0-x64.zip"} for v in rocm_versions} + cpu_linux = first(rf"{p}-bin-Linux-[^/]+-x86_64\.zip") + vulkan_linux = first(rf"{p}-bin-Linux-[^/]+-x86_64-vulkan\.zip") + metal = first(rf"{p}-bin-Darwin-macOS-[^/]+-arm64\.zip") + win = {key: name for key, name in { + "cpu": f"sd-{branch}-{short}-bin-win-cpu-x64.zip", + "vulkan": f"sd-{branch}-{short}-bin-win-vulkan-x64.zip", + "cuda12": f"sd-{branch}-{short}-bin-win-cuda12-x64.zip", + "cudart": "cudart-sd-bin-win-cu12-x64.zip"}.items() if name in attached} + + linux_x64 = [] + if cpu_linux: + linux_x64.append(["CPU", LINUX_X64_RUNS_ON, link("download", cpu_linux)]) + if vulkan_linux: + linux_x64.append(["Vulkan", LINUX_X64_RUNS_ON, link("download", vulkan_linux)]) + # A ROCm version is linked only as a complete Windows + Linux pair. + paired = {v: n for v, n in rocm.items() if n["ubuntu"] in attached and n["win"] in attached} + linux_x64 += [[f"ROCm {v}.0", LINUX_X64_RUNS_ON, link("download", names_["ubuntu"])] + for v, names_ in paired.items()] + if cuda("ubuntu", r"x64\.tar\.xz"): + linux_x64.append(["CUDA", CUDA_X64_RUNS_ON, " ".join(cuda("ubuntu", r"x64\.tar\.xz"))]) + linux_arm64 = ([["CUDA", CUDA_ARM64_RUNS_ON, " ".join(cuda("ubuntu", r"arm64\.tar\.xz"))]] + if cuda("ubuntu", r"arm64\.tar\.xz") else []) + + def table(title, rows): + if not rows: + return [] + return [f"**{title}**", "", "| Package | Runs on | Download |", "|---|---|---|", + *[f"| {' | '.join(r)} |" for r in rows], ""] + + win_rocm = [link(f"{v}.0", n["win"]) for v, n in paired.items()] + windows = [] + if "cpu" in win: + windows.append(f"- CPU: {link('download', win['cpu'])}") + if "vulkan" in win: + windows.append(f"- Vulkan: {link('download', win['vulkan'])}") + if win_rocm: + windows.append(f"- ROCm: {' | '.join(win_rocm)}") + if "cuda12" in win: + runtime = f" (runtime: {link('cudart', win['cudart'])})" if "cudart" in win else "" + windows.append(f"- CUDA 12, all architectures: {link('download', win['cuda12'])}{runtime}") + win_cuda = cuda("windows", r"x64\.zip") + if win_cuda: + windows.append(f"- CUDA: {' | '.join(win_cuda)}") + + missing = [f"- ROCm {v}.0: did not build, or did not pass the release checks. The " + "attached `qualification-*.json` records list the failing checks." + for v in rocm if v not in paired] + if not any("-cuda-sm_" in n for n in names): + missing.append("- CUDA (per-architecture builds): at least one CUDA architecture failed " + "to build, so no per-architecture CUDA builds are included.") + if not cpu_linux or "cpu" not in win: + missing.append("- CPU: did not build.") + if not vulkan_linux: + missing.append("- Vulkan (Linux): did not build.") + if "vulkan" not in win: + missing.append("- Vulkan (Windows): did not build.") + if "cuda12" not in win: + missing.append("- CUDA 12, all architectures (Windows): did not build.") + if not metal: + missing.append("- Metal: did not build.") + + body = ["
", "", summary, "", "
", "", + *table("Linux x64", linux_x64), *table("Linux arm64", linux_arm64), + *(["**Windows x64**", *windows, ""] if windows else []), + *(["**macOS arm64**", f"- Metal: {link('download', metal)}", ""] if metal else [])] + if paired: + body += [f"ROCm packages need the ROCm runtime of the same version, installed " + f"separately: see [Using the ROCm builds](https://github.com/{repo}" + f"#using-the-rocm-builds). [Lemonade](https://github.com/lemonade-sdk/lemonade) " + f"installs it automatically.", ""] + if missing: + body += ["**Not in this release**", *missing] + return "\n".join(body).rstrip() + "\n" + + +def main(): + parser = argparse.ArgumentParser(description="Render release notes") + parser.add_argument("--tag", required=True) + parser.add_argument("--repo", required=True) + parser.add_argument("--assets-file", required=True) + parser.add_argument("--rocm-versions", required=True, help="X.Y, e.g. 10.0,10.1,10.2") + parser.add_argument("--summary", default="") + parser.add_argument("--output", required=True) + args = parser.parse_args() + with open(args.assets_file, encoding="utf-8") as handle: + names = [line.strip() for line in handle if line.strip()] + versions = [v for v in args.rocm_versions.replace(" ", "").split(",") if v] + body = render(args.tag, args.repo, names, versions, args.summary) + with open(args.output, "w", encoding="utf-8") as handle: + handle.write(body) + print(body) + + +if __name__ == "__main__": + main() diff --git a/.github/qualify-rocm/report.py b/.github/qualify-rocm/report.py new file mode 100644 index 0000000000..a2549a994d --- /dev/null +++ b/.github/qualify-rocm/report.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +""" +Shared reporting for the ROCm build-qualification suite. + +Every tier emits a JSON *fragment* with an identical schema; `aggregate.py` +merges the fragments for one artifact into a single qualification record that +is attached to the GitHub release. + +The schema is deliberately flat and stable so a dashboard could consume it +later without reshaping: + + - Every test has a stable `id` ("T0.3", "T1.2") that never changes meaning. + - `status` is always one of the STATUS_* values below. + - Numbers live under `details` as numbers, never strings. + - `gating` says whether a FAIL blocks the ROCm family from the release. + +This module is stdlib-only: Tier 1 runs on self-hosted machines where nothing +is installed but ROCm itself. +""" + +import datetime +import json +import os +import re +import sys +import time +import traceback + +SCHEMA_VERSION = 1 + +STATUS_PASS = "pass" +STATUS_FAIL = "fail" +STATUS_WARN = "warn" +STATUS_SKIP = "skip" + +_SEVERITY = {STATUS_SKIP: 0, STATUS_PASS: 1, STATUS_WARN: 2, STATUS_FAIL: 3} + +TIER_NAMES = { + "tier0": "Static artifact verification", + "tier1": "GPU functional inference", +} + + +def now_iso(): + """Current UTC time as an ISO-8601 string with a trailing 'Z'.""" + return ( + datetime.datetime.now(datetime.timezone.utc) + .replace(microsecond=0) + .isoformat() + .replace("+00:00", "Z") + ) + + +def short_version(version): + """'10.1.0' -> '10.1': the ROCm version as records and the feed write it. + + Release asset names carry the full version, the dashboard's ROCm tracks the + short one, so every record stores the short form. + """ + return ".".join(str(version).split(".")[:2]) if version else version + + +def test_order(test_id): + """Sort "T0.10" after "T0.9", and unknown ids after known ones.""" + match = re.match(r"^T(\d+)\.(\d+)$", test_id or "") + if match: + return (int(match.group(1)), int(match.group(2)), "") + return (sys.maxsize, sys.maxsize, test_id or "") + + +def build_meta( + artifact, + os_name=None, + rocm_version=None, + sdcpp_tag=None, + upstream_sha=None, + gfx_target=None, + hardware_validated=False, + run_id=None, + run_attempt=None, +): + """Per-artifact metadata block shared by every fragment. + + `artifact` is the release asset filename, which is the only identifier a + user filing a bug report will have in front of them. + """ + build_id = artifact or "local" + if run_id: + build_id = f"{build_id}@{run_id}" + return { + "build_id": build_id, + "artifact": artifact, + "os": os_name, + "rocm_version": short_version(rocm_version), + # The release tag, master--. + "sdcpp_tag": sdcpp_tag, + # The upstream stable-diffusion.cpp commit this archive was built from. + # Pinned once per run, so every artifact in a release reports the same one. + "upstream_sha": upstream_sha, + "gfx_target": gfx_target, + "hardware_validated": bool(hardware_validated), + "run_id": run_id, + "run_attempt": run_attempt, + } + + +class TierReport: + """Collects test results for one tier and serializes a JSON fragment.""" + + def __init__(self, tier, meta): + if tier not in TIER_NAMES: + raise ValueError(f"unknown tier {tier!r}") + self.tier = tier + self.meta = meta + self.tests = [] + self._started = time.monotonic() + self._generated_at = now_iso() + + def add(self, test_id, name, status, gating=True, duration_ms=None, + error=None, details=None): + """Record a single test result.""" + if status not in _SEVERITY: + raise ValueError(f"invalid status {status!r}") + self.tests.append({ + "id": test_id, + "name": name, + "tier": self.tier, + "status": status, + "gating": bool(gating), + "duration_ms": duration_ms, + "error": error, + "details": details or {}, + }) + return status + + def run(self, test_id, name, fn, gating=True): + """Run a check function, timing it and trapping exceptions. + + `fn` returns a status string, or (status, error), or + (status, error, details). A raised exception is recorded as a FAIL with + the traceback in details, so one broken check never aborts the tier -- + we always want the full picture of a bad build in one run. + """ + start = time.monotonic() + try: + result = fn() + if isinstance(result, str): + status, error, details = result, None, None + elif len(result) == 2: + (status, error), details = result, None + else: + status, error, details = result + except Exception as exc: # noqa: BLE001 - capture everything + status = STATUS_FAIL + error = f"{type(exc).__name__}: {exc}" + details = {"traceback": traceback.format_exc()} + duration_ms = int((time.monotonic() - start) * 1000) + return self.add(test_id, name, status, gating=gating, + duration_ms=duration_ms, error=error, details=details) + + def status_of(self, test_id): + """Status of a recorded test, or None if it was not recorded.""" + return next((t["status"] for t in self.tests if t["id"] == test_id), None) + + def counts(self): + out = {STATUS_PASS: 0, STATUS_FAIL: 0, STATUS_WARN: 0, STATUS_SKIP: 0, + "total": len(self.tests)} + for test in self.tests: + out[test["status"]] += 1 + return out + + def rollup_status(self): + """Tier status = worst severity among *gating* tests.""" + worst = STATUS_PASS + for test in self.tests: + if not test["gating"]: + continue + if _SEVERITY[test["status"]] > _SEVERITY[worst]: + worst = test["status"] + return worst + + def to_dict(self): + return { + "schema_version": SCHEMA_VERSION, + "kind": "tier_fragment", + "tier": self.tier, + "tier_name": TIER_NAMES[self.tier], + "status": self.rollup_status(), + "generated_at": self._generated_at, + "duration_ms": int((time.monotonic() - self._started) * 1000), + "build": self.meta, + "counts": self.counts(), + "tests": sorted(self.tests, key=lambda t: test_order(t["id"])), + } + + def write(self, path): + parent = os.path.dirname(os.path.abspath(path)) + os.makedirs(parent, exist_ok=True) + with open(path, "w", encoding="utf-8") as handle: + json.dump(self.to_dict(), handle, indent=2) + handle.write("\n") + + def print_summary(self): + """Human-readable summary to stdout (the CI log).""" + rollup = self.rollup_status() + print(f"\n=== {self.tier} ({TIER_NAMES[self.tier]}): {rollup.upper()} ===") + for test in sorted(self.tests, key=lambda t: test_order(t["id"])): + gate = "" if test["gating"] else " (non-gating)" + line = f" [{test['status'].upper()}] {test['id']} {test['name']}{gate}" + if test["error"]: + line += f" -- {test['error']}" + print(line) + counts = self.counts() + print(f" totals: {counts[STATUS_PASS]} pass, {counts[STATUS_FAIL]} fail, " + f"{counts[STATUS_WARN]} warn, {counts[STATUS_SKIP]} skip") + + +def merge_fragments(fragments, extra_meta=None): + """Merge per-tier fragments for one artifact into one record.""" + fragments = sorted(fragments, key=lambda frag: frag.get("tier", "")) + meta = {} + for frag in fragments: + for key, value in frag.get("build", {}).items(): + # Never let a tier that did not touch hardware clear the flag a + # tier that did has already set. + if key == "hardware_validated": + meta[key] = bool(meta.get(key)) or bool(value) + elif value is not None or key not in meta: + meta[key] = value + if extra_meta: + meta.update({k: v for k, v in extra_meta.items() if v is not None}) + + tiers = {} + for frag in fragments: + tier = frag["tier"] + bucket = tiers.setdefault(tier, { + "status": STATUS_SKIP, + "tier_name": frag.get("tier_name"), + "counts": {}, + "tests": [], + }) + seen = {t.get("id") for t in bucket["tests"]} + for test in frag.get("tests", []): + # Identical ids from a re-run would double-count; keep the first. + if test.get("id") in seen: + continue + bucket["tests"].append(test) + seen.add(test.get("id")) + # Fragments arrive in file-name order, which put the release job's + # post-merge checks first; list every tier's tests by id instead. + for bucket in tiers.values(): + bucket["tests"].sort(key=lambda test: test_order(test.get("id"))) + + overall = STATUS_PASS + totals = {STATUS_PASS: 0, STATUS_FAIL: 0, STATUS_WARN: 0, STATUS_SKIP: 0, "total": 0} + for tier, bucket in tiers.items(): + counts = {STATUS_PASS: 0, STATUS_FAIL: 0, STATUS_WARN: 0, STATUS_SKIP: 0, + "total": len(bucket["tests"])} + status = STATUS_PASS + for test in bucket["tests"]: + counts[test["status"]] += 1 + if test.get("gating") and _SEVERITY[test["status"]] > _SEVERITY[status]: + status = test["status"] + bucket["counts"] = counts + bucket["status"] = status + if _SEVERITY[status] > _SEVERITY[overall]: + overall = status + for key, value in counts.items(): + totals[key] = totals.get(key, 0) + value + + return { + "schema_version": SCHEMA_VERSION, + "kind": "qualification_record", + "generated_at": now_iso(), + "build": meta, + "overall": overall, + "promoted": False, + "counts": totals, + "tiers": tiers, + } diff --git a/.github/qualify-rocm/tier0_static.py b/.github/qualify-rocm/tier0_static.py new file mode 100644 index 0000000000..dcc3fd63a8 --- /dev/null +++ b/.github/qualify-rocm/tier0_static.py @@ -0,0 +1,737 @@ +#!/usr/bin/env python3 +""" +Tier 0 -- static verification of a published ROCm archive. No GPU required. + +Runs on a free hosted runner against the ARCHIVE WE ARE ABOUT TO PUBLISH, not +against the build tree. That distinction matters because every bug this tier +exists to catch -- a dropped gfx target, a missing library, a leaked build +path, a missing licence -- is invisible in the build tree and only appears in +the packaged bytes. + +The two operating systems are packaged differently, and the checks follow suit: + - Linux: a zip of build/bin/ (versioned .so names stored as symlinks). + ggml loads its HIP backend, libggml-hip.so, as a plug-in. + - Windows: a flat zip. ggml's HIP backend is linked into + stable-diffusion.dll, and the HIP runtime itself (amdhip64_7.dll, + amd_comgr.dll, rocm_kpack.dll) ships next to sd-server.exe. +Neither archive contains ROCm's math libraries (hipBLAS, hipBLASLt, rocBLAS); +the user installs those, and Lemonade does it automatically. + +Checks: + T0.1 archive contents -- every file a user needs is present: + sd-cli, sd-server, the stable-diffusion + and ggml libraries, the licences, and on + Windows the bundled HIP runtime. + T0.2 HIP code present -- the file holding the GPU code exists and + is large enough to contain it. + T0.3 gfx target audit -- that file really contains code for every + gfx target the build asked for. + See binfmt.py for how and why. + T0.4 CPU backend variants -- Linux only: ggml-cpu-* present. Windows + links the CPU backend in. + T0.5 runtime dependency survey -- every non-ROCm dependency resolves from + the archive or the base system; the ROCm + ones are recorded as expected-external. + T0.6 Linux version support -- Linux only. The archive must not require + a newer C library than the oldest + distribution we support. + T0.7 library search path -- Linux only. No absolute build-machine + folder in the binaries' library search + path (RUNPATH/RPATH); only $ORIGIN. + T0.8 sd-server flag surface -- the flags Lemonade launches sd-server + with, and the one Tier 1 relies on, are + all still accepted (needs --run-binaries). + T0.9 upstream provenance -- sd-server reports the upstream commit this + run pinned (needs --run-binaries). + T0.10 ROCm dependency resolution -- the ROCm libraries this archive needs + exist in the ROCm a user will install + (needs --rocm-dirs). + T0.11 bundled HIP runtime -- the HIP runtime shipped in the archive is + byte-identical to that ROCm version's own + copy (needs --rocm-dirs). + +T0.12 (final archive integrity) is emitted separately by check_final.py, which +runs in the release job on the exact files about to be uploaded. + +Test ids are this repository's own: they do not share meanings with lemonade-sdk/llama.cpp's, +and an id is never reused for a different check. + +Usage: + python3 tier0_static.py --meta meta/qualify-meta-win-rocm-10.1.json \ + --archive-dir ./artifact --run-binaries --output tier0-win-rocm-10.1.json + + python3 tier0_static.py --archive sd-master-abc1234-bin-win-rocm-10.1.0-x64.zip \ + --os win --rocm-version 10.1.0 --gpu-targets "gfx1010;...;gfx1201" \ + --upstream-sha --run-binaries --rocm-dirs "" --output tier0.json +""" + +import argparse +import fnmatch +import hashlib +import json +import os +import re +import shutil +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import archive # noqa: E402 +import binfmt # noqa: E402 +import report # noqa: E402 + +# Files a consumer needs, by exact name at the top of the archive's binary folder. +# The unversioned Linux .so names are symlinks in the zip; they still +# count, because that is the name the binaries ask the loader for. +REQUIRED_FILES = { + "ubuntu": ["sd-cli", "sd-server", "libstable-diffusion.so", "libggml.so", + "libggml-base.so", "libggml-hip.so", "ggml.txt", "stable-diffusion.cpp.txt"], + "win": ["sd-cli.exe", "sd-server.exe", "stable-diffusion.dll", "ggml.txt", + "stable-diffusion.cpp.txt", "amdhip64_7.dll", "amd_comgr.dll", "rocm_kpack.dll"], +} + +# The file that holds the GPU code. Linux builds ggml with GGML_BACKEND_DL, so +# its HIP backend is a separate plug-in; the Windows ROCm build does not, so the +# HIP backend is linked into stable-diffusion.dll. +HIP_CODE = {"ubuntu": "libggml-hip.so", "win": "stable-diffusion.dll"} + +# Other binaries that carry HIP kernels of their own. libstable-diffusion.so +# compiles some of stable-diffusion.cpp's own GPU code, so it is audited too -- +# but only when it carries any, so an upstream change that moves that code +# elsewhere does not read as a broken audit. +OTHER_HIP_CODE = {"ubuntu": ["libstable-diffusion.so"], "win": []} + +# A multi-target HIP fat binary is around a gigabyte. Anything below this holds +# little or no GPU code. +MIN_HIP_CODE_BYTES = 64 << 20 + +CPU_VARIANT_GLOB = "libggml-cpu-*.so" + +# The HIP runtime shipped next to sd-server.exe since TheRock#7691: Windows +# looks for DLLs in the program's folder first, so this keeps a stale +# amdhip64_7.dll from the display driver in System32 from being picked instead. +# Linux ships none. +BUNDLED_HIP_RUNTIME = {"ubuntu": [], "win": ["amdhip64_7.dll", "amd_comgr.dll", "rocm_kpack.dll"]} + +# Libraries that come with any Linux installation, so the archive does not and +# should not carry them. +BASE_LIBS_LINUX = { + "libc.so.6", "libm.so.6", "libdl.so.2", "librt.so.1", "libpthread.so.0", + "libstdc++.so.6", "libgcc_s.so.1", "ld-linux-x86-64.so.2", "libutil.so.1", + "libresolv.so.2", "libgomp.so.1", +} +# Windows DLLs supplied by the OS or the MSVC redistributable. gdi32 and ntdll +# are needed by the bundled HIP runtime, which llama.cpp's archives do not ship. +BASE_DLLS_WIN = ("kernel32", "user32", "gdi32", "advapi32", "ws2_32", "shell32", + "ole32", "oleaut32", "bcrypt", "crypt32", "dbghelp", "ntdll", + "msvcp140", "vcruntime140", "vcruntime140_1", "msvcrt", + "api-ms-win-", "ucrtbase", "concrt140", "powrprof", + "psapi", "setupapi", "cfgmgr32", "version", "winmm") + +# ROCm libraries. Apart from the bundled HIP runtime these are deliberately NOT +# in the archive: the user installs ROCm, and stable-diffusion.cpp loads it from +# there at run time. T0.5 records which ones an archive needs; T0.10 confirms +# they exist in the ROCm that will actually be installed. hipBLASLt is named +# libhipblaslt.dll on Windows, hence both spellings. +ROCM_LIB_PREFIXES = ( + "libamdhip64", "libhipblas", "librocblas", "libhipblaslt", "librocsolver", + "libamd_comgr", "libhsa-runtime64", "librocm", "libroctx", "librocprofiler", +) +ROCM_DLL_PREFIXES = ( + "amdhip64", "hipblas", "libhipblas", "rocblas", "hipblaslt", "libhipblaslt", + "rocsolver", "amd_comgr", "amdhsa", "rocm", +) + +# --- oldest Linux we support ------------------------------------------------ +# The Linux ROCm artifact is built on Ubuntu 24.04, which is also the oldest +# release Lemonade supports. Ubuntu 24.04 ships glibc 2.39, so an archive that +# needs anything newer than that would fail to start even on a supported machine. +# +# Raise this only together with the runner image in the build job, and only +# after deciding that dropping the older distributions is acceptable. See +# binfmt.elf_glibc_floor() for what this number means. +SUPPORTED_GLIBC = (2, 39) +SUPPORTED_DISTRO = "Ubuntu 24.04" + +# Flags Lemonade passes to a ROCm sd-server +# (lemonade-sdk/lemonade src/cpp/server/backends/sdcpp/sdcpp_server.cpp). +# This repo rebuilds upstream every night, so a rename should fail here within +# a day rather than surfacing as a Lemonade bug. +LEMONADE_SERVER_FLAGS = [ + "--listen-port", "-m", "--model", "--diffusion-model", "--llm", "--vae", + # Raises the log level to verbose. Lemonade passes it only in debug mode, but + # it is listed because Tier 1 depends on it: without it sd-server never + # prints where it put the weights or its compute buffers, and the GPU check + # has nothing to inspect. If upstream renames it, failing here names the + # cause instead of leaving Tier 1 to report a confusing absence of evidence. + "-v", +] + +# The first line of `sd-server --help`: +# "stable-diffusion.cpp version master-1106-532d2c1, commit 532d2c1" +VERSION_RE = re.compile(r"stable-diffusion\.cpp version (\S+), commit ([0-9a-f]+)") + + +# --------------------------------------------------------------------------- +# Archive handling +# --------------------------------------------------------------------------- + +def exe(name, os_name): + return f"{name}.exe" if os_name == "win" else name + + +def listing(root): + return sorted(os.listdir(root)) + + +def binaries(root): + """Every regular file at the top of the archive's binary folder, symlinks excluded. + """ + for name in listing(root): + path = os.path.join(root, name) + if os.path.isfile(path) and not os.path.islink(path): + yield name, path + + +def sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def rocm_env(rocm_dirs, root, os_name): + """The environment to launch an archive binary with: the user-style ROCm + first, then the archive folder, exactly the search order Lemonade sets up. + """ + env = dict(os.environ) + joined = os.pathsep.join(rocm_dirs + [root]) + key = "PATH" if os_name == "win" else "LD_LIBRARY_PATH" + env[key] = joined + os.pathsep + env.get(key, "") + return env + + +# --------------------------------------------------------------------------- +# Checks +# --------------------------------------------------------------------------- + +def check_contents(root, os_name): + """T0.1: every file a consumer needs is present. + + The tools Lemonade launches, the libraries they load, the two licence files + every other zip this repository publishes carries, and on Windows the HIP + runtime shipped next to sd-server.exe. Any `test-*` file means upstream's + unit tests leaked into the archive, which is worth a warning but harmless. + """ + files = set(listing(root)) + missing = [f for f in REQUIRED_FILES[os_name] if f not in files] + tests = sorted(f for f in files if f.startswith("test-")) + details = {"entries": len(files), "missing": missing, + "test_binaries_shipped": len(tests), "test_binaries": tests[:10]} + if missing: + return (report.STATUS_FAIL, f"missing from archive: {', '.join(missing)}", details) + if tests: + return (report.STATUS_WARN, + f"{len(tests)} upstream test binary/binaries shipped to users", details) + return (report.STATUS_PASS, None, details) + + +def check_hip_code(root, os_name): + """T0.2: the file holding the GPU code exists and is big enough to hold it. + + A HIP compile that silently produced nothing still leaves a file behind; on + Windows stable-diffusion.dll would even exist without any GPU code at all, so + the size is what tells the two apart. + """ + name = HIP_CODE[os_name] + path = os.path.join(root, name) + details = {"binary": name, "exists": os.path.exists(path)} + if not details["exists"]: + return (report.STATUS_FAIL, f"{name} is missing -- the HIP build failed or was " + "dropped at packaging", details) + details["bytes"] = os.path.getsize(path) + if details["bytes"] < MIN_HIP_CODE_BYTES: + return (report.STATUS_FAIL, f"{name} is only {details['bytes'] / 1e6:.1f} MB; a " + "multi-target HIP fat binary is ~1 GB, so it holds little or no GPU code", + details) + return (report.STATUS_PASS, None, details) + + +def check_gfx_targets(root, os_name, gpu_targets): + """T0.3: the GPU code covers every gfx target the build asked for. + + `gpu_targets` is the build job's own matrix entry, carried in the + qualify-meta JSON, so each OS is compared against the list it was compiled + with. A missing target is silent at run time: users with that GPU get the CPU. + + An audit that finds nothing at all means the METHOD is broken (the toolchain + changed the bundle entry format), and that must fail loudly rather than pass. + Uneven per-target counts mean a target reached only some translation units, + which is a warning. + """ + path = os.path.join(root, HIP_CODE[os_name]) + if not os.path.exists(path): + return (report.STATUS_FAIL, f"{HIP_CODE[os_name]} missing (see T0.2)", {}) + expected = [t for t in re.split(r"[;,\s]+", gpu_targets or "") if t] + if not expected: + return (report.STATUS_FAIL, "no expected gfx target list was supplied", {}) + + result = binfmt.audit_gfx_targets(path, expected) + if result["present_count"] == 0: + return (report.STATUS_FAIL, "found no gfx code objects at all -- the audit " + "method is broken, not necessarily the build (see binfmt.BUNDLE_ENTRY_RE)", + result) + + problems = [] + if result["missing"]: + problems.append(f"{HIP_CODE[os_name]} lacks {', '.join(result['missing'])}") + others = {} + for name in OTHER_HIP_CODE[os_name]: + other = os.path.join(root, name) + if not os.path.exists(other): + continue + audit = binfmt.audit_gfx_targets(other, expected) + others[name] = {k: audit[k] for k in ("present_count", "missing", "extra", + "entry_count_uniform", "bundle_magic_count")} + if audit["present_count"] and audit["missing"]: + problems.append(f"{name} lacks {', '.join(audit['missing'])}") + result["other_binaries"] = others + + if problems: + return (report.STATUS_FAIL, "requested gfx target(s) missing from the fat binary: " + f"{'; '.join(problems)}. Users with those GPUs fall back to the CPU " + "with no error.", result) + uneven = [n for n, a in others.items() if not a["entry_count_uniform"]] + if not result["entry_count_uniform"] or uneven: + return (report.STATUS_WARN, "all targets present but entry counts differ -- a " + "target may be compiled into only some translation units", result) + return (report.STATUS_PASS, None, result) + + +def check_cpu_variants(root, os_name): + """T0.4: the CPU backend variants are present (Linux). + + The Linux build uses GGML_CPU_ALL_VARIANTS, which yields one library per CPU + generation; a single one means the variant build collapsed. The Windows ROCm + build links its CPU backend into stable-diffusion.dll, so there is nothing to + count there. + """ + if os_name != "ubuntu": + return (report.STATUS_SKIP, "the Windows ROCm build links the CPU backend into " + "stable-diffusion.dll", {}) + variants = sorted(fnmatch.filter(listing(root), CPU_VARIANT_GLOB)) + details = {"count": len(variants), "variants": variants} + if not variants: + return (report.STATUS_FAIL, f"no CPU backend matching {CPU_VARIANT_GLOB}", details) + if len(variants) < 5: + return (report.STATUS_WARN, f"only {len(variants)} CPU backend variant(s); " + "GGML_CPU_ALL_VARIANTS=ON normally yields 14+", details) + return (report.STATUS_PASS, None, details) + + +def _deps(path, os_name): + """The libraries a binary imports, or None when the file is not a binary. + """ + if os_name == "ubuntu": + return binfmt.elf_dynamic(path)[0] if binfmt.is_elf(path) else None + return binfmt.pe_imports(path) if binfmt.is_pe(path) else None + + +def _is_rocm(name, os_name): + """Whether a library name belongs to ROCm. + """ + prefixes = ROCM_LIB_PREFIXES if os_name == "ubuntu" else ROCM_DLL_PREFIXES + return name.lower().startswith(prefixes) + + +def check_dependencies(root, os_name): + """T0.5: survey every binary's dynamic dependencies. + + ROCm libraries are recorded as expected-external: the archive needs a user + installed ROCm for hipBLAS, hipBLASLt and rocBLAS, and the set a consumer must + provide is written down per release. Anything else that is neither in the + archive nor part of the OS is a packaging defect and fails -- the binary would + not start on a user's machine. + """ + present = set(listing(root)) + present_lower = {f.lower() for f in present} + rocm_needed, unresolved, scanned = set(), {}, 0 + for name, path in binaries(root): + try: + deps = _deps(path, os_name) + except (ValueError, OSError, struct.error) as exc: + unresolved[name] = [f""] + continue + if not deps: + continue + scanned += 1 + missing = [] + for dep in deps: + if _is_rocm(dep, os_name): + rocm_needed.add(dep) + elif os_name == "ubuntu" and (dep in present or dep in BASE_LIBS_LINUX): + continue + elif os_name == "win" and (dep.lower() in present_lower + or dep.lower().startswith(BASE_DLLS_WIN)): + continue + else: + missing.append(dep) + if missing: + unresolved[name] = sorted(missing) + + details = {"binaries_scanned": scanned, "rocm_runtime_required": sorted(rocm_needed), + "unresolved": unresolved} + if unresolved: + flat = sorted({d for deps in unresolved.values() for d in deps}) + return (report.STATUS_FAIL, f"{len(unresolved)} binary/binaries need libraries " + f"that are neither in the archive nor part of the OS: {', '.join(flat[:6])}", + details) + if not rocm_needed: + return (report.STATUS_WARN, "no ROCm runtime dependency found at all", details) + return (report.STATUS_PASS, None, details) + + +def check_linux_version_support(root, os_name): + """T0.6: the archive still runs on the oldest Linux we support. + + Each binary records the newest version of the system C library it needs. + Whichever binary needs the newest one decides the oldest Linux release the + whole archive can run on. If that goes past what SUPPORTED_GLIBC allows, + users on a supported distribution get a startup error instead of a program. + + This normally only changes when the build job's runner image changes, which + is exactly the moment it should be noticed. + """ + if os_name != "ubuntu": + return (report.STATUS_SKIP, "Linux-only check", {}) + needs, needs_file, per_file = (0, 0), None, {} + for name, path in binaries(root): + if not binfmt.is_elf(path): + continue + floor = binfmt.elf_glibc_floor(path) + if not floor: + continue + per_file[name] = ".".join(map(str, floor)) + if floor > needs: + needs, needs_file = floor, name + + details = {"glibc_required": ".".join(map(str, needs)) if needs_file else None, + "glibc_allowed": ".".join(map(str, SUPPORTED_GLIBC)), + "oldest_supported_distro": SUPPORTED_DISTRO, + "required_by": needs_file, "per_file": per_file} + if not needs_file: + return (report.STATUS_WARN, "could not determine the glibc this archive needs", details) + if needs > SUPPORTED_GLIBC: + return (report.STATUS_FAIL, f"{needs_file} needs glibc {details['glibc_required']}, " + f"newer than {SUPPORTED_DISTRO} provides ({details['glibc_allowed']}); " + "it will not start there", details) + return (report.STATUS_PASS, None, details) + + +def check_rpath(root, os_name): + """T0.7: no absolute build-machine paths in RUNPATH. + + The HIP link adds the pip-installed ROCm devel tree's lib folder + (.../_rocm_sdk_devel/lib) to RUNPATH even with CMAKE_INSTALL_RPATH='$ORIGIN', + so the Linux ROCm job resets every binary to '$ORIGIN' with patchelf before + packaging ("Normalize RPATH for portable distribution"). This catches a + build-machine path that survives it, e.g. if that step is removed or stops + reaching a file. Every published Linux ROCm zip before that step carried one. + """ + if os_name != "ubuntu": + return (report.STATUS_SKIP, "Linux-only check", {}) + leaks = {} + for name, path in binaries(root): + if not binfmt.is_elf(path): + continue + bad = [part for entry in binfmt.elf_dynamic(path)[1] for part in entry.split(":") + if part and not part.startswith("$ORIGIN")] + if bad: + leaks[name] = bad + details = {"leaked": leaks} + if leaks: + flat = sorted({p for parts in leaks.values() for p in parts}) + return (report.STATUS_FAIL, f"{len(leaks)} binary/binaries carry a build-machine " + f"path in RUNPATH: {flat[0]}", details) + return (report.STATUS_PASS, None, details) + + +class ServerHelp: + """Runs `sd-server --help` once and shares the result between T0.8 and T0.9. + + Needs --run-binaries (the runner's OS matches the archive) and a user-style + ROCm, without which sd-server cannot load at all. Without either, both + checks are skipped rather than failed. + """ + + def __init__(self, root, os_name, run_binaries, rocm_dirs): + self.root, self.os_name = root, os_name + self.run_binaries, self.rocm_dirs = run_binaries, rocm_dirs + self._result = None + + def get(self): + if self._result is None: + self._result = self._run() + return self._result + + def _run(self): + if not self.run_binaries: + return None, "not running binaries on this runner" + if not self.rocm_dirs: + return None, "no ROCm runtime supplied; sd-server cannot load without one" + server = os.path.join(self.root, exe("sd-server", self.os_name)) + if not os.path.exists(server): + return None, "sd-server missing (see T0.1)" + proc = subprocess.run([server, "--help"], capture_output=True, text=True, + errors="replace", check=False, timeout=180, cwd=self.root, + env=rocm_env(self.rocm_dirs, self.root, self.os_name)) + return proc, None + + +def check_server_flags(help_run): + """T0.8: the sd-server flags Lemonade launches with are all still accepted. + + Checks `sd-server --help`. Windows needs the user-style ROCm on PATH even for + this, because stable-diffusion.dll imports hipBLAS at load time. + """ + proc, why = help_run.get() + if proc is None: + status = report.STATUS_FAIL if "missing" in why else report.STATUS_SKIP + return (status, why, {}) + text = (proc.stdout or "") + (proc.stderr or "") + details = {"returncode": proc.returncode, "help_bytes": len(text)} + if proc.returncode != 0 or not text.strip(): + details["output_tail"] = text[-600:] + return (report.STATUS_FAIL, f"sd-server --help exited {proc.returncode} " + f"(0x{proc.returncode & 0xFFFFFFFF:08X}) with {len(text)} bytes of output", + details) + missing = [f for f in LEMONADE_SERVER_FLAGS + if not re.search(rf"(? {root} ({len(listing(root))} entries)") + help_run = ServerHelp(root, args.os_name, args.run_binaries, rocm_dirs) + checks = { + "T0.1": lambda: check_contents(root, args.os_name), + "T0.2": lambda: check_hip_code(root, args.os_name), + "T0.3": lambda: check_gfx_targets(root, args.os_name, args.gpu_targets), + "T0.4": lambda: check_cpu_variants(root, args.os_name), + "T0.5": lambda: check_dependencies(root, args.os_name), + "T0.6": lambda: check_linux_version_support(root, args.os_name), + "T0.7": lambda: check_rpath(root, args.os_name), + "T0.8": lambda: check_server_flags(help_run), + "T0.9": lambda: check_provenance(help_run, args.upstream_sha), + "T0.10": lambda: check_rocm_dependencies(root, args.os_name, rocm_dirs), + "T0.11": lambda: check_bundled_runtime(root, args.os_name, rocm_dirs), + } + for test_id, name in TIER0_CHECKS: + tier.run(test_id, name, checks[test_id]) + finally: + shutil.rmtree(workdir, ignore_errors=True) + + tier.write(args.output) + tier.print_summary() + print(f"\nWrote {args.output}") + if args.fail_on_error and tier.rollup_status() == report.STATUS_FAIL: + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/.github/qualify-rocm/tier1_gpu.py b/.github/qualify-rocm/tier1_gpu.py new file mode 100644 index 0000000000..1ce83cfd6f --- /dev/null +++ b/.github/qualify-rocm/tier1_gpu.py @@ -0,0 +1,921 @@ +#!/usr/bin/env python3 +""" +Tier 1 -- GPU functional inference. Requires a real AMD GPU (gfx1151 runners). + +Drives sd-server over HTTP rather than sd-cli, because sd-server is the binary +Lemonade actually launches, with the model Lemonade validates +stable-diffusion.cpp with. It is started the way Lemonade starts it (model and +port) plus `-v`, which Lemonade adds only in debug mode but T1.2 needs. + +T1.2 is the check that carries the weight here. A ROCm build that cannot use +the GPU is not treated as an error by stable-diffusion.cpp: it logs that no +ROCm device was found and carries on with the CPU. sd-server still starts, +still answers, and still returns a perfectly valid image -- it just takes ten +times longer. So a test that only asks "did we get an image?" passes happily on +a build whose GPU support is entirely broken. T1.2 confirms the GPU really did +the work. + +Checks: + T1.1 server boot -- sd-server starts and serves its web page. + T1.2 GPU really did the work -- GATING. A ROCm device was found, the + model's weights were placed in VRAM on a + ROCm device with none left on the CPU, and + compute buffers were allocated in VRAM on a + ROCm device. + T1.3 GPU target detected -- GATING. The device sd-server found is the + gfx target this runner is meant to validate. + This is what makes `hardware_validated` true. + T1.4 image well-formed -- GATING. A PNG of the requested size that + decodes and is not blank. + T1.5 deterministic output -- NON-gating. The same request again gives + identical bytes. See check_determinism(). + T1.6 ROCm loaded from the expected places -- GATING. The running server + loaded the bundled HIP runtime from the + archive and every other ROCm library from + the user's ROCm install -- nothing from a + stale display-driver copy in System32. + +Usage: + python3 tier1_gpu.py --meta qualify-meta-win-rocm-10.1.json \ + --archive-dir ./artifact --gfx-target gfx1151 --output tier1.json +""" + +import argparse +import atexit +import base64 +import hashlib +import http.client +import json +import os +import platform +import re +import shutil +import signal +import socket +import struct +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request +import zlib + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import archive # noqa: E402 +import report # noqa: E402 + +READY_TIMEOUT = 600 +REQUEST_TIMEOUT = 600 + +# --------------------------------------------------------------------------- +# What is run +# --------------------------------------------------------------------------- + +# The model Lemonade validates stable-diffusion.cpp with ("SD-Turbo-GGUF" in +# Lemonade's server_models.json): about 2 GB, one file, no licence gate. Pinned +# to one revision and checked against its SHA-256 and size, because a download +# that arrives truncated would otherwise fail T1.1 and withhold a good build. +MODEL_REPO = "Green-Sky/SD-Turbo-GGUF" +MODEL_REVISION = "19a31586d02d64a73b4419bc193b3ecfaf38e1f0" +MODEL_FILE = "sd_turbo-f16-q8_0.gguf" +MODEL_BYTES = 2023745376 +MODEL_SHA256 = "d50be7655f0a554cf8041c145d88b210bd5f3c545423119dee62ae08cae51580" +MODEL_URL = f"https://huggingface.co/{MODEL_REPO}/resolve/{MODEL_REVISION}/{MODEL_FILE}" + +# One small, quick image: SD-Turbo is made for 4 steps at 512x512 with +# classifier-free guidance off (cfg 1.0), as Lemonade runs it. +WIDTH = HEIGHT = 512 +PROMPT = "a red apple on a wooden table" +# sd-server's OpenAI route ignores top-level seed/steps; they travel inside the +# prompt as , which is also how Lemonade passes them. +GEN_ARGS = {"seed": 42, "sample_params": {"sample_steps": 4, "guidance": {"txt_cfg": 1.0}}} + +# Added to the model and port Lemonade launches sd-server with. Lemonade passes +# `-v` only in debug mode (as its CI runs), but here it is not optional: the +# weight-buffer and compute-buffer lines T1.2 requires are verbose-only, so +# without it T1.2 would find no evidence and fail a good build. +SERVER_ARGS = ["-v"] + +# --------------------------------------------------------------------------- +# Evidence that the GPU genuinely did the work +# +# All three are required, and each names a ROCm device or VRAM, so none can +# appear unless a ROCm device was found and used: +# " Device 0: AMD Radeon(TM) 8060S Graphics, gfx1151 (0x1151), VMM: no, ..." +# printed by ggml when it finds ROCm devices (any log level); +# "model manager prepared params backend buffers (1411.07 MB, 686 tensors, +# 2 blocks, VRAM) on ROCm0" +# one per model component as its weights are loaded (verbose only). On a +# CPU fallback it reads "(..., RAM) on CPU" instead, which fails the check; +# "unet compute buffer size: 87.86 MB(VRAM) on ROCm0 (peak across 1 segment)" +# printed when a graph is about to run (verbose only). +# +# These three were chosen because upstream kept them as it changed its other +# logging. Two placement summaries are version-specific and have already been +# renamed once, so they are optional: recorded when present, and a failure only +# if they show a component on the CPU, never required: +# "total params memory size = 1929.50MB (VRAM 1929.50MB, RAM 0.00MB): ..." +# (upstream master-1106 and earlier) +# "load_unet: 1411.02 MiB params -> ROCm0" +# (master-1117 and later) +# +# Deliberately NOT accepted as evidence, despite how it reads: +# "Initializing backend: ROCm0" +# stable-diffusion.cpp prints it BEFORE trying to start the device, so it also appears +# when the device then fails to initialise and everything falls back to the CPU. +# --------------------------------------------------------------------------- +DEVICE_RE = re.compile(r"Device (\d+): (.+?), (gfx[0-9a-fA-F]+) \(0x[0-9a-fA-F]+\)") +PARAMS_BUFFER_RE = re.compile(r"prepared params backend buffers \(\s*([0-9.]+) MB, [^)]*?" + r"(VRAM|RAM)\) on (\S+)") +COMPUTE_RE = re.compile(r"(\w+) compute buffer size: ([0-9.]+) MB\(VRAM\) on (ROCm\d+)") +TOTAL_PARAMS_RE = re.compile(r"total params memory size = ([0-9.]+)MB \(VRAM ([0-9.]+)MB, " + r"RAM ([0-9.]+)MB\):([^\n]*)") +COMPONENT_RE = re.compile(r"(\w+) ([0-9.]+)MB\((VRAM|RAM|N/A)\)") +LOAD_PARAMS_RE = re.compile(r"load_(\w+): ([0-9.]+) MiB params -> (\S+)") +ROCM_DEVICE_RE = re.compile(r"^ROCm\d+$") + +# Lines that explain WHY the GPU went unused, so the failure message can say +# something more useful than "no evidence found". Each was seen in a real CPU +# fallback of sd-server with the GPU hidden. +CPU_FALLBACK_HINTS = [ + re.compile(r"failed to initialize ROCm", re.I), + re.compile(r"no ROCm-capable device", re.I), + re.compile(r"auto-fit: no GPU devices"), + re.compile(r"device \S+ failed to init"), + re.compile(r"loading CPU backend"), + re.compile(r"Using CPU backend"), +] + +# Settings a self-hosted runner may carry that would change which ROCm runtime +# or which device gets used. Removed before launching, and recorded in the +# report's runner_env if they were set. +FOREIGN_ROCM_ENV = ("ROCM_PATH", "HIP_PATH", "HIP_DEVICE_LIB_PATH", "HSA_OVERRIDE_GFX_VERSION", + "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES", + "ROCBLAS_TENSILE_LIBPATH", "HIPBLASLT_TENSILE_LIBPATH") + +# Library names that belong to ROCm, for T1.6. Same lists as +# lemonade-sdk/llamacpp-rocm, minus ggml-hip, which is this archive's own code. +ROCM_LIB_PREFIXES = ( + "libamdhip64", "libhsa-runtime64", "libamd_comgr", "librocblas", "libhipblas", + "librocsolver", "librocm", "libroctx", "librocprofiler", "libtensilelite", + "liborigami", "librocroller", "libhiprtc", +) +ROCM_DLL_PREFIXES = ( + "amdhip64", "amd_comgr", "rocblas", "hipblas", "libhipblas", "rocsolver", + "rocm_", "origami", "libtensilelite", "hiprtc", +) +HIP_RUNTIME_PREFIX = ("libamdhip64", "amdhip64") + + +# --------------------------------------------------------------------------- +# Inputs this script fetches for itself +# +# Extraction and downloading live here so the job works on any runner regardless +# of which shell it has. A self-hosted machine is not guaranteed to provide the +# same tools a hosted one does. +# --------------------------------------------------------------------------- + +def file_sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def ensure_model(cache_dir): + """Return a verified copy of the test model, downloading it at most once per machine. + + The cache lives under the runner's tool cache, which survives between jobs + on a self-hosted machine, so each machine downloads the 2 GB once. A cached + copy is re-hashed every time and replaced if it does not match. A download + goes to a per-process temporary name and is only moved into place once its + size and SHA-256 are right, so two jobs on one machine cannot see each + other's half-written file. + """ + folder = os.path.join(cache_dir, "sdcpp-qualify", MODEL_REVISION[:12]) + path = os.path.join(folder, MODEL_FILE) + os.makedirs(folder, exist_ok=True) + if os.path.exists(path): + if os.path.getsize(path) == MODEL_BYTES and file_sha256(path) == MODEL_SHA256: + print(f"Using cached model {path}") + return path + print(f"::warning::cached model {path} is corrupt; downloading it again") + os.remove(path) + + last = None + for attempt in range(1, 4): + part = f"{path}.{os.getpid()}.part" + try: + print(f"Downloading model (attempt {attempt}/3): {MODEL_URL}") + digest = hashlib.sha256() + with urllib.request.urlopen(MODEL_URL, timeout=600) as resp, open(part, "wb") as out: + for chunk in iter(lambda: resp.read(1 << 20), b""): + digest.update(chunk) + out.write(chunk) + size = os.path.getsize(part) + if size != MODEL_BYTES or digest.hexdigest() != MODEL_SHA256: + raise OSError(f"downloaded {size} bytes with sha256 {digest.hexdigest()}, " + f"expected {MODEL_BYTES} bytes with sha256 {MODEL_SHA256}") + os.replace(part, path) + return path + except Exception as exc: # noqa: BLE001 - any failure is retried + last = exc + if os.path.exists(part): + os.remove(part) + time.sleep(10 * attempt) + raise SystemExit(f"::error::could not download the test model: {last}") + + +# --------------------------------------------------------------------------- +# The machine this ran on +# --------------------------------------------------------------------------- + +def _read(path): + try: + with open(path, encoding="utf-8", errors="replace") as handle: + return handle.read().strip() or None + except OSError: + return None + + +def _windows_gpu_drivers(): + """AMD display adapters and their driver versions, from the registry.""" + import winreg # pylint: disable=import-outside-toplevel + + found = [] + base = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}" + try: + root = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, base) + except OSError: + return found + with root: + index = 0 + while True: + try: + sub = winreg.EnumKey(root, index) + except OSError: + break + index += 1 + if not sub.isdigit(): + continue + entry = {} + try: + with winreg.OpenKey(root, sub) as key: + for value in ("DriverDesc", "ProviderName", "DriverVersion", + "DriverDate", "RadeonSoftwareVersion"): + try: + entry[value] = str(winreg.QueryValueEx(key, value)[0]) + except OSError: + pass + except OSError: + continue + text = " ".join(entry.values()) + if "Advanced Micro Devices" in text or "AMD" in text or "Radeon" in text: + found.append(entry) + return found + + +def runner_environment(): + """What a GPU result depends on besides the archive: driver, kernel, stray ROCm. + + Recorded in every report so a failure that only happens on one machine, or + after a driver update, can be traced without access to that machine. + """ + env = { + "platform": platform.platform(), + "machine_name": platform.node(), + "python": platform.python_version(), + "foreign_rocm_env_removed": {k: os.environ[k] for k in FOREIGN_ROCM_ENV + if k in os.environ}, + } + if os.name == "nt": + env["gpu_drivers"] = _windows_gpu_drivers() + system32 = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32") + env["driver_hip_runtime_in_system32"] = sorted( + f for f in os.listdir(system32) if f.lower().startswith("amdhip64")) + else: + env["kernel"] = platform.release() + env["amdgpu_module_version"] = _read("/sys/module/amdgpu/version") + env["kfd_present"] = os.path.exists("/dev/kfd") + env["system_rocm"] = { + "opt_rocm_present": os.path.isdir("/opt/rocm"), + "opt_rocm_version": _read("/opt/rocm/.info/version"), + } + return env + + +# --------------------------------------------------------------------------- +# HTTP +# --------------------------------------------------------------------------- + +def http_get(url, timeout=10): + """(status, body) for an HTTP answer, or (None, b"") when there was none. + + An HTTP error status is returned rather than swallowed, and a reply that is + not HTTP at all returns status 0. A timeout or a reset connection returns + None, so use port_in_use() to ask whether anything is listening. + """ + try: + with urllib.request.urlopen(url, timeout=timeout) as resp: + return resp.status, resp.read() + except urllib.error.HTTPError as exc: + return exc.code, b"" + except http.client.HTTPException: + return 0, b"" + except (urllib.error.URLError, OSError): + return None, b"" + + +def port_in_use(port): + """Whether anything at all accepts connections on 127.0.0.1:port.""" + try: + with socket.create_connection(("127.0.0.1", port), timeout=3): + return True + except OSError: + return False + + +def generate(base): + """Ask sd-server for one image the way Lemonade does; return (PNG bytes, seconds).""" + prompt = f"{PROMPT}{json.dumps(GEN_ARGS)}" + payload = {"prompt": prompt, "n": 1, "size": f"{WIDTH}x{HEIGHT}", + "response_format": "b64_json"} + req = urllib.request.Request(f"{base}/v1/images/generations", + data=json.dumps(payload).encode("utf-8"), + headers={"Content-Type": "application/json"}) + start = time.monotonic() + with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: + body = json.loads(resp.read().decode("utf-8")) + elapsed = time.monotonic() - start + return base64.b64decode(body["data"][0]["b64_json"]), elapsed + + +def decode_png(data): + """Return (width, height, channels, raw pixel bytes) for an 8-bit RGB/RGBA/gray PNG. + + A small decoder rather than an image library, because the self-hosted + runners have nothing installed beyond Python itself. sd-server writes plain + 8-bit, non-interlaced PNGs; anything else is reported as unsupported. + """ + if data[:8] != b"\x89PNG\r\n\x1a\n": + raise ValueError("not a PNG") + pos, idat, header = 8, [], None + while pos < len(data): + length, kind = struct.unpack(">I4s", data[pos:pos + 8]) + chunk = data[pos + 8:pos + 8 + length] + if kind == b"IHDR": + header = struct.unpack(">IIBBBBB", chunk) + elif kind == b"IDAT": + idat.append(chunk) + elif kind == b"IEND": + break + pos += 12 + length + if header is None: + raise ValueError("PNG has no IHDR") + width, height, depth, color, _compression, _filter_method, interlace = header + channels = {0: 1, 2: 3, 4: 2, 6: 4}.get(color) + if depth != 8 or channels is None or interlace: + raise ValueError(f"unsupported PNG: depth {depth}, color type {color}, interlace {interlace}") + raw = zlib.decompress(b"".join(idat)) + stride = width * channels + out = bytearray(height * stride) + prev = bytearray(stride) + for y in range(height): + kind = raw[y * (stride + 1)] + line = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)]) + for x in range(stride): + a = line[x - channels] if x >= channels else 0 + b = prev[x] + c = prev[x - channels] if x >= channels else 0 + if kind == 1: + line[x] = (line[x] + a) & 0xFF + elif kind == 2: + line[x] = (line[x] + b) & 0xFF + elif kind == 3: + line[x] = (line[x] + ((a + b) >> 1)) & 0xFF + elif kind == 4: + p = a + b - c + pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) + line[x] = (line[x] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 0xFF + elif kind != 0: + raise ValueError(f"bad PNG filter type {kind}") + out[y * stride:(y + 1) * stride] = line + prev = line + return width, height, channels, bytes(out) + + +# --------------------------------------------------------------------------- +# Server lifecycle +# --------------------------------------------------------------------------- + +def build_env(rocm_dirs, root): + """The environment Lemonade starts sd-server with, minus any foreign ROCm. + + The user-style ROCm goes first on the library search path, then the archive + folder. On Windows the program's own folder is searched before PATH anyway, + so the bundled HIP runtime wins over both PATH and System32 -- which is why + it is bundled -- and hipBLAS/rocBLAS come from the ROCm install. + """ + env = {k: v for k, v in os.environ.items() if k not in FOREIGN_ROCM_ENV} + key = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH" + env[key] = os.pathsep.join(rocm_dirs + [root, env.get(key, "")]) + return env + + +class Server: + def __init__(self, exe, model, port, log_path, env, cwd): + self.exe = exe + self.model = model + self.port = port + self.log_path = log_path + self.env = env + self.cwd = cwd + self.proc = None + self._log = None + + def start(self): + cmd = [self.exe, "-m", self.model, "--listen-port", str(self.port), *SERVER_ARGS] + print("+ " + " ".join(cmd), flush=True) + self._log = open(self.log_path, "w", encoding="utf-8", errors="replace") + kwargs = {} + if os.name != "nt": + kwargs["start_new_session"] = True + self.proc = subprocess.Popen(cmd, stdout=self._log, stderr=subprocess.STDOUT, + env=self.env, cwd=self.cwd, **kwargs) + + def running(self): + return self.proc is not None and self.proc.poll() is None + + def exit_text(self): + if self.proc is None or self.proc.returncode is None: + return "sd-server is not running" + code = self.proc.returncode + return f"sd-server exited (rc={code}, 0x{code & 0xFFFFFFFF:08X})" + + def wait_ready(self, timeout): + """Poll sd-server's web page until it answers -- and only from our own process. + + A 200 only counts while the process this script started is still alive, + so another server on the same port can never stand in for it. + """ + if self.proc is None: + return False, "sd-server was never started" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if not self.running(): + return False, f"{self.exit_text()} before it was ready" + status, _ = http_get(f"http://127.0.0.1:{self.port}/") + if status == 200 and self.running(): + return True, None + time.sleep(2) + return False, f"sd-server not ready within {timeout}s" + + def stop(self): + proc = self.proc + if proc is not None and proc.poll() is None: + try: + if os.name == "nt": + proc.terminate() + else: + os.killpg(os.getpgid(proc.pid), signal.SIGTERM) + proc.wait(timeout=30) + except (ProcessLookupError, OSError, subprocess.TimeoutExpired): + try: + proc.kill() + except OSError: + pass + if self._log: + self._log.close() + + def log_text(self): + try: + with open(self.log_path, encoding="utf-8", errors="replace") as handle: + return handle.read() + except OSError: + return "" + + +# --------------------------------------------------------------------------- +# Which libraries the running server actually loaded +# --------------------------------------------------------------------------- + +def _linux_loaded_files(pid): + paths = [] + with open(f"/proc/{pid}/maps", encoding="utf-8", errors="replace") as handle: + for line in handle: + parts = line.split(None, 5) + if len(parts) == 6 and parts[5].startswith("/"): + path = parts[5].strip() + if path.endswith(" (deleted)"): + path = path[: -len(" (deleted)")] + if path not in paths: + paths.append(path) + return paths + + +def _windows_loaded_files(pid): + import ctypes # pylint: disable=import-outside-toplevel + from ctypes import wintypes # pylint: disable=import-outside-toplevel + + process_query_information, process_vm_read, list_modules_all = 0x0400, 0x0010, 0x03 + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + psapi = ctypes.WinDLL("psapi", use_last_error=True) + kernel32.OpenProcess.restype = wintypes.HANDLE + kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + psapi.EnumProcessModulesEx.argtypes = [ + wintypes.HANDLE, ctypes.POINTER(wintypes.HMODULE), wintypes.DWORD, + ctypes.POINTER(wintypes.DWORD), wintypes.DWORD] + psapi.GetModuleFileNameExW.argtypes = [ + wintypes.HANDLE, wintypes.HMODULE, wintypes.LPWSTR, wintypes.DWORD] + + handle = kernel32.OpenProcess(process_query_information | process_vm_read, False, pid) + if not handle: + raise OSError(ctypes.get_last_error(), "OpenProcess failed") + try: + count = 1024 + needed = wintypes.DWORD() + while True: + modules = (wintypes.HMODULE * count)() + if not psapi.EnumProcessModulesEx(handle, modules, ctypes.sizeof(modules), + ctypes.byref(needed), list_modules_all): + raise OSError(ctypes.get_last_error(), "EnumProcessModulesEx failed") + if needed.value <= ctypes.sizeof(modules): + break + count = needed.value // ctypes.sizeof(wintypes.HMODULE) + 16 + buffer = ctypes.create_unicode_buffer(32768) + paths = [] + for i in range(needed.value // ctypes.sizeof(wintypes.HMODULE)): + if psapi.GetModuleFileNameExW(handle, modules[i], buffer, len(buffer)): + paths.append(buffer.value) + return paths + finally: + kernel32.CloseHandle(handle) + + +def _is_rocm(name): + low = name.lower() + if os.name == "nt": + return low.startswith(ROCM_DLL_PREFIXES) and low.endswith(".dll") + return name.startswith(ROCM_LIB_PREFIXES) and ".so" in name + + +def _same_dir(a, b): + return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b)) + + +# --------------------------------------------------------------------------- +# Checks +# --------------------------------------------------------------------------- + +def gpu_evidence(log): + """Pull the device, weight-placement and compute-buffer lines out of the log.""" + devices = [{"index": int(m.group(1)), "name": m.group(2), "gfx": m.group(3)} + for m in DEVICE_RE.finditer(log)] + params = [{"mb": float(mb), "memory": memory, "device": device} + for mb, memory, device in PARAMS_BUFFER_RE.findall(log)] + compute = [{"graph": g, "mb": float(mb), "device": dev} for g, mb, dev in COMPUTE_RE.findall(log)] + + # Version-specific placement summaries, if this upstream prints either. + placement = {} + total = TOTAL_PARAMS_RE.search(log) + if total: + for name, size, where in COMPONENT_RE.findall(total.group(4)): + if float(size) > 0: + placement[name] = "GPU" if where == "VRAM" else where + for name, size, device in LOAD_PARAMS_RE.findall(log): + if float(size) > 0: + placement[name] = "GPU" if ROCM_DEVICE_RE.match(device) else device + return { + "devices": devices, + "params_buffers": params, + "compute_buffers": compute, + "placement": placement, + } + + +def check_gpu_did_work(server): + """T1.2: confirm the GPU actually did the work, not merely that it was found. + + This is the check the tier exists for. Every other check here passes + happily when stable-diffusion.cpp has fallen back to the CPU. + + All of these must hold: a ROCm device was found; the model's weights were + placed in VRAM on a ROCm device, and none of them on the CPU; and at least + one compute buffer was allocated in VRAM on a ROCm device, which only + happens once a graph really runs there. If this upstream also prints a + per-component placement summary, every component in it must be on a GPU. + The device patterns match any device index (ROCm0, ROCm1, ...), so a runner + with two GPUs passes as long as all the work landed on GPUs. + """ + log = server.log_text() + evidence = gpu_evidence(log) + on_gpu = [b for b in evidence["params_buffers"] + if b["memory"] == "VRAM" and ROCM_DEVICE_RE.match(b["device"]) and b["mb"] > 0] + off_gpu = [b for b in evidence["params_buffers"] + if not (b["memory"] == "VRAM" and ROCM_DEVICE_RE.match(b["device"]))] + not_on_gpu = sorted(n for n, where in evidence["placement"].items() if where != "GPU") + # The verdict uses every line; the report keeps the first few of each. + details = {**evidence, + "params_buffers": evidence["params_buffers"][:10], + "params_buffer_count": len(evidence["params_buffers"]), + "compute_buffers": evidence["compute_buffers"][:10], + "compute_buffer_count": len(evidence["compute_buffers"])} + + problems = [] + if not details["devices"]: + problems.append("no ROCm device was detected") + if not on_gpu: + problems.append("no model weights were placed in VRAM on a ROCm device") + if off_gpu: + problems.append(f"{len(off_gpu)} weight buffer(s) were placed in RAM on the CPU") + if not_on_gpu: + problems.append(f"{', '.join(not_on_gpu)} weights were not placed on the GPU") + if not any(c["mb"] > 0 for c in evidence["compute_buffers"]): + problems.append("no compute buffer was allocated in VRAM on a ROCm device") + if not problems: + print("GPU confirmed by:") + for device in details["devices"]: + print(f" Device {device['index']}: {device['name']}, {device['gfx']}") + for buffer in on_gpu[:3]: + print(f" weights: {buffer['mb']} MB in VRAM on {buffer['device']}") + for buffer in details["compute_buffers"][:3]: + print(f" {buffer['graph']} compute buffer: {buffer['mb']} MB in VRAM on {buffer['device']}") + return (report.STATUS_PASS, None, details) + + details["cpu_fallback_hints"] = [p.pattern for p in CPU_FALLBACK_HINTS if p.search(log)] + details["log_tail"] = log[-3000:] + # The weight and compute-buffer lines are verbose-only: when a GPU was found + # but the log has no verbose lines at all, the likelier cause is the log level. + if details["devices"] and "[V]" not in log: + return (report.STATUS_FAIL, "a ROCm device was found but the log has no verbose ([V]) " + f"lines at all: sd-server was not started with {SERVER_ARGS}, so the " + "evidence was never printed", details) + return (report.STATUS_FAIL, f"GPU was NOT used -- {'; '.join(problems)}. This is silent " + "at run time: sd-server still returns an image, just from the CPU.", details) + + +def check_gpu_target(server, gfx_target): + """T1.3: the device sd-server found is the gfx target this runner validates. + + `gfx_target` comes from the workflow's Tier 1 leg, so adding a runner with + another GPU is one more matrix leg, not a change here. Only when this passes + is the archive recorded as hardware-validated on that target. + """ + devices = gpu_evidence(server.log_text())["devices"] + detected = sorted({d["gfx"].lower() for d in devices}) + details = {"expected": gfx_target, "detected": detected, + "device_names": sorted({d["name"] for d in devices})} + if not detected: + return (report.STATUS_FAIL, "sd-server reported no ROCm device", details) + if gfx_target.lower() not in detected: + return (report.STATUS_FAIL, f"expected a {gfx_target} device, sd-server found " + f"{', '.join(detected)}", details) + return (report.STATUS_PASS, None, details) + + +def check_image(state): + """T1.4: the image is a real picture of the requested size. + + A PNG of exactly WIDTHxHEIGHT that decodes completely, and is not flat: a + GPU kernel that produces NaNs typically yields an all-black or uniform image + that is still a perfectly valid PNG. Lemonade's validator only reads the PNG + header, so this also catches what it would not. + """ + if "error" in state: + return (report.STATUS_FAIL, state["error"], {}) + data = state["png"] + width, height, channels, pixels = decode_png(data) + sample = pixels[::7] + mean = sum(sample) / len(sample) + stddev = (sum((v - mean) ** 2 for v in sample) / len(sample)) ** 0.5 + details = {"bytes": len(data), "width": width, "height": height, "channels": channels, + "pixel_mean": round(mean, 2), "pixel_stddev": round(stddev, 2), + "distinct_values": len(set(sample)), "request_seconds": round(state["seconds"], 2), + "sha256": hashlib.sha256(data).hexdigest()} + if (width, height) != (WIDTH, HEIGHT): + return (report.STATUS_FAIL, f"image is {width}x{height}, requested {WIDTH}x{HEIGHT}", details) + if stddev < 5 or details["distinct_values"] < 16: + return (report.STATUS_FAIL, "image is blank or flat -- the GPU produced no real " + "picture (often NaNs)", details) + return (report.STATUS_PASS, None, details) + + +def check_determinism(base, state): + """T1.5: the same request with the same seed gives identical bytes. + + Non-gating, and worth being honest about why. On a GPU thousands of threads + add numbers in whatever order they happen to finish, so results can differ + in the last decimal place between runs, which can flip a pixel. On the + gfx1151 runners sd-server is in fact bit-exact from run to run, so a + difference here is a hint worth a look, not proof of a defect. It is not + compared across ROCm versions, whose images legitimately differ. + """ + if "png" not in state: + return (report.STATUS_SKIP, "the first image was not generated", {}) + second, seconds = generate(base) + first_hash = hashlib.sha256(state["png"]).hexdigest() + second_hash = hashlib.sha256(second).hexdigest() + details = {"first_sha256": first_hash, "second_sha256": second_hash, + "second_request_seconds": round(seconds, 2)} + if first_hash != second_hash: + return (report.STATUS_WARN, "the same request with the same seed produced a " + "different image", details) + return (report.STATUS_PASS, None, details) + + +def check_loaded_from_expected(server, root, rocm_dirs): + """T1.6: every ROCm library inside the running server came from where it should. + + The HIP runtime the archive bundles (amdhip64_7.dll, amd_comgr.dll, + rocm_kpack.dll on Windows) must come from the archive folder, and every + other ROCm library (hipBLAS, hipBLASLt, rocBLAS, ...) from the user's ROCm + install. Anything else -- a display driver's amdhip64_7.dll in System32, a + system ROCm under /opt/rocm -- means the binary is running against a ROCm + it was not built for. That is the mix behind Lemonade #3718, where + hipGetDeviceCount() returned 0 and every request ran on the CPU. + + Taken after the requests have run, so libraries that are only loaded on + first use -- the code-object compiler, the maths libraries -- are included. + """ + proc = server.proc + if proc is None or proc.poll() is not None: + return (report.STATUS_FAIL, "sd-server is not running, so its loaded " + "libraries cannot be inspected", {}) + paths = _windows_loaded_files(proc.pid) if os.name == "nt" else _linux_loaded_files(proc.pid) + + bundled = {f.lower() for f in os.listdir(root) if _is_rocm(f)} + rocm = [p for p in paths if _is_rocm(os.path.basename(p))] + misplaced = [] + for path in rocm: + name, folder = os.path.basename(path).lower(), os.path.dirname(path) + expected = [root] if name in bundled else rocm_dirs + if not any(_same_dir(folder, place) for place in expected): + misplaced.append(path) + hip_runtime = [p for p in rocm if os.path.basename(p).lower().startswith(HIP_RUNTIME_PREFIX)] + details = { + "archive_dir": root, + "bundled_in_archive": sorted(bundled), + "modules_loaded": len(paths), + "rocm_libraries_loaded": sorted(rocm), + "loaded_from_unexpected_place": misplaced, + } + if not hip_runtime: + return (report.STATUS_FAIL, "the HIP runtime is not loaded in the server at all, so " + "it cannot be using the GPU", details) + if misplaced: + return (report.STATUS_FAIL, f"{len(misplaced)} ROCm library/libraries were loaded " + f"from neither the archive nor the user's ROCm install, e.g. {misplaced[0]}", + details) + return (report.STATUS_PASS, None, details) + + +CHECKS_AFTER_BOOT = [ + ("T1.2", "GPU really did the work", True), + ("T1.3", "GPU target detected", True), + ("T1.4", "image well-formed", True), + ("T1.5", "deterministic output", False), + ("T1.6", "ROCm loaded from the expected places", True), +] + + +def main(): + parser = argparse.ArgumentParser(description="Tier 1 GPU functional inference") + parser.add_argument("--meta", default=None, + help="qualify-meta-*.json written by the build job. Supplies " + "--rocm-version/--tag and names the archive to find " + "under --archive-dir, so the command line needs no " + "other arguments in CI.") + parser.add_argument("--archive-dir", default=".", + help="where to look for the archive named by --meta") + parser.add_argument("--archive", default=None, + help="published archive to test; extracted automatically") + parser.add_argument("--archive-root", default=None, + help="an already-extracted archive, instead of --archive") + parser.add_argument("--model", default=None, + help="path to an already-verified model file; downloaded if absent") + parser.add_argument("--model-cache", + default=os.environ.get("RUNNER_TOOL_CACHE") or tempfile.gettempdir(), + help="persistent folder the model is cached in") + parser.add_argument("--rocm-version", default=None) + parser.add_argument("--gfx-target", default="gfx1151") + parser.add_argument("--artifact", default=None, help="release asset filename") + parser.add_argument("--tag", default=None) + parser.add_argument("--upstream-sha", default=None) + parser.add_argument("--rocm-dirs", default=os.environ.get("ROCM_RUNTIME_DIRS", ""), + help="os.pathsep-separated ROCm runtime directories") + parser.add_argument("--port", type=int, default=8233) + parser.add_argument("--logs-dir", default=".") + parser.add_argument("--ready-timeout", type=int, default=READY_TIMEOUT) + parser.add_argument("--run-id", default=os.environ.get("GITHUB_RUN_ID")) + parser.add_argument("--run-attempt", default=os.environ.get("GITHUB_RUN_ATTEMPT")) + parser.add_argument("--output", default="tier1-report.json") + parser.add_argument("--fail-on-error", action="store_true") + args = parser.parse_args() + + if args.meta: + with open(args.meta, encoding="utf-8-sig") as handle: + info = json.load(handle) + args.rocm_version = args.rocm_version or info.get("rocm_version") + args.tag = args.tag or info.get("tag") + args.upstream_sha = args.upstream_sha or info.get("upstream_sha") + args.artifact = args.artifact or info.get("artifact") + if not args.archive and not args.archive_root: + args.archive = os.path.join(args.archive_dir, info["artifact"]) + if not args.rocm_version: + parser.error("--rocm-version is required when --meta is not given") + + # Absolute, because sd-server runs from the archive folder, not from here. + rocm_dirs = [os.path.abspath(d) for d in args.rocm_dirs.split(os.pathsep) if d] + if not rocm_dirs: + raise SystemExit( + "::error::No ROCm runtime directories supplied. These archives do not " + "contain ROCm's math libraries, so install_rocm.py must run first -- it " + "exports ROCM_RUNTIME_DIRS, which this script reads automatically.") + + # Placed inside the runner's own temporary area, which the runner cleans and + # the teardown step searches. Removed however this run ends. + workdir = tempfile.mkdtemp(prefix="tier1-", dir=os.environ.get("RUNNER_TEMP") or None) + atexit.register(lambda: shutil.rmtree(workdir, ignore_errors=True)) + + if args.archive_root: + root = os.path.abspath(args.archive_root) + elif args.archive: + if not os.path.exists(args.archive): + raise SystemExit(f"::error::archive not found: {args.archive}") + root = archive.extract(args.archive, os.path.join(workdir, "x")) + print(f"Extracted {args.archive} -> {root}") + else: + parser.error("one of --meta, --archive or --archive-root is required") + + exe = os.path.join(root, archive.SERVER["win" if os.name == "nt" else "ubuntu"]) + if not os.path.exists(exe): + raise SystemExit(f"::error::sd-server not found at {exe}") + model = args.model or ensure_model(args.model_cache) + + meta = report.build_meta( + artifact=args.artifact or (os.path.basename(args.archive) if args.archive else None), + os_name="win" if os.name == "nt" else "ubuntu", rocm_version=args.rocm_version, + sdcpp_tag=args.tag, upstream_sha=args.upstream_sha, gfx_target=args.gfx_target, + run_id=args.run_id, run_attempt=args.run_attempt) + meta["runner_env"] = runner_environment() + tier = report.TierReport("tier1", meta) + + os.makedirs(args.logs_dir, exist_ok=True) + log_path = os.path.join(args.logs_dir, f"sd-server-{args.gfx_target}-rocm{args.rocm_version}.log") + base = f"http://127.0.0.1:{args.port}" + server = Server(exe, os.path.abspath(model), args.port, log_path, + build_env(rocm_dirs, root), root) + state = {} + + def skip_rest(reason): + for test_id, name, gating in CHECKS_AFTER_BOOT: + tier.add(test_id, name, report.STATUS_SKIP, gating=gating, error=reason) + + try: + # Another server already on this port would answer in place of the one under test. + if port_in_use(args.port): + tier.add("T1.1", "server boot", report.STATUS_FAIL, + error=f"port {args.port} is already in use by another process", + details={"port": args.port}) + skip_rest("server not started") + else: + server.start() + ready, err = server.wait_ready(args.ready_timeout) + if not ready: + tier.add("T1.1", "server boot", report.STATUS_FAIL, error=err, + details={"log_tail": server.log_text()[-3000:]}) + skip_rest("server not ready") + else: + tier.add("T1.1", "server boot", report.STATUS_PASS, + details={"port": args.port, "args": SERVER_ARGS, "model": MODEL_FILE}) + try: + state["png"], state["seconds"] = generate(base) + except Exception as exc: # noqa: BLE001 - recorded by T1.4 + state["error"] = f"image request failed: {type(exc).__name__}: {exc}" + if not server.running(): + state = {"error": f"{server.exit_text()} while generating the image"} + tier.run("T1.2", "GPU really did the work", lambda: check_gpu_did_work(server)) + tier.run("T1.3", "GPU target detected", + lambda: check_gpu_target(server, args.gfx_target)) + tier.run("T1.4", "image well-formed", lambda: check_image(state)) + tier.run("T1.5", "deterministic output", + lambda: check_determinism(base, state), gating=False) + tier.run("T1.6", "ROCm loaded from the expected places", + lambda: check_loaded_from_expected(server, root, rocm_dirs)) + finally: + server.stop() + + meta["hardware_validated"] = tier.status_of("T1.3") == report.STATUS_PASS + tier.write(args.output) + tier.print_summary() + print(f"\nWrote {args.output}") + if args.fail_on_error and tier.rollup_status() == report.STATUS_FAIL: + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fb649dd462..7951189a98 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,12 +12,16 @@ on: pull_request: # validate the release build on PRs; the release job is skipped so nothing is published paths: # The build jobs clone stable-diffusion.cpp source from upstream - # (leejet/stable-diffusion.cpp), so only changes to this workflow itself - # can affect the outcome of a PR run. Scope PR runs to it. + # (leejet/stable-diffusion.cpp), so only this workflow and the ROCm + # qualification suite can affect the outcome of a PR run. - '.github/workflows/build.yml' + - '.github/qualify-rocm/**' env: BRANCH_NAME: master + # The ROCm archives every run should produce. Keep in step with the ROCm build and qualify matrices. + ROCM_VERSIONS: "10.0,10.1,10.2" + ROCM_OPERATING_SYSTEMS: "ubuntu,win" permissions: contents: read @@ -27,7 +31,61 @@ concurrency: cancel-in-progress: true jobs: + # Pins one upstream commit for the whole run, so a push upstream mid-run cannot put two revisions under one tag. + resolve-upstream: + runs-on: ubuntu-24.04 + outputs: + sha: ${{ steps.resolve.outputs.sha }} + tag: ${{ steps.resolve.outputs.tag }} + short: ${{ steps.resolve.outputs.short }} + skip: ${{ steps.published.outputs.complete == 'true' }} + steps: + - name: Clone + uses: actions/checkout@v6 + with: + fetch-depth: 0 + repository: 'leejet/stable-diffusion.cpp' + path: upstream + + - name: Checkout qualification suite + uses: actions/checkout@v6 + with: + path: lemonade-ci + + - name: Resolve commit and tag + id: resolve + run: | + sha=$(git -C upstream rev-parse HEAD) + short=${GITHUB_SHA::7} + tag="${BRANCH_NAME}-$(git -C upstream rev-list --count HEAD)-${short}" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "short=$short" >> "$GITHUB_OUTPUT" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "Pinning this run to upstream $sha ($tag)" + + # The tag only changes when upstream or this fork changes, so a nightly on unchanged + # sources would rebuild a release that already exists. Skip it when that release + # already holds every family; rebuild to fill the gaps when it does not. + - name: Check whether this tag is already fully published + id: published + if: github.event_name == 'schedule' + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ steps.resolve.outputs.tag }} + SHORT: ${{ steps.resolve.outputs.short }} + run: | + if gh release view "$TAG" -R "${{ github.repository }}" --json assets \ + --jq '.assets[] | select(.state == "uploaded") | .name' > assets.txt; then + python3 lemonade-ci/.github/qualify-rocm/release_assets.py check-release \ + --branch "$BRANCH_NAME" --short "$SHORT" --rocm-versions "$ROCM_VERSIONS" --names-file assets.txt + else + echo "No complete release $TAG yet; building it." + echo "complete=false" >> "$GITHUB_OUTPUT" + fi + ubuntu-latest-cmake: + needs: resolve-upstream + if: needs.resolve-upstream.outputs.skip != 'true' # Pinned: Lemonade expects Ubuntu-24.04 asset names, and binaries built on # newer Ubuntu need a newer glibc than 24.04 and Debian 13 provide. runs-on: ubuntu-24.04 @@ -39,6 +97,7 @@ jobs: submodules: recursive fetch-depth: 0 repository: 'leejet/stable-diffusion.cpp' + ref: ${{ needs.resolve-upstream.outputs.sha }} - name: Setup Node uses: actions/setup-node@v4 @@ -94,6 +153,8 @@ jobs: sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-${{ steps.system-info.outputs.OS_NAME }}-${{ steps.system-info.outputs.OS_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}.zip ubuntu-latest-cmake-vulkan: + needs: resolve-upstream + if: needs.resolve-upstream.outputs.skip != 'true' # Pinned for the same reason as ubuntu-latest-cmake. runs-on: ubuntu-24.04 @@ -104,6 +165,7 @@ jobs: submodules: recursive fetch-depth: 0 repository: 'leejet/stable-diffusion.cpp' + ref: ${{ needs.resolve-upstream.outputs.sha }} - name: Setup Node uses: actions/setup-node@v4 @@ -159,6 +221,8 @@ jobs: sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-${{ steps.system-info.outputs.OS_NAME }}-${{ steps.system-info.outputs.OS_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}-vulkan.zip ubuntu-latest-cuda: + needs: resolve-upstream + if: needs.resolve-upstream.outputs.skip != 'true' runs-on: ubuntu-22.04 strategy: @@ -175,7 +239,7 @@ jobs: submodules: recursive fetch-depth: 0 repository: 'leejet/stable-diffusion.cpp' - ref: master + ref: ${{ needs.resolve-upstream.outputs.sha }} - name: ccache uses: ggml-org/ccache-action@v1.2.16 @@ -286,6 +350,8 @@ jobs: path: sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-ubuntu-cuda-${{ matrix.sm }}-x64.tar.xz windows-latest-cuda: + needs: resolve-upstream + if: needs.resolve-upstream.outputs.skip != 'true' runs-on: windows-2022 strategy: @@ -302,7 +368,7 @@ jobs: submodules: recursive fetch-depth: 0 repository: 'leejet/stable-diffusion.cpp' - ref: master + ref: ${{ needs.resolve-upstream.outputs.sha }} - name: Install CUDA Toolkit id: cuda-toolkit @@ -376,6 +442,8 @@ jobs: path: sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-windows-cuda-${{ matrix.sm }}-x64.zip ubuntu-arm64-cuda: + needs: resolve-upstream + if: needs.resolve-upstream.outputs.skip != 'true' # GB10 (sm_121) ARM64 Linux build runs-on: ubuntu-24.04-arm @@ -392,7 +460,7 @@ jobs: submodules: recursive fetch-depth: 0 repository: 'leejet/stable-diffusion.cpp' - ref: master + ref: ${{ needs.resolve-upstream.outputs.sha }} - name: ccache uses: ggml-org/ccache-action@v1.2.16 @@ -488,12 +556,16 @@ jobs: path: sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-ubuntu-cuda-${{ matrix.sm }}-arm64.tar.xz windows-latest-cmake: + needs: resolve-upstream + if: needs.resolve-upstream.outputs.skip != 'true' runs-on: windows-2022 env: VULKAN_VERSION: 1.4.328.1 strategy: + # Each build is published as its own family, so one failing must not cancel the others. + fail-fast: false matrix: include: - build: "cpu" @@ -509,6 +581,7 @@ jobs: submodules: recursive fetch-depth: 0 repository: 'leejet/stable-diffusion.cpp' + ref: ${{ needs.resolve-upstream.outputs.sha }} - name: Setup Node uses: actions/setup-node@v4 @@ -609,6 +682,8 @@ jobs: sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-${{ matrix.build }}-x64.zip windows-latest-rocm: + needs: resolve-upstream + if: needs.resolve-upstream.outputs.skip != 'true' runs-on: windows-2022 strategy: @@ -631,6 +706,7 @@ jobs: submodules: recursive fetch-depth: 0 repository: 'leejet/stable-diffusion.cpp' + ref: ${{ needs.resolve-upstream.outputs.sha }} - name: Setup Node uses: actions/setup-node@v4 @@ -728,13 +804,8 @@ jobs: -DGPU_TARGETS="${{ matrix.gpu_targets }}" cmake --build . --config Release --parallel ${env:NUMBER_OF_PROCESSORS} - - name: Get commit hash - id: commit - if: ${{ github.event_name == 'schedule' || github.event.inputs.create_release == 'true' }} - uses: pr-mpt/actions-commit-hash@v2 - + # Packed on every event, pull requests included, so the qualify jobs can test the archive. - name: Bundle HIP runtime libraries - if: ${{ github.event_name == 'schedule' || github.event.inputs.create_release == 'true' }} run: | $ErrorActionPreference = "Stop" $binPath = (rocm-sdk path --bin).Trim() @@ -746,19 +817,50 @@ jobs: } - name: Pack artifacts - if: ${{ github.event_name == 'schedule' || github.event.inputs.create_release == 'true' }} run: | - 7z a sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-rocm-${{ matrix.ROCM_VERSION }}-x64.zip .\build\bin\* + Copy-Item ggml/LICENSE .\build\bin\ggml.txt + Copy-Item LICENSE .\build\bin\stable-diffusion.cpp.txt + 7z a sd-${{ env.BRANCH_NAME }}-${{ needs.resolve-upstream.outputs.short }}-bin-win-rocm-${{ matrix.ROCM_VERSION }}-x64.zip .\build\bin\* + + # The qualify jobs audit the archive against this job's own gpu_targets, and the + # release job proves with the SHA-256 that it uploads the archive they tested (T0.12). + - name: Record qualification metadata + run: | + $archive = 'sd-${{ env.BRANCH_NAME }}-${{ needs.resolve-upstream.outputs.short }}-bin-win-rocm-${{ matrix.ROCM_VERSION }}-x64.zip' + $short = ('${{ matrix.ROCM_VERSION }}'.Split('.')[0..1] -join '.') + $meta = [ordered]@{ + os = 'win' + rocm_version = $short + rocm_version_full = '${{ matrix.ROCM_VERSION }}' + gpu_targets = '${{ matrix.gpu_targets }}' + tag = '${{ needs.resolve-upstream.outputs.tag }}' + upstream_sha = '${{ needs.resolve-upstream.outputs.sha }}' + artifact = $archive + sha256 = (Get-FileHash -Algorithm SHA256 -Path $archive).Hash.ToLowerInvariant() + } + $path = "qualify-meta-win-rocm-$short.json" + $meta | ConvertTo-Json | Set-Content -Path $path -Encoding utf8 + Get-Content $path + echo "ROCM_VERSION_SHORT=$short" >> $env:GITHUB_ENV - name: Upload artifacts - if: ${{ github.event_name == 'schedule' || github.event.inputs.create_release == 'true' }} uses: actions/upload-artifact@v4 with: - name: sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-rocm-${{ matrix.ROCM_VERSION }}-x64.zip + name: sd-${{ env.BRANCH_NAME }}-${{ needs.resolve-upstream.outputs.short }}-bin-win-rocm-${{ matrix.ROCM_VERSION }}-x64.zip path: | - sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-rocm-${{ matrix.ROCM_VERSION }}-x64.zip + sd-${{ env.BRANCH_NAME }}-${{ needs.resolve-upstream.outputs.short }}-bin-win-rocm-${{ matrix.ROCM_VERSION }}-x64.zip + retention-days: ${{ github.event_name == 'pull_request' && '7' || '' }} + + - name: Upload qualification metadata + uses: actions/upload-artifact@v4 + with: + name: qualify-meta-win-rocm-${{ env.ROCM_VERSION_SHORT }} + path: qualify-meta-win-rocm-${{ env.ROCM_VERSION_SHORT }}.json + retention-days: ${{ github.event_name == 'pull_request' && '7' || '' }} ubuntu-latest-rocm: + needs: resolve-upstream + if: needs.resolve-upstream.outputs.skip != 'true' runs-on: ubuntu-24.04 env: @@ -770,13 +872,13 @@ jobs: matrix: include: - ROCM_VERSION: "10.0.0" - gpu_targets: "gfx908;gfx90a;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1150;gfx1151;gfx1152;gfx1200;gfx1201" + gpu_targets: "gfx908;gfx90a;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201" build: 'x64' - ROCM_VERSION: "10.1.0" - gpu_targets: "gfx908;gfx90a;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1150;gfx1151;gfx1152;gfx1200;gfx1201" + gpu_targets: "gfx908;gfx90a;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201" build: 'x64' - ROCM_VERSION: "10.2.0" - gpu_targets: "gfx908;gfx90a;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1150;gfx1151;gfx1152;gfx1200;gfx1201" + gpu_targets: "gfx908;gfx90a;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201" build: 'x64' steps: @@ -787,6 +889,7 @@ jobs: submodules: recursive fetch-depth: 0 repository: 'leejet/stable-diffusion.cpp' + ref: ${{ needs.resolve-upstream.outputs.sha }} - name: ccache uses: ggml-org/ccache-action@v1.2.16 @@ -807,7 +910,7 @@ jobs: - name: Dependencies id: depends run: | - sudo apt install -y build-essential git cmake wget + sudo apt install -y build-essential git cmake wget patchelf - name: Free disk space run: | @@ -893,18 +996,16 @@ jobs: -DSD_BUILD_SHARED_LIBS=ON cmake --build . --config Release - - name: Get commit hash - id: commit - if: ${{ github.event_name == 'schedule' || github.event.inputs.create_release == 'true' }} - uses: prompt/actions-commit-hash@v2 - - - name: Prepare artifacts - id: prepare_artifacts - if: ${{ github.event_name == 'schedule' || github.event.inputs.create_release == 'true' }} + # The HIP link adds the pip-installed ROCm devel tree to RUNPATH + # (.../_rocm_sdk_devel/lib), a build-machine path that means nothing on a user's machine. + - name: Normalize RPATH for portable distribution run: | - # Copy licenses - cp ggml/LICENSE ./build/bin/ggml.txt - cp LICENSE ./build/bin/stable-diffusion.cpp.txt + for f in build/bin/*; do + [ -f "$f" ] && ! [ -L "$f" ] || continue + if file "$f" | grep -q 'ELF'; then + patchelf --set-rpath '$ORIGIN' "$f" + fi + done - name: Fetch system info id: system-info @@ -914,23 +1015,53 @@ jobs: echo "OS_VERSION=`lsb_release -s -r`" >> "$GITHUB_OUTPUT" echo "OS_TYPE=`uname -s`" >> "$GITHUB_OUTPUT" + # Packed on every event, pull requests included, so the qualify jobs can test the archive. - name: Pack artifacts id: pack_artifacts - if: ${{ github.event_name == 'schedule' || github.event.inputs.create_release == 'true' }} run: | cp ggml/LICENSE ./build/bin/ggml.txt cp LICENSE ./build/bin/stable-diffusion.cpp.txt - zip -y -r sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-Ubuntu-${{ env.UBUNTU_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}-rocm-${{ matrix.ROCM_VERSION }}.zip ./build/bin + archive=sd-${{ env.BRANCH_NAME }}-${{ needs.resolve-upstream.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-Ubuntu-${{ env.UBUNTU_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}-rocm-${{ matrix.ROCM_VERSION }}.zip + zip -y -r "$archive" ./build/bin + echo "archive=$archive" >> "$GITHUB_OUTPUT" + echo "ROCM_VERSION_SHORT=$(echo '${{ matrix.ROCM_VERSION }}' | cut -d '.' -f 1,2)" >> "$GITHUB_ENV" + + # Same as windows-latest-rocm, SHA-256 included. + - name: Record qualification metadata + env: + ARCHIVE: ${{ steps.pack_artifacts.outputs.archive }} + run: | + cat > "qualify-meta-ubuntu-rocm-${ROCM_VERSION_SHORT}.json" <- + python .github/qualify-rocm/install_rocm.py + --version ${{ matrix.rocm }}.0 + --arch gfx1151 + + - name: Run Tier 0 static verification + run: >- + python .github/qualify-rocm/tier0_static.py + --meta meta/qualify-meta-${{ matrix.os }}-rocm-${{ matrix.rocm }}.json + --archive-dir ./artifact + --run-binaries + --fail-on-error + --output fragments/tier0-${{ matrix.os }}-rocm-${{ matrix.rocm }}.json + + - name: Upload Tier 0 report + if: always() + uses: actions/upload-artifact@v4 + with: + name: qualify-fragments-tier0-${{ matrix.os }}-${{ matrix.rocm }} + path: fragments/*.json + if-no-files-found: warn + + qualify-tier1: + # Runs on every event except a pull request from a fork, which must not reach the self-hosted GPU runners. + if: >- + ${{ !cancelled() && needs.resolve-upstream.result == 'success' && needs.resolve-upstream.outputs.skip != 'true' && + (github.event_name != 'pull_request' || + github.event.pull_request.head.repo.full_name == github.repository) }} + needs: + - resolve-upstream + - ubuntu-latest-rocm + - windows-latest-rocm + timeout-minutes: 60 + + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu + rocm: "10.0" + runner: [self-hosted, strix-halo, xsj-dispatch, Linux] + - os: ubuntu + rocm: "10.1" + runner: [self-hosted, strix-halo, xsj-dispatch, Linux] + - os: ubuntu + rocm: "10.2" + runner: [self-hosted, strix-halo, xsj-dispatch, Linux] + - os: win + rocm: "10.0" + runner: [self-hosted, strix-halo, xsj-dispatch, Windows] + - os: win + rocm: "10.1" + runner: [self-hosted, strix-halo, xsj-dispatch, Windows] + - os: win + rocm: "10.2" + runner: [self-hosted, strix-halo, xsj-dispatch, Windows] + + runs-on: ${{ matrix.runner }} + + steps: + - name: Checkout qualification suite + uses: actions/checkout@v6 + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: '3.12' + + # Self-hosted runners may carry another Python earlier on PATH. + - name: Pin the interpreter + shell: python + run: | + import os + location = os.environ["pythonLocation"] + interpreter = (os.path.join(location, "python.exe") if os.name == "nt" + else os.path.join(location, "bin", "python")) + if not os.path.exists(interpreter): + raise SystemExit(f"::error::no interpreter at {interpreter}") + with open(os.environ["GITHUB_ENV"], "a", encoding="utf-8") as handle: + handle.write(f"QUALIFY_PYTHON={interpreter}\n") + + - name: Download qualification metadata + uses: actions/download-artifact@v4 + with: + name: qualify-meta-${{ matrix.os }}-rocm-${{ matrix.rocm }} + path: ./meta + + - name: Name the archive + id: archive + shell: python + run: | + import json, os + with open("meta/qualify-meta-${{ matrix.os }}-rocm-${{ matrix.rocm }}.json", encoding="utf-8-sig") as handle: + name = json.load(handle)["artifact"] + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as out: + out.write(f"name={name}\n") + + - name: Download ROCm archive + uses: actions/download-artifact@v4 + with: + name: ${{ steps.archive.outputs.name }} + path: ./artifact + + - name: Install a user-style ROCm runtime + run: >- + ${{ env.QUALIFY_PYTHON }} .github/qualify-rocm/install_rocm.py + --version ${{ matrix.rocm }}.0 + --arch gfx1151 + --output-json rocm-install.json + + - name: Run Tier 1 GPU inference + run: >- + ${{ env.QUALIFY_PYTHON }} .github/qualify-rocm/tier1_gpu.py + --meta meta/qualify-meta-${{ matrix.os }}-rocm-${{ matrix.rocm }}.json + --archive-dir ./artifact + --gfx-target gfx1151 + --logs-dir fragments + --fail-on-error + --output fragments/tier1-${{ matrix.os }}-rocm-${{ matrix.rocm }}.json + + - name: Upload Tier 1 report + if: always() + uses: actions/upload-artifact@v4 + with: + name: qualify-fragments-tier1-${{ matrix.os }}-${{ matrix.rocm }} + path: | + fragments/*.json + fragments/*.log + if-no-files-found: warn + + # Backstop for a cancelled run. Only sd-server processes started from this job's + # temp folder are stopped, never another one on a shared machine. + - name: Tear down (Windows) + if: always() && runner.os == 'Windows' + continue-on-error: true + shell: powershell + run: | + Get-Process sd-server -ErrorAction SilentlyContinue | + Where-Object { $_.Path -and $_.Path.StartsWith($env:RUNNER_TEMP, [StringComparison]::OrdinalIgnoreCase) } | + Stop-Process -Force + + - name: Tear down (Linux) + if: always() && runner.os == 'Linux' + continue-on-error: true + run: pkill -f "${RUNNER_TEMP}/tier1-[^ ]*/sd-server" || true + release: - # always() overrides the default behavior of skipping this job when a - # needed build job fails (e.g. one CUDA sm_* matrix leg fails while - # sibling legs succeed and upload). The job must still run so the - # per-family checks below can decide what's actually complete and safe - # to publish. - if: ${{ always() && (github.event_name == 'schedule' || github.event.inputs.create_release == 'true') }} + # !cancelled() so a failed build leg does not skip the release -- the per-family + # checks below decide what is complete and safe to publish -- while a run + # cancelled before this job starts publishes nothing. A cancel during the upload + # leaves what was already uploaded; the next nightly sees the gap and refills it. + if: >- + ${{ !cancelled() && needs.resolve-upstream.result == 'success' && + needs.resolve-upstream.outputs.skip != 'true' && + (github.event_name == 'schedule' || github.event.inputs.create_release == 'true') }} permissions: contents: write - runs-on: ubuntu-latest + # Two runs on the same tag (a manual release overlapping the nightly) would + # otherwise upload into one release at once and could pair one run's + # qualification record with the other run's archive. The second one waits. + concurrency: + group: release-${{ needs.resolve-upstream.outputs.tag }} + cancel-in-progress: false + + runs-on: ubuntu-24.04 needs: + - resolve-upstream - ubuntu-latest-cmake - ubuntu-latest-cmake-vulkan - ubuntu-latest-cuda @@ -1021,6 +1370,17 @@ jobs: - macos-arm64-cmake - windows-latest-cmake - windows-latest-rocm + - qualify-tier0 + - qualify-tier1 + + # For publish-qualification: the ROCm archives T0.12 ran on, and the ones this run uploaded. + outputs: + final_checked: ${{ steps.final.outputs.archives }} + published_rocm: ${{ steps.upload_release.outputs.rocm }} + + env: + TAG: ${{ needs.resolve-upstream.outputs.tag }} + SHORT: ${{ needs.resolve-upstream.outputs.short }} steps: - name: Clone @@ -1030,6 +1390,12 @@ jobs: submodules: recursive fetch-depth: 0 repository: 'leejet/stable-diffusion.cpp' + ref: ${{ needs.resolve-upstream.outputs.sha }} + + - name: Checkout qualification suite + uses: actions/checkout@v6 + with: + path: lemonade-ci - name: Download artifacts id: download-artifact @@ -1039,105 +1405,119 @@ jobs: pattern: sd-* merge-multiple: true - - name: Get commit count - id: commit_count - run: | - echo "count=$(git rev-list --count HEAD)" >> $GITHUB_OUTPUT - - - name: Get commit hash - id: commit - uses: prompt/actions-commit-hash@v2 - - - name: Generate tag name - id: tag_name - run: | - TAG_NAME="${{ env.BRANCH_NAME }}-${{ steps.commit_count.outputs.count }}-${{ steps.commit.outputs.short }}" - echo "name=${TAG_NAME}" >> $GITHUB_OUTPUT - + # Each backend family ships as a complete set or not at all; each ROCm version is + # its own family, so a gap in one version never withholds another. - name: Check release artifacts id: check_artifacts - env: - BRANCH: ${{ env.BRANCH_NAME }} - SHORT: ${{ steps.commit.outputs.short }} - run: | - total_missing=0 - summary="" - - check_family() { - local family="$1"; shift - local patterns=("$@") - local missing=0 - for pattern in "${patterns[@]}"; do - if ! ls $pattern >/dev/null 2>&1; then - echo "::error::[$family] Missing artifact: $pattern" - missing=$((missing + 1)) - fi - done - if [ "$missing" -gt 0 ]; then - echo "::warning::$family family is incomplete ($missing artifact(s) missing) — dropping all $family artifacts from this release." - for pattern in "${patterns[@]}"; do - rm -fv $pattern 2>/dev/null || true - done - total_missing=$((total_missing + missing)) - summary="${summary}${summary:+, }${family}: $missing missing, family dropped" - fi - } - - # Each backend family must be published as a complete, internally - # consistent set across every platform/variant/SDK it covers — never - # a partial mix. A gap in one family drops that whole family from - # the release; other families are unaffected. - - # CUDA: 8 sm_* variants on ubuntu x64 and windows x64; only sm_121 - # (GB10) is built for ubuntu arm64. - cuda_patterns=() - for sm in sm_75 sm_80 sm_86 sm_89 sm_90 sm_100 sm_120 sm_121; do - cuda_patterns+=("artifact/sd-${BRANCH}-${SHORT}-ubuntu-cuda-${sm}-x64.tar.xz") - cuda_patterns+=("artifact/sd-${BRANCH}-${SHORT}-windows-cuda-${sm}-x64.zip") - done - cuda_patterns+=("artifact/sd-${BRANCH}-${SHORT}-ubuntu-cuda-sm_121-arm64.tar.xz") - check_family cuda "${cuda_patterns[@]}" - - # TheRock ROCm: each version is its own family. Lemonade downloads exactly - # the version its `therock.version` pin names, so a gap in one version must - # not withhold another; only the Windows+Linux pair within a version must match. - # Keep this list in sync with the windows-latest-rocm and ubuntu-latest-rocm matrices. - for rocm_ver in 10.0.0 10.1.0 10.2.0; do - check_family "rocm-${rocm_ver}" \ - "artifact/sd-${BRANCH}-${SHORT}-bin-win-rocm-${rocm_ver}-x64.zip" \ - "artifact/sd-${BRANCH}-${SHORT}-bin-Linux-Ubuntu-24.04-x86_64-rocm-${rocm_ver}.zip" - done + run: >- + python3 lemonade-ci/.github/qualify-rocm/release_assets.py check-dir + --dir artifact --branch "$BRANCH_NAME" --short "$SHORT" --rocm-versions "$ROCM_VERSIONS" - # CPU: ubuntu-latest-cmake's filename embeds the runner's OS name/ - # version via lsb_release, so it's wildcarded rather than pinned. - check_family cpu \ - "artifact/sd-${BRANCH}-${SHORT}-bin-Linux-*-x86_64.zip" \ - "artifact/sd-${BRANCH}-${SHORT}-bin-win-cpu-x64.zip" + - name: Download qualification fragments + uses: actions/download-artifact@v4 + with: + pattern: qualify-fragments-* + path: ./fragments + merge-multiple: true - # Vulkan: same runner as CPU, differs only in -DSD_VULKAN=ON. - # Only builds Linux since the runner doesn't have a dedicated Windows vulkan build. - check_family vulkan \ - "artifact/sd-${BRANCH}-${SHORT}-bin-Linux-*-x86_64-vulkan.zip" + - name: Download qualification metadata + uses: actions/download-artifact@v4 + with: + pattern: qualify-meta-* + path: ./meta + merge-multiple: true - check_family metal \ - "artifact/sd-${BRANCH}-${SHORT}-bin-Darwin-macOS-*-arm64.zip" + # T0.12: the exact files about to be uploaded are the ones Tier 0 and Tier 1 tested. + - name: Final-archive checks + id: final + run: | + shopt -s nullglob + mkdir -p fragments + # Only this attempt's final checks count, never ones downloaded from an earlier attempt. + rm -f fragments/tier0-final-*.json + checked="" + for archive in artifact/sd-"${BRANCH_NAME}-${SHORT}"-bin-*-rocm-*.zip; do + base=$(basename "$archive") + if [[ "$base" == *-win-rocm-* ]]; then os=win; else os=ubuntu; fi + ver=$(sed -E 's/.*-rocm-([0-9]+\.[0-9]+)\.[0-9]+(-x64)?\.zip$/\1/' <<<"$base") + checked="${checked:+$checked }$base" + python3 lemonade-ci/.github/qualify-rocm/check_final.py \ + --archive "$archive" --meta "meta/qualify-meta-$os-rocm-$ver.json" \ + --output "fragments/tier0-final-$os-rocm-$ver.json" \ + || echo "::error::check_final.py crashed on $base, so T0.12 will show as missing" + done + echo "archives=$checked" >> "$GITHUB_OUTPUT" - echo "missing=$total_missing" >> "$GITHUB_OUTPUT" - echo "summary=$summary" >> "$GITHUB_OUTPUT" + # So publish-qualification can still see T0.12 if this job stops before writing records. + - name: Upload final-archive reports + if: ${{ !cancelled() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: qualify-fragments-final + path: fragments/tier0-final-*.json + if-no-files-found: ignore - files=$(find ./artifact -maxdepth 1 \( -name '*.zip' -o -name '*.tar.xz' \) 2>/dev/null | wc -l) + - name: Qualify ROCm release artifacts + id: qualify + continue-on-error: true + run: | + mkdir -p qualification + python3 lemonade-ci/.github/qualify-rocm/aggregate.py \ + --fragments-dir ./fragments \ + --tag "$TAG" \ + --records-dir ./qualification \ + --output-summary ./qualification/qualification-summary.json \ + --operating-systems "$ROCM_OPERATING_SYSTEMS" \ + --rocm-versions "$ROCM_VERSIONS" \ + --require-final \ + --fail-on-no-promote + + # Uploaded straight away so a later failure in this job cannot keep them out of the feed. + - name: Upload qualification records + if: always() + uses: actions/upload-artifact@v4 + with: + name: qualification-records + path: qualification/*.json + if-no-files-found: warn - # Never create or update a release with nothing to publish. - if [ "$files" -eq 0 ]; then - echo "::error::No release artifacts found in ./artifact — aborting before creating a release." - exit 1 + - name: Drop unqualified ROCm versions + id: rocm_gate + env: + PROMOTE: ${{ steps.qualify.outputs.promote_rocm }} + BLOCKED: ${{ steps.qualify.outputs.blocked_rocm_versions }} + run: | + if [ "$PROMOTE" = "true" ]; then + echo "Every ROCm version qualified." + echo "dropped=0" >> "$GITHUB_OUTPUT" + exit 0 fi - - if [ "$total_missing" -gt 0 ]; then - echo "$total_missing artifact(s) missing ($summary) — continuing to publish the $files artifact(s) from complete families. The job will still fail below so the gap gets noticed." - else - echo "All expected artifacts present. Found $files artifact(s) ready to upload." + # No verdict at all means no evidence for any version, so withhold them all. + blocked="$BLOCKED" + if [ -z "$blocked" ]; then + blocked="${ROCM_VERSIONS//,/ }" + echo "::warning::Qualification produced no verdict; withholding every ROCm version." fi + dropped=0 + for version in $blocked; do + for archive in "artifact/sd-${BRANCH_NAME}-${SHORT}-bin-win-rocm-${version}.0-x64.zip" \ + "artifact/sd-${BRANCH_NAME}-${SHORT}-bin-Linux-"*"-rocm-${version}.0.zip"; do + [ -f "$archive" ] || continue + echo "::warning::ROCm ${version} did not qualify; withholding $(basename "$archive")." + rm -fv "$archive" + dropped=$((dropped + 1)) + done + done + echo "dropped=$dropped" >> "$GITHUB_OUTPUT" + echo "blocked=$blocked" >> "$GITHUB_OUTPUT" + + - name: Stage qualification records as release assets + run: | + shopt -s nullglob + for record in qualification/qualification-sd-*.json; do + cp -v "$record" artifact/ + done - name: Determine release summary id: release_summary @@ -1148,20 +1528,16 @@ jobs: echo "value=$(git log -1 --pretty=%s)" >> "$GITHUB_OUTPUT" fi - # Get the release for this tag, creating it if it does not exist yet. - # This is idempotent: if a previous run created the release but failed - # partway through uploading (e.g. a transient GitHub outage), re-running - # reuses the existing release so the upload step below can fill the gaps. + # Reuses the release when the tag already exists (an earlier run left gaps to fill). - name: Create or get release id: release uses: actions/github-script@v8 env: - TAG_NAME: ${{ steps.tag_name.outputs.name }} RELEASE_SUMMARY: ${{ steps.release_summary.outputs.value }} with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | - const tag = process.env.TAG_NAME; + const tag = process.env.TAG; const { owner, repo } = context.repo; let release; try { @@ -1170,7 +1546,7 @@ jobs: } catch (e) { if (e.status !== 404) throw e; try { - release = (await github.rest.repos.createRelease({ owner, repo, tag_name: tag, body: process.env.RELEASE_SUMMARY })).data; + release = (await github.rest.repos.createRelease({ owner, repo, tag_name: tag, name: tag, body: process.env.RELEASE_SUMMARY })).data; core.info(`Created release ${tag} (id ${release.id})`); } catch (createError) { if (createError.status !== 422) throw createError; @@ -1180,23 +1556,22 @@ jobs: } core.setOutput('id', release.id); + # Assets already in the release are never replaced: Lemonade may already pin them, and + # they were qualified when they were uploaded. A record is uploaded with its archive. + # checksums.txt is rebuilt from GitHub's digests, so it always matches what is published. - name: Upload release id: upload_release uses: actions/github-script@v8 env: RELEASE_ID: ${{ steps.release.outputs.id }} with: - github-token: ${{secrets.GITHUB_TOKEN}} + github-token: ${{ secrets.GITHUB_TOKEN }} script: | const fs = require('fs'); const { owner, repo } = context.repo; const release_id = Number(process.env.RELEASE_ID); - const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); - // Retry transient failures (network errors, 5xx, rate limits) with - // exponential backoff so a momentary GitHub blip does not abort the - // whole upload and leave the release partially populated. async function withRetry(label, fn, attempts = 5) { for (let i = 1; ; i++) { try { @@ -1210,63 +1585,256 @@ jobs: } } } + const listAssets = () => github.paginate(github.rest.repos.listReleaseAssets, { owner, repo, release_id }); + async function upload(name, data) { + await withRetry(`upload ${name}`, () => + github.rest.repos.uploadReleaseAsset({ owner, repo, release_id, name, data }) + .catch(async (e) => { + if (e.status !== 422) throw e; + const asset = (await listAssets()).find((a) => a.name === name); + if (asset?.state === 'uploaded') return; + if (asset) await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id }); + throw new Error(`retrying upload for ${name} after deleting conflicting asset`); + })); + core.info(`uploaded ${name}`); + } + async function remove(asset, reason) { + core.warning(`deleting ${reason} asset ${asset.name}`); + await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id }); + } - const files = fs.readdirSync('./artifact').filter((f) => f.endsWith('.zip') || f.endsWith('.tar.xz')); - const wanted = new Set(files); - - // Reconcile existing release assets against what this run decided to - // publish: drop anything not fully uploaded (a broken partial upload) - // and anything not in the current file set. The latter case matters - // because the release is reused across runs against the same tag — - // if a family was complete and published in an earlier run but this - // run finds it incomplete and drops it locally, its assets from that - // earlier run would otherwise linger and make the family look - // complete even though this run couldn't reproduce it. - const existing = new Set(); - for (const a of await github.paginate(github.rest.repos.listReleaseAssets, { owner, repo, release_id })) { - if (a.state === 'uploaded' && wanted.has(a.name)) { - existing.add(a.name); - } else { - const reason = a.state !== 'uploaded' ? `incomplete (${a.state})` : 'stale (not part of this run)'; - core.warning(`deleting ${reason} asset ${a.name}`); - await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: a.id }); - } + const published = new Map(); + for (const a of await listAssets()) { + if (a.state === 'uploaded') published.set(a.name, a); + else await remove(a, `incomplete (${a.state})`); } - let uploaded = 0; - let skipped = 0; - for (const file of files) { - if (existing.has(file)) { - core.info(`skipping ${file} (already uploaded)`); - skipped++; + const files = fs.readdirSync('./artifact'); + const archives = files.filter((f) => f.endsWith('.zip') || f.endsWith('.tar.xz')); + // A record goes up before its archive, so an archive is never published without one. + const records = files.filter((f) => f.startsWith('qualification-') && f.endsWith('.json')); + const recordFor = (archive) => `qualification-${archive.replace(/\.(zip|tar\.xz)$/, '')}.json`; + async function uploadRecord(record) { + if (published.has(record)) await remove(published.get(record), 'superseded'); + await upload(record, fs.readFileSync(`./artifact/${record}`)); + } + const uploaded = []; + for (const file of archives) { + if (published.has(file)) { + core.info(`keeping ${file} (already published)`); continue; } - const data = fs.readFileSync(`./artifact/${file}`); - await withRetry(`upload ${file}`, () => - github.rest.repos.uploadReleaseAsset({ owner, repo, release_id, name: file, data }) - .catch(async (e) => { - if (e.status !== 422) throw e; - const assets = await github.paginate(github.rest.repos.listReleaseAssets, { owner, repo, release_id }); - const asset = assets.find((a) => a.name === file); - if (asset?.state === 'uploaded') { - core.info(`accepting ${file} (already uploaded)`); - return; - } - if (asset) { - core.warning(`deleting conflicting asset ${file} (${asset.state})`); - await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id }); - throw new Error(`retrying upload for ${file} after deleting conflicting asset`); - } - throw e; - })); - core.info(`uploaded ${file}`); - uploaded++; + if (records.includes(recordFor(file))) await uploadRecord(recordFor(file)); + await upload(file, fs.readFileSync(`./artifact/${file}`)); + uploaded.push(file); + // Written after every upload, so a later failure still reports what did ship. + core.setOutput('rocm', uploaded.filter((f) => /-rocm-/.test(f)).join(' ')); + } + // Records of withheld archives say why they were withheld. + for (const record of records) { + const archive = record.replace(/^qualification-/, '').replace(/\.json$/, '.zip'); + if (!published.has(archive) && !uploaded.includes(archive)) await uploadRecord(record); } - core.info(`Done: ${uploaded} uploaded, ${skipped} already present, ${files.length} total.`); + const assets = (await listAssets()).filter((a) => a.state === 'uploaded'); + const sums = assets.filter((a) => a.name.endsWith('.zip') || a.name.endsWith('.tar.xz')) + .sort((a, b) => a.name.localeCompare(b.name)) + .map((a) => { + if (!a.digest?.startsWith('sha256:')) throw new Error(`no SHA-256 digest for ${a.name}`); + return `${a.digest.slice('sha256:'.length)} ${a.name}`; + }); + const old = assets.find((a) => a.name === 'checksums.txt'); + if (old) await remove(old, 'superseded'); + await upload('checksums.txt', Buffer.from(sums.join('\n') + '\n')); + + const names = assets.map((a) => a.name).filter((n) => n !== 'checksums.txt'); + fs.writeFileSync('release-assets.txt', [...names, 'checksums.txt'].join('\n') + '\n'); + core.setOutput('rocm', uploaded.filter((f) => /-rocm-/.test(f)).join(' ')); + core.info(`Done: ${uploaded.length} archive(s) uploaded, ${archives.length - uploaded.length} already published.`); + + - name: Write release notes + env: + RELEASE_SUMMARY: ${{ steps.release_summary.outputs.value }} + run: >- + python3 lemonade-ci/.github/qualify-rocm/release_notes.py + --tag "$TAG" --repo "${{ github.repository }}" + --assets-file release-assets.txt --rocm-versions "$ROCM_VERSIONS" + --summary "$RELEASE_SUMMARY" --output release-notes.md + + - name: Update release notes + uses: actions/github-script@v8 + env: + RELEASE_ID: ${{ steps.release.outputs.id }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const fs = require('fs'); + const { owner, repo } = context.repo; + await github.rest.repos.updateRelease({ + owner, repo, release_id: Number(process.env.RELEASE_ID), + name: process.env.TAG, body: fs.readFileSync('release-notes.md', 'utf8'), + }); - name: Fail if any artifacts were missing if: steps.check_artifacts.outputs.missing != '0' run: | echo "::error::${{ steps.check_artifacts.outputs.missing }} artifact(s) were missing (${{ steps.check_artifacts.outputs.summary }}) — the incomplete families were dropped from this release; other families were still published. See the 'Check release artifacts' step for the full per-file list." exit 1 + + - name: Fail if ROCm qualification did not pass + if: steps.rocm_gate.outputs.dropped != '0' + run: | + echo "::error::ROCm ${{ steps.rocm_gate.outputs.blocked }} did not qualify — ${{ steps.rocm_gate.outputs.dropped }} archive(s) were withheld. Every other ROCm version and backend was published normally. The attached qualification-*.json records list each failing check." + exit 1 + + # Publishes every run's ROCm qualification records, passing or failing, to the + # qualification-data branch the ROCm readiness dashboard reads (format: .github/qualify-rocm/FEED.md). + # A nightly skipped because its release was already complete records only that it + # checked and found nothing new (index.json "last_check"). The branch is created on the first publish. + publish-qualification: + if: >- + ${{ !cancelled() && needs.resolve-upstream.result == 'success' && + (needs.resolve-upstream.outputs.skip == 'true' || + needs.release.result == 'success' || needs.release.result == 'failure') }} + needs: + - resolve-upstream + - release + + runs-on: ubuntu-24.04 + + permissions: + contents: write # to push to the qualification-data branch + actions: read # to read each ROCm build job's result + + steps: + - name: Checkout qualification suite + uses: actions/checkout@v6 + with: + path: lemonade-ci + + - name: Download qualification records + if: needs.resolve-upstream.outputs.skip != 'true' + continue-on-error: true + uses: actions/download-artifact@v4 + with: + name: qualification-records + path: ./records + + - name: Download qualification fragments + if: needs.resolve-upstream.outputs.skip != 'true' + continue-on-error: true + uses: actions/download-artifact@v4 + with: + pattern: qualify-fragments-* + path: ./fragments + merge-multiple: true + + # If the release job stopped before writing records, build them from the tier reports. + - name: Collect qualification records + if: needs.resolve-upstream.outputs.skip != 'true' + env: + TAG: ${{ needs.resolve-upstream.outputs.tag }} + run: | + set -euo pipefail + shopt -s nullglob + records=(records/qualification-sd-*.json) + if [ ${#records[@]} -gt 0 ]; then + echo "Using the ${#records[@]} record(s) the release job wrote." + exit 0 + fi + echo "The release job wrote no records; building them from the Tier 0 and Tier 1 reports." + mkdir -p records fragments + python3 lemonade-ci/.github/qualify-rocm/aggregate.py \ + --fragments-dir ./fragments \ + --tag "$TAG" \ + --records-dir ./records \ + --output-summary ./records/qualification-summary.json \ + --operating-systems "$ROCM_OPERATING_SYSTEMS" \ + --rocm-versions "$ROCM_VERSIONS" \ + --require-final + + - name: Read build job results + if: needs.resolve-upstream.outputs.skip != 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + set -uo pipefail + for attempt in 1 2 3; do + if gh api --paginate \ + "repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/jobs?filter=latest&per_page=100" \ + --jq '.jobs[] | {name, conclusion}' > jobs.jsonl; then + grep -E '"name":"(ubuntu-latest-rocm|windows-latest-rocm) ' jobs.jsonl || true + exit 0 + fi + echo "Could not read the run's jobs (attempt $attempt); retrying" + sleep $((attempt * 5)) + done + echo "::warning::Could not read the run's jobs; build_result will be 'unknown'." + : > jobs.jsonl + + - name: Publish to qualification-data branch + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.resolve-upstream.outputs.tag }} + UPSTREAM_SHA: ${{ needs.resolve-upstream.outputs.sha }} + PUBLISHED_ROCM: ${{ needs.release.outputs.published_rocm }} + FINAL_CHECKED: ${{ needs.release.outputs.final_checked }} + UNCHANGED: ${{ needs.resolve-upstream.outputs.skip }} + run: | + set -euo pipefail + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + REPO_URL="https://x-access-token:${GH_TOKEN}@github.com/${{ github.repository }}.git" + BRANCH="qualification-data" + + pushed=0 + for attempt in 1 2 3 4 5; do + rm -rf data + found=0 + git ls-remote --exit-code --heads "$REPO_URL" "$BRANCH" >/dev/null || found=$? + if [ "$found" -eq 0 ]; then + if ! git clone --quiet --depth 1 --branch "$BRANCH" "$REPO_URL" data; then + echo "Clone failed (attempt $attempt); retrying"; sleep $((attempt * 3)); continue + fi + elif [ "$found" -eq 2 ]; then + echo "$BRANCH does not exist yet; creating it" + git init --quiet data + git -C data checkout --quiet --orphan "$BRANCH" + git -C data remote add origin "$REPO_URL" + else + echo "Could not reach the repository (attempt $attempt); retrying"; sleep $((attempt * 3)); continue + fi + + if [ "$UNCHANGED" = "true" ]; then + python3 lemonade-ci/.github/qualify-rocm/publish_qualification.py --mark-unchanged \ + --data-dir data/qualification --tag "$TAG" --upstream-sha "$UPSTREAM_SHA" + else + python3 lemonade-ci/.github/qualify-rocm/publish_qualification.py \ + --records-dir records \ + --data-dir data/qualification \ + --operating-systems "$ROCM_OPERATING_SYSTEMS" \ + --rocm-versions "$ROCM_VERSIONS" \ + --tag "$TAG" \ + --upstream-sha "$UPSTREAM_SHA" \ + --jobs-file jobs.jsonl \ + --published-artifacts "$PUBLISHED_ROCM" \ + --final-checked "$FINAL_CHECKED" + fi + cp lemonade-ci/.github/qualify-rocm/FEED.md data/qualification/SCHEMA.md + + git -C data add -A + if git -C data diff --cached --quiet; then + echo "Nothing changed; the feed already holds this run." + pushed=1; break + fi + if [ "$UNCHANGED" = "true" ]; then message="unchanged"; else message="run"; fi + git -C data commit --quiet -m "qualification: ${message} ${{ github.run_id }} (${TAG})" + if git -C data push --quiet origin "$BRANCH"; then + pushed=1; break + fi + echo "Push rejected (attempt $attempt), most likely because another run published first; retrying" + sleep $((attempt * 3)) + done + + [ "$pushed" = 1 ] || { echo "::error::Could not publish to $BRANCH after 5 attempts."; exit 1; } + echo "Feed: https://raw.githubusercontent.com/${{ github.repository }}/${BRANCH}/qualification/index.json" diff --git a/README.md b/README.md index 91423d895a..571a347417 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,119 @@ # Lemonade Stable diffusion fork -This repo is a "Github actions only" fork of stable diffusion that is built with more ROCm releases than upstream stable diffusion supports. +This repo is a "Github actions only" fork of [stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp) that is built with more ROCm releases than upstream stable diffusion supports. -These are built for the purpose of lemonade use, but they can be utilized by any project. Releases just need to be used with matching AMD ROCm SDK releases. +These are built for the purpose of [Lemonade](https://github.com/lemonade-sdk/lemonade) use, but they can be utilized by any project. Releases just need to be used with matching AMD ROCm releases — see [Using the ROCm builds](#using-the-rocm-builds). # Cadence -The builds are triggered nightly, or can optionally be triggered on demand as well. +The builds are triggered nightly, or can optionally be triggered on demand as well. A nightly publishes when upstream stable-diffusion.cpp or this repository changed, or to fill in a build an earlier run could not publish. +Every ROCm build is checked before it is published — statically, and by generating an image on an AMD Strix Halo (gfx1151) GPU on Windows and Linux. A ROCm version is published only when both its Windows and Linux builds pass. See [.github/qualify-rocm](.github/qualify-rocm/README.md). + +# Using the ROCm builds + +[Lemonade](https://github.com/lemonade-sdk/lemonade) does all of this for you. + +If you instead want to use a build on its own, follow these steps: + +### 1. Find your GPU's gfx target + +Every AMD GPU has a gfx target, for example: + +| GPU | gfx target | +|---|---| +| Ryzen AI Max (Radeon 8060S, Strix Halo) | `gfx1151` | +| Ryzen AI 300 (Radeon 890M) | `gfx1150` | +| Ryzen 7040/8040 (Radeon 780M) | `gfx1103` | +| Radeon RX 7900 XT/XTX | `gfx1100` | +| Radeon RX 9070/9070 XT | `gfx1201` | + +`sd-server` also prints it when it starts, in a line like `Device 0: AMD Radeon(TM) 8060S Graphics, gfx1151 (0x1151)`. + +The builds include code for gfx1010, gfx1011, gfx1012, gfx1030–gfx1036, gfx1100–gfx1103, gfx1150–gfx1153, gfx1200 and gfx1201, and on Linux also gfx908, gfx90a, gfx942 and gfx950. + +### 2. Download a build + +From the [latest release](https://github.com/lemonade-sdk/stable-diffusion.cpp/releases/latest), pick one ROCm version and download your OS's zip: + +- Windows: `sd-master--bin-win-rocm--x64.zip` +- Linux: `sd-master--bin-Linux-Ubuntu-24.04-x86_64-rocm-.zip` (Ubuntu 24.04 or newer) + +You also need a model, for example [SD-Turbo](https://huggingface.co/Green-Sky/SD-Turbo-GGUF/resolve/main/sd_turbo-f16-q8_0.gguf) (~2 GB). + +### 3. Install the matching ROCm runtime + +The ROCm zips (in the [Releases](https://github.com/lemonade-sdk/stable-diffusion.cpp/releases) page of this repo) contain stable-diffusion.cpp (`sd-server`, `sd-cli` and their libraries) but not ROCm's math libraries (hipBLAS, hipBLASLt, rocBLAS). Those come from AMD's ROCm runtime, installed with `pip`, and it must be the **same ROCm version** as the zip. + +Use Python 3.12 or 3.13, and replace `10.2.0` with the zip's ROCm version and `gfx1151` with your gfx target. + +Windows (PowerShell): + +```powershell +python -m venv rocm-10.2 +.\rocm-10.2\Scripts\python.exe -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ "rocm[libraries,device-gfx1151]==10.2.0" +``` + +Linux: + +```bash +python3 -m venv rocm-10.2 +./rocm-10.2/bin/python -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ "rocm[libraries,device-gfx1151]==10.2.0" +``` + +### 4. Unpack and start sd-server + +Windows (PowerShell, from the folder holding `rocm-10.2`): + +```powershell +Expand-Archive sd-master--bin-win-rocm-10.2.0-x64.zip -DestinationPath sd +$env:PATH = "$PWD\rocm-10.2\Lib\site-packages\_rocm_sdk_libraries\bin;$env:PATH" +.\sd\sd-server.exe -m sd_turbo-f16-q8_0.gguf --listen-port 8080 +``` + +> Keep the `amdhip64_7.dll`, `amd_comgr.dll` and `rocm_kpack.dll` that came in the zip next to `sd-server.exe`: they stop Windows from loading the older copy the AMD display driver installs. + +Linux (from the folder holding `rocm-10.2`): + +```bash +unzip sd-master--bin-Linux-Ubuntu-24.04-x86_64-rocm-10.2.0.zip +SITE=$(./rocm-10.2/bin/python -c "import sysconfig; print(sysconfig.get_paths()['purelib'])") +export LD_LIBRARY_PATH="$SITE/_rocm_sdk_core/lib:$SITE/_rocm_sdk_libraries/lib:$LD_LIBRARY_PATH" +./build/bin/sd-server -m sd_turbo-f16-q8_0.gguf --listen-port 8080 +``` + +### 5. Generate an image + +Open in a browser, or call the OpenAI-style API. Generation settings such as the seed and step count go inside the prompt, in ``; these are the ones SD-Turbo is made for. + +Windows (PowerShell): + +```powershell +$body = '{"prompt":"a glass of lemonade on a wooden table{\"seed\":42,\"sample_params\":{\"sample_steps\":4,\"guidance\":{\"txt_cfg\":1.0}}}","size":"512x512","response_format":"b64_json"}' +$r = Invoke-RestMethod -Uri http://127.0.0.1:8080/v1/images/generations -Method Post -ContentType "application/json" -Body $body +[IO.File]::WriteAllBytes("$PWD\image.png", [Convert]::FromBase64String($r.data[0].b64_json)) +``` + +Linux: + +```bash +curl -s http://127.0.0.1:8080/v1/images/generations -H "Content-Type: application/json" \ + -d '{"prompt":"a glass of lemonade on a wooden table{\"seed\":42,\"sample_params\":{\"sample_steps\":4,\"guidance\":{\"txt_cfg\":1.0}}}","size":"512x512","response_format":"b64_json"}' \ + | python3 -c "import base64, json, sys; open('image.png', 'wb').write(base64.b64decode(json.load(sys.stdin)['data'][0]['b64_json']))" +``` + +### Is it using the GPU? + +A build that cannot use the GPU still works — on the CPU, several times slower, without an error. + +Start `sd-server` with `-v` and check its output for `Device 0: … gfx…` and lines ending in `(VRAM) on ROCm0`. + +`failed to initialize ROCm: no ROCm-capable device is detected` or `… RAM) on CPU` means it is running on the CPU. + +### Troubleshooting + +| Symptom | Cause | +|---|---| +| Windows: `sd-server.exe` exits at once with code `-1073741515` (`0xC0000135`) | The ROCm runtime folder is not on `PATH` (step 4) | +| Windows: exits with code `-1073741819` (`0xC0000005`) | The `amdhip64_7.dll` / `amd_comgr.dll` from the zip are missing or replaced | +| Linux: `error while loading shared libraries: libhipblas.so.3: cannot open shared object file` | `LD_LIBRARY_PATH` is not set (step 4) |