Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e58868e6f | ||
|
|
c1cf2e917e | ||
|
|
2f1dcebf0c | ||
|
|
f4c26754db | ||
|
|
55396d6aae | ||
|
|
da89e18ee4 | ||
|
|
a0ae5b6321 | ||
|
|
36a50ff15c | ||
|
|
84c9722143 | ||
|
|
f65f55ce68 | ||
|
|
571e39a928 | ||
|
|
bd10709053 | ||
|
|
8a5e2443ea | ||
|
|
ef317d0f41 | ||
|
|
e74478e18f | ||
|
|
7bd2140c5d | ||
|
|
9d5ed005ac | ||
|
|
0b50a7c0be | ||
|
|
652659a502 | ||
|
|
ca0ad47841 | ||
|
|
4e38406e0b | ||
|
|
df71595ae7 | ||
|
|
c82a5b84c4 | ||
|
|
9324611b1a |
@@ -1,20 +1,23 @@
|
||||
---
|
||||
name: reseed-performance-baseline
|
||||
description: Re-seed the HF performance-tracking baseline for an intentional runtime, dependency, or environment-caused benchmark shift using one or more reviewed normalized performance JSONs. Use when performance CI fails because metrics such as latency, throughput, component time, or peak memory changed for an accepted reason and the rolling median baseline in FastVideo/performance-tracking must be advanced from a consistent batch of reviewed source results. The workflow backs up existing history under /tmp, validates all source JSONs for the same (model_id, gpu_type), rejects internally inconsistent source batches, uploads one success=true reseed record per accepted source JSON, and offers to clean local temp state after a successful upload.
|
||||
description: Re-seed the HF performance-tracking baseline for an intentional runtime, dependency, environment-caused benchmark shift, or reviewed v2 calibration using one or more reviewed normalized performance JSONs. Use when performance CI fails because metrics such as latency, throughput, component time, or peak memory changed for an accepted reason and the rolling median baseline in FastVideo/performance-tracking must be advanced, or when a new v2 exact comparable identity needs its first approved baseline. The workflow backs up existing history under /tmp, validates all source JSONs for the same legacy (model_id, gpu_type) target or the same v2 exact identity, rejects internally inconsistent source batches, uploads one success=true baseline record per accepted source JSON, and offers to clean local temp state after a successful upload.
|
||||
---
|
||||
|
||||
# Re-seed Performance Baseline
|
||||
|
||||
## Purpose
|
||||
|
||||
Replace or advance the rolling performance baseline for a single
|
||||
`(model_id, gpu_type)` pair in the HF dataset
|
||||
`FastVideo/performance-tracking`.
|
||||
Replace or advance the rolling performance baseline in the HF dataset
|
||||
`FastVideo/performance-tracking`. Legacy targets are scoped by
|
||||
`(model_id, gpu_type)`. V2 targets are scoped by exact comparable identity:
|
||||
`workload_id`, `variant_id`, `benchmark_version`, `hardware_profile_id`,
|
||||
`software_profile_id`, and `recipe_fingerprint`.
|
||||
|
||||
Performance comparison uses the median of up to the last 5 successful records
|
||||
for the same model and GPU. Failed records are useful audit history, but they
|
||||
do not move the future baseline because `compare_baseline.py` loads records
|
||||
with `successful_only=True`.
|
||||
Performance comparison uses the median of up to the last 5 successful,
|
||||
baseline-eligible records for the same target. Failed or calibration-only
|
||||
records are useful audit history, but they do not move the future baseline
|
||||
because `compare_baseline.py` loads records with `successful_only=True` and
|
||||
`baseline_eligible_only=True`.
|
||||
|
||||
This skill now reseeds from a reviewed batch of one or more source performance
|
||||
JSONs. It uploads one new `success=true` record per accepted source JSON; it
|
||||
@@ -22,11 +25,13 @@ does not blindly replicate one measurement into 3 or 5 records. The effective
|
||||
reseed size is therefore dynamic and equals the number of provided, validated,
|
||||
internally consistent source JSONs.
|
||||
|
||||
If the operator provides fewer than 3 records, call out that the last-5 rolling
|
||||
median may not move immediately. If the operator provides 3 consistent shifted
|
||||
records, the rolling median usually moves immediately. If the operator provides
|
||||
5 consistent shifted records, the last-5 window is effectively reset to the new
|
||||
runtime profile.
|
||||
For baseline shifts with existing history, if the operator provides fewer than
|
||||
3 records, call out that the last-5 rolling median may not move immediately. If
|
||||
the operator provides 3 consistent shifted records, the rolling median usually
|
||||
moves immediately. If the operator provides 5 consistent shifted records, the
|
||||
last-5 window is effectively reset to the new runtime profile. For the first
|
||||
approved v2 baseline of a new exact identity, one reviewed calibration seed is
|
||||
enough for the next comparable run to leave `CALIBRATION_NEEDED`.
|
||||
|
||||
These records are intentional operator-approved baseline resets, not ordinary
|
||||
independent main-branch persistence. Mark them clearly with provenance fields
|
||||
@@ -66,8 +71,8 @@ approval, then upload reviewed accepted baseline records.
|
||||
|
||||
| Parameter | Required | Description |
|
||||
|-----------|----------|-------------|
|
||||
| `model_id` | Yes | Benchmark id, e.g. `wan-t2v-1.3b-2gpu`. This maps to the HF subdirectory after `sanitize(model_id)`. |
|
||||
| `gpu_type` | Yes | Exact GPU device string from the performance record, e.g. the L40S device name emitted by CI. Baselines are GPU-specific. |
|
||||
| `model_id` | Legacy required; v2 inferred | Benchmark id, e.g. `wan-t2v-1.3b-2gpu`. This maps to the HF subdirectory after `sanitize(model_id)`. For v2 records, use the `model_id` from each source artifact only as the upload directory; comparison is by exact identity. |
|
||||
| `gpu_type` | Legacy required; v2 inferred | Exact GPU device string from the performance record, e.g. the L40S device name emitted by CI. V2 hardware matching uses `hardware_profile_id`; preserve `gpu_type` as display metadata. |
|
||||
| `source_results` | Yes | One or more local paths or Buildkite artifact URLs for accepted shifted performance JSONs. Prefer normalized `normalized_perf_*.json` artifacts emitted by `compare_baseline.py`. Accept `source_result` as an alias only for a single JSON. |
|
||||
| `max_intra_batch_regression` | No | Maximum allowed regression of any source JSON against the source batch median. Default: `0.05` (5%). |
|
||||
| `intent_rationale` | Yes | One-line explanation for why the baseline shift is legitimate. This is written into provenance and should be reused in the PR. |
|
||||
@@ -78,10 +83,14 @@ Hardcoded defaults:
|
||||
supported by the code, but use the default unless the user explicitly asks).
|
||||
- Local sync root: `/tmp/perf-tracking` (`PERFORMANCE_TRACKING_ROOT` override
|
||||
is supported).
|
||||
- Prepared-record staging root: `/tmp/performance_reseed_prepared`
|
||||
(`PERFORMANCE_RESEED_STAGING_ROOT` override is supported). Keep it separate
|
||||
and non-nested from the sync root.
|
||||
- Backup root: `/tmp/performance_reseed_backup`.
|
||||
- Download scratch root for source artifact URLs: `/tmp/performance_reseed_source`.
|
||||
- Baseline window: last 5 `success=true` records for the same
|
||||
`(model_id, gpu_type)`.
|
||||
- Baseline window: last 5 `success=true`, `baseline_eligible=true` records
|
||||
for the same legacy `(model_id, gpu_type)` target or the same v2 exact
|
||||
comparable identity.
|
||||
- Reseed count: dynamic. Upload exactly one accepted seed record per validated
|
||||
source JSON.
|
||||
|
||||
@@ -115,12 +124,24 @@ with open(source_result, encoding="utf-8") as f:
|
||||
record = json.load(f)
|
||||
```
|
||||
|
||||
Stop if any normalized record's `model_id` or `gpu_type` does not match the
|
||||
requested `model_id` and `gpu_type`.
|
||||
Classify the source batch before continuing:
|
||||
|
||||
- **Legacy source records** have no v2 exact identity fields. Stop if any
|
||||
normalized record's `model_id` or `gpu_type` does not match the requested
|
||||
`model_id` and `gpu_type`.
|
||||
- **V2 source records** have exact identity fields. Stop unless every source
|
||||
record has all six comparable identity fields and they are identical across
|
||||
the batch: `workload_id`, `variant_id`, `benchmark_version`,
|
||||
`hardware_profile_id`, `software_profile_id`, and `recipe_fingerprint`.
|
||||
Do not fall back to legacy `(model_id, gpu_type)` matching for v2 records.
|
||||
|
||||
The source records may have `success: false` when they came from failed
|
||||
rolling baseline comparisons. That is expected; only the reviewed reseed
|
||||
records become new `success: true` baseline records after explicit approval.
|
||||
For a first v2 baseline seed, the source records must instead be successful
|
||||
scheduled-main full-suite `CALIBRATION_NEEDED` normalized artifacts. Reject PR,
|
||||
local, direct-run, non-main-branch, or non-full-suite calibration artifacts as
|
||||
seed sources.
|
||||
|
||||
Sort validated source records by their original `timestamp` ascending before
|
||||
preparing the seed records. If a source timestamp is missing or unparsable,
|
||||
@@ -194,7 +215,7 @@ export HF_REPO_ID="${HF_REPO_ID:-FastVideo/performance-tracking}"
|
||||
python -c 'from fastvideo.performance.hf_store import sync_from_hf; import os; sync_from_hf(os.environ["PERFORMANCE_TRACKING_ROOT"], strict=True)'
|
||||
```
|
||||
|
||||
Then back up only the sanitized model directory under `/tmp`:
|
||||
For legacy records, back up the sanitized model directory under `/tmp`:
|
||||
|
||||
```bash
|
||||
SHORT_COMMIT=$(git rev-parse --short=12 HEAD)
|
||||
@@ -209,6 +230,16 @@ mkdir -p "$BACKUP_DIR"
|
||||
cp -R "${PERFORMANCE_TRACKING_ROOT}/${MODEL_SAFE}" "$BACKUP_DIR/" 2>/dev/null || true
|
||||
```
|
||||
|
||||
For v2 records, back up the full local tracking root after sync. Exact identity
|
||||
lookup scans across model directories, so a benchmark rename may have relevant
|
||||
history outside the current source artifact's `model_id` directory:
|
||||
|
||||
```bash
|
||||
BACKUP_DIR="/tmp/performance_reseed_backup/${TIMESTAMP}_${SHORT_COMMIT}_v2_exact_identity"
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
cp -R "${PERFORMANCE_TRACKING_ROOT}" "$BACKUP_DIR/tracking-root"
|
||||
```
|
||||
|
||||
Write provenance next to the backup:
|
||||
|
||||
```bash
|
||||
@@ -231,7 +262,9 @@ first baseline seed. Continue, but report that baseline history was empty.
|
||||
|
||||
### 3. Compute old baseline and candidate shift
|
||||
|
||||
Load the last 5 successful records for the target:
|
||||
Load the last 5 successful baseline records for the target.
|
||||
|
||||
For legacy targets:
|
||||
|
||||
```python
|
||||
from fastvideo.performance.hf_store import load_records_for_model
|
||||
@@ -242,6 +275,28 @@ records = load_records_for_model(
|
||||
"<gpu_type>",
|
||||
last_n=5,
|
||||
successful_only=True,
|
||||
baseline_eligible_only=True,
|
||||
)
|
||||
```
|
||||
|
||||
For v2 exact-identity targets:
|
||||
|
||||
```python
|
||||
from fastvideo.performance.hf_store import load_records_for_identity
|
||||
|
||||
records = load_records_for_identity(
|
||||
"/tmp/perf-tracking",
|
||||
{
|
||||
"workload_id": "<workload_id>",
|
||||
"variant_id": "<variant_id>",
|
||||
"benchmark_version": "<benchmark_version>",
|
||||
"hardware_profile_id": "<hardware_profile_id>",
|
||||
"software_profile_id": "<software_profile_id>",
|
||||
"recipe_fingerprint": "<recipe_fingerprint>",
|
||||
},
|
||||
last_n=5,
|
||||
successful_only=True,
|
||||
baseline_eligible_only=True,
|
||||
)
|
||||
```
|
||||
|
||||
@@ -257,7 +312,8 @@ medians after appending the proposed seed records, and source batch spread for:
|
||||
|
||||
Also print how many successful old records exist. Make clear:
|
||||
|
||||
- 1 seed record usually does not move a last-5 median by itself.
|
||||
- 1 seed record usually does not move an existing last-5 median by itself, but
|
||||
it is enough to establish the first v2 baseline for a new exact identity.
|
||||
- 3 consistent seed records usually move the last-5 median immediately.
|
||||
- 5 consistent seed records effectively reset the last-5 window.
|
||||
- The records are intentional approved baseline resets and must be labeled
|
||||
@@ -267,10 +323,10 @@ Also print how many successful old records exist. Make clear:
|
||||
|
||||
Require an explicit confirmation phrase before preparing the upload:
|
||||
|
||||
> About to RE-SEED performance baseline for `<model_id>` on `<gpu_type>`.
|
||||
> About to RE-SEED performance baseline for `<target description>`.
|
||||
> This will upload `<N>` new `success=true` records to
|
||||
> `FastVideo/performance-tracking/<sanitize(model_id)>/`, one per accepted
|
||||
> source JSON.
|
||||
> `FastVideo/performance-tracking/<sanitize(model_id)>/` or the source
|
||||
> artifact's v2 model directory, one per accepted source JSON.
|
||||
>
|
||||
> Reason: `<intent_rationale>`
|
||||
> Source results: `<source_results>`
|
||||
@@ -288,25 +344,63 @@ Do not continue unless the user types exactly `confirm performance reseed`.
|
||||
|
||||
### 5. Create the accepted seed records
|
||||
|
||||
Create one seed record from each normalized source result. Do not copy the
|
||||
Create one seed record from each normalized source result.
|
||||
|
||||
For first v2 baseline seeds, use the scoped utility. It validates exact
|
||||
identity, requires successful scheduled-main full-suite `CALIBRATION_NEEDED`
|
||||
source artifacts, preserves the normalized v2 identity and metadata fields,
|
||||
and writes seed records with `success=true`, `baseline_eligible=true`, and
|
||||
`comparison_status=PASS`:
|
||||
|
||||
```bash
|
||||
python fastvideo/tests/performance/seed_baseline.py \
|
||||
--source-result <normalized_perf_1.json> \
|
||||
--source-result <normalized_perf_2.json> \
|
||||
--intent-rationale "<intent_rationale>" \
|
||||
--max-intra-batch-regression 0.05 \
|
||||
--tracking-root "${PERFORMANCE_TRACKING_ROOT}" \
|
||||
--staging-root "${PERFORMANCE_RESEED_STAGING_ROOT:-/tmp/performance_reseed_prepared}"
|
||||
```
|
||||
|
||||
The utility is prepare-only and intentionally has no upload option. Upload the
|
||||
scoped records only after the separate confirmation in step 6.
|
||||
|
||||
The utility validates against an isolated fresh HF snapshot and leaves
|
||||
`PERFORMANCE_TRACKING_ROOT` untouched; that argument only proves the staging
|
||||
root is separate from the operator's tracking mirror. Before writing, it stops
|
||||
if the exact identity already has a successful baseline-eligible record or if
|
||||
the workload/variant/version already trusts another recipe. It atomically
|
||||
reserves the exact identity and writes a digest-protected upload manifest bound
|
||||
to the current HF endpoint, repository id, and repository type. Keep the
|
||||
prepared records, manifest, source files, and reservation unchanged until the
|
||||
operation is uploaded or explicitly cleaned up.
|
||||
|
||||
If the prepared seed records look correct, upload only those scoped records in
|
||||
step 7. Do not rerun the utility with a different source list after approval.
|
||||
|
||||
For legacy reseeds or accepted v2 baseline shifts from regression artifacts,
|
||||
create one seed record from each normalized source result. Do not copy the
|
||||
source JSON wholesale.
|
||||
|
||||
Infer the baseline field allowlist from all existing HF records for the target
|
||||
`(model_id, gpu_type)` after syncing, including both `success=true` and
|
||||
`success=false` records. Use the union of non-provenance keys present in those
|
||||
target records, preserving only fields that also exist in the normalized
|
||||
source record or are explicitly set by the reseed workflow. Always include
|
||||
`model_id`, `timestamp`, and `success` because the upload path and baseline
|
||||
loader depend on them. Always set `timestamp` to a fresh reseed timestamp and
|
||||
`success` to `true`. Do not include unrelated source-only fields that are
|
||||
absent from existing HF records.
|
||||
after syncing, including both `success=true` and `success=false` records. For
|
||||
legacy targets the target is `(model_id, gpu_type)`. For v2 baseline-shift
|
||||
reseeds the target is the exact comparable identity. Use the union of
|
||||
non-provenance keys present in those target records, preserving only fields
|
||||
that also exist in the normalized source record or are explicitly set by the
|
||||
reseed workflow. Always include `model_id`, `timestamp`, `success`,
|
||||
`baseline_eligible`, and `comparison_status` because the upload path and
|
||||
baseline loader depend on them. Always set `timestamp` to a fresh reseed
|
||||
timestamp, `success` to `true`, `baseline_eligible` to `true`, and
|
||||
`comparison_status` to `PASS`. Do not include unrelated source-only fields
|
||||
that are absent from existing HF records.
|
||||
|
||||
Exclude existing provenance or operator metadata from the inferred baseline
|
||||
field allowlist. At minimum, exclude keys prefixed with `baseline_reseed` and
|
||||
any fields known to be local-only audit metadata.
|
||||
|
||||
If there are no previous HF records for the target model/GPU, fall back to this
|
||||
default baseline field list:
|
||||
If there are no previous HF records for the target, fall back to this default
|
||||
baseline field list:
|
||||
|
||||
- `model_id`
|
||||
- `timestamp`
|
||||
@@ -319,6 +413,22 @@ default baseline field list:
|
||||
- `dit_time_s`
|
||||
- `vae_decode_time_s`
|
||||
- `success`
|
||||
- `baseline_eligible`
|
||||
- `comparison_status`
|
||||
|
||||
For v2 baseline-shift reseeds with no previous HF records for the exact
|
||||
identity, also preserve:
|
||||
|
||||
- `workload_id`
|
||||
- `variant_id`
|
||||
- `benchmark_version`
|
||||
- `recipe_fingerprint`
|
||||
- `hardware_profile_id`
|
||||
- `software_profile_id`
|
||||
- `recipe`
|
||||
- `hardware_profile`
|
||||
- `software_profile`
|
||||
- `software_comparison_profile`
|
||||
|
||||
Do not upload extra fields from the source artifact.
|
||||
|
||||
@@ -334,6 +444,22 @@ Optional provenance fields are allowed and useful:
|
||||
- `baseline_reseed_operator`
|
||||
- `baseline_reseed_max_intra_batch_regression`
|
||||
|
||||
The v2 calibration seed utility writes analogous first-seed provenance:
|
||||
|
||||
- `baseline_seed: true`
|
||||
- `baseline_seed_reason`
|
||||
- `baseline_seed_source_result`
|
||||
- `baseline_seed_source_status`
|
||||
- `baseline_seed_source_timestamp`
|
||||
- `baseline_seed_source_success`
|
||||
- `baseline_seed_source_run_source`
|
||||
- `baseline_seed_source_branch`
|
||||
- `baseline_seed_source_test_scope`
|
||||
- `baseline_seed_source_pr_number`
|
||||
- `baseline_seed_batch_size`
|
||||
- `baseline_seed_batch_index`
|
||||
- `baseline_seed_operator`
|
||||
|
||||
Use a fresh reseed timestamp for each seed record, not the original source
|
||||
result timestamp. This is required because
|
||||
`load_records_for_model(..., last_n=5)` keeps the last records after loading
|
||||
@@ -356,7 +482,8 @@ Prefer uploading new accepted seed records so failed history remains visible.
|
||||
Print:
|
||||
|
||||
- Backup directory path under `/tmp`.
|
||||
- Prepared local record paths under `PERFORMANCE_TRACKING_ROOT`.
|
||||
- Prepared local record paths under `PERFORMANCE_RESEED_STAGING_ROOT`.
|
||||
- Prepared upload-manifest path under the identity reservation.
|
||||
- HF paths that will receive the new records.
|
||||
- Old rolling medians.
|
||||
- Source batch medians, source batch spread, reseed count, and candidate
|
||||
@@ -368,22 +495,36 @@ prepared records plus backup on disk.
|
||||
|
||||
### 7. Upload only the scoped records
|
||||
|
||||
Use the shared storage helper so the path and repo type match CI:
|
||||
For a first v2 calibration seed, use the manifest uploader after the user
|
||||
replies exactly `upload`:
|
||||
|
||||
```python
|
||||
from fastvideo.performance.hf_store import upload_record
|
||||
|
||||
upload_record("<local_record_path>", record, strict=True)
|
||||
```bash
|
||||
python -c 'from fastvideo.tests.performance.seed_baseline import upload_prepared_seed_manifest; print(upload_prepared_seed_manifest("<prepared_manifest>"))'
|
||||
```
|
||||
|
||||
Run it once per prepared record. Each upload goes to:
|
||||
The uploader verifies the source and prepared-record digests, pins and scans
|
||||
the current HF revision, rechecks exact-identity and recipe-cohort conflicts,
|
||||
and writes the entire batch in one commit whose `parent_commit` must still be
|
||||
current. A concurrent Hub update makes the commit fail. Do not retry
|
||||
automatically: preserve staging, refresh/review remote state, and request a new
|
||||
explicit `upload` after the conflict is understood. Each record goes to:
|
||||
|
||||
```text
|
||||
FastVideo/performance-tracking/<sanitize(model_id)>/<record_filename>.json
|
||||
```
|
||||
|
||||
Never bulk upload the whole tracking root. Never modify another model's
|
||||
directory in the same operation.
|
||||
Never call `upload_record()` once per first-seed record: that can partially
|
||||
land the batch and has no compare-and-swap guard.
|
||||
|
||||
For a legacy reseed or an accepted v2 baseline shift, the first-seed manifest
|
||||
validator does not apply because an eligible baseline already exists. Upload
|
||||
only the individually reviewed records prepared in step 5 with the shared
|
||||
`upload_record(local_path, record, strict=True)` helper. Stop on the first
|
||||
failure and report exactly which records reached HF; do not silently rerun or
|
||||
replicate the remainder.
|
||||
|
||||
Never bulk upload the tracking or staging root, and never modify another
|
||||
model's directory in the same operation.
|
||||
|
||||
### 8. Report outcome and offer cleanup
|
||||
|
||||
@@ -405,9 +546,14 @@ distinguish an accepted baseline shift from a hidden regression.
|
||||
After the upload is verified, ask whether the user wants to clear temporary
|
||||
local state. Explain what each directory is for:
|
||||
|
||||
- `PERFORMANCE_TRACKING_ROOT`, usually `/tmp/perf-tracking`: local synced
|
||||
mirror of `FastVideo/performance-tracking` plus the prepared local seed
|
||||
records used for scoped upload.
|
||||
- `PERFORMANCE_TRACKING_ROOT`, usually `/tmp/perf-tracking`: read-only local
|
||||
synced mirror used for operator review and reporting. First-v2 preparation
|
||||
independently proves remote state from a fresh temporary HF snapshot.
|
||||
- `PERFORMANCE_RESEED_STAGING_ROOT`, usually
|
||||
`/tmp/performance_reseed_prepared`: prepared local seed records used for the
|
||||
scoped upload, plus the identity reservation and digest manifest. Keeping
|
||||
this separate prevents aborted preparations from appearing in later
|
||||
baseline reads.
|
||||
- `/tmp/performance_reseed_backup/<...>`: local backup of the target model's
|
||||
pre-reseed HF history plus `PROVENANCE.txt`, kept so a bad reseed can be
|
||||
audited or corrected.
|
||||
@@ -417,14 +563,18 @@ local state. Explain what each directory is for:
|
||||
Ask:
|
||||
|
||||
> Reseed succeeded. Do you want me to delete the local temp tracking mirror,
|
||||
> source downloads, and reseed backup under `/tmp`? These files are local
|
||||
> safety/audit artifacts only; HF already has the uploaded records.
|
||||
> this reseed's prepared staging records, source downloads, and reseed backup
|
||||
> under `/tmp`? These files are local safety/audit artifacts only; HF already
|
||||
> has the uploaded records.
|
||||
>
|
||||
> Reply `cleanup reseed temp` to delete them, anything else to keep them.
|
||||
|
||||
Do not delete anything unless the user replies exactly
|
||||
`cleanup reseed temp`. If cleanup is requested, remove only the specific
|
||||
directories created for this reseed. Never remove unrelated `/tmp` contents.
|
||||
directories and prepared record paths created for this reseed. Do not remove
|
||||
the shared staging root when it contains other records. Remove this operation's
|
||||
identity reservation only with its prepared records and manifest, and never
|
||||
remove unrelated `/tmp` contents.
|
||||
|
||||
## Failure modes and handling
|
||||
|
||||
@@ -436,19 +586,34 @@ directories created for this reseed. Never remove unrelated `/tmp` contents.
|
||||
against the source batch median by more than `max_intra_batch_regression`.
|
||||
Ask for cleaner sources or a reviewed explanation before continuing.
|
||||
- **Too few source records to move the median.** Continue only after making
|
||||
clear that one or two records may not immediately move the last-5 median.
|
||||
clear that one or two records may not immediately move an existing last-5
|
||||
median. This warning does not block a first v2 calibration seed for an exact
|
||||
identity with no eligible baseline yet.
|
||||
- **The source results are noisy or suspicious.** Stop. Reseeding amplifies
|
||||
those measurements into the baseline, so they must be reviewed first.
|
||||
- **HF sync fails.** Stop for destructive reseeds. A stale or empty sync can
|
||||
make the old baseline look missing.
|
||||
- **The exact v2 identity already has an eligible baseline.** Stop. The
|
||||
`CALIBRATION_NEEDED` artifact is stale; use the reviewed baseline-shift path
|
||||
instead of the first-seed utility.
|
||||
- **The workload/variant/version trusts another recipe.** Stop. The source is
|
||||
stale relative to the current recipe cohort and must not bypass
|
||||
`RECIPE_MISMATCH` by creating a second trusted recipe.
|
||||
- **The staging root already has a prepared seed for the exact identity.**
|
||||
Stop and reuse, upload, or explicitly clean that preparation. Do not prepare
|
||||
another copy of the same measurement.
|
||||
- **The conditional Hub commit loses its parent race.** Stop without retrying.
|
||||
Keep the preparation, refresh and review the new remote state, then request
|
||||
a new explicit `upload` only if the seed is still valid.
|
||||
- **Candidate still violates fixed thresholds.** Report that this skill only
|
||||
handles the rolling HF baseline; update benchmark JSON thresholds in code
|
||||
review if maintainers accept the new absolute limit.
|
||||
- **The user aborts at either confirmation.** Leave the backup and prepared
|
||||
records on disk. Nothing should be uploaded.
|
||||
- **The user declines cleanup.** Keep `/tmp/perf-tracking`, the source
|
||||
download directory if any, and `/tmp/performance_reseed_backup/<...>` in
|
||||
place for audit/debugging.
|
||||
- **The user declines cleanup.** Keep `/tmp/perf-tracking`, the prepared seed
|
||||
records under `/tmp/performance_reseed_prepared`, the source download
|
||||
directory if any, and `/tmp/performance_reseed_backup/<...>` in place for
|
||||
audit/debugging.
|
||||
- **A bad seed was uploaded.** Use the backup and HF history to identify the
|
||||
uploaded file, then remove or supersede it with an explicitly reviewed
|
||||
corrective record. Do not silently rewrite unrelated history.
|
||||
@@ -459,8 +624,9 @@ directories created for this reseed. Never remove unrelated `/tmp` contents.
|
||||
intentional baseline replacement.
|
||||
- `fastvideo/tests/performance/compare_baseline.py` — normalization, rolling
|
||||
median comparison, and persistence rules.
|
||||
- `fastvideo/performance/hf_store.py` — HF sync, record loading,
|
||||
`sanitize()`, and `upload_record()`.
|
||||
- `fastvideo/performance/hf_store.py` — HF sync and record loading helpers.
|
||||
- `fastvideo/tests/performance/seed_baseline.py` — first-seed preparation,
|
||||
staging reservation, manifest validation, and conditional batch upload.
|
||||
- `fastvideo/tests/performance/test_inference_performance.py` — source result
|
||||
JSON schema.
|
||||
- `.buildkite/performance-benchmarks/tests/*.json` — fixed absolute benchmark
|
||||
@@ -473,3 +639,4 @@ directories created for this reseed. Never remove unrelated `/tmp` contents.
|
||||
| 2026-05-03 | Initial version. Sister workflow to `reseed-ssim-references`, scoped to one performance `(model_id, gpu_type)` baseline seed with backup, confirmation, provenance, and `success=true` upload. |
|
||||
| 2026-05-03 | Previous policy: replicate one approved shifted source result into 3 success records by default, or 5 only when explicitly requested. Add provenance marker for replicated-source reseeds. Superseded by the 2026-05-08 dynamic multi-source policy. |
|
||||
| 2026-05-08 | Replace fixed 3/5 replication with dynamic multi-source reseeding: upload one seed record per reviewed source JSON, validate intra-batch consistency, move backup/source scratch under `/tmp`, and ask whether to clean temp state after successful upload. |
|
||||
| 2026-07-13 | Keep first-v2-seed preparation outside the canonical mirror, reserve staging identities atomically, reject stale or replayed calibration seeds, and upload reviewed manifests with a single parent-guarded Hub commit. |
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"config_schema_version": 2,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2,
|
||||
"benchmark_version": 3,
|
||||
"description": "Wan2.1 T2V 1.3B inference performance",
|
||||
"model": {
|
||||
"model_path": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
||||
|
||||
@@ -104,6 +104,11 @@ and does not override stored status.
|
||||
- `GET /api/performance/trends?days=90&run_source=scheduled_main`
|
||||
- `GET /api/performance/records?days=90&run_source=local`
|
||||
|
||||
The current v1 grouping key is `(model_id, gpu_type)`. Baselines are computed
|
||||
from the latest five previous successful records in each group for dashboard
|
||||
context. CI gating uses only records marked `baseline_eligible=true`.
|
||||
V2 records use the same comparison cohort as CI: `workload_id`, `variant_id`,
|
||||
`benchmark_version`, `recipe_fingerprint`, `hardware_profile_id`, and
|
||||
`software_profile_id`. `model_id` and `gpu_type` remain display/filter
|
||||
metadata, so renaming either does not split history. Legacy records still group
|
||||
by `(model_id, gpu_type)`. Dashboard baselines use the latest five previous
|
||||
successful, baseline-eligible records in each group. Summary and trend filters
|
||||
match the latest display metadata after grouping, while the raw records endpoint
|
||||
continues to filter individual records.
|
||||
|
||||
@@ -12,7 +12,8 @@ It serves three audiences:
|
||||
* **Maintainers** — surfaces regressions in a Markdown summary on every
|
||||
performance build and a long-form Plotly dashboard.
|
||||
* **Local developers** — lets you run the same benchmark on your own machine,
|
||||
then compare against the historical baseline for the same model and GPU.
|
||||
then compare against the historical baseline for the same comparable
|
||||
identity.
|
||||
|
||||
## Quick start (local)
|
||||
|
||||
@@ -81,9 +82,9 @@ fastvideo/performance/
|
||||
The HF dataset (`FastVideo/performance-tracking` by default) holds one
|
||||
normalized JSON per run. For v2 records, the rolling baseline is the median of
|
||||
the last 5 successful, baseline-eligible records in the same comparison cohort:
|
||||
`model_id`, `gpu_type`, `workload_id`, `variant_id`, `benchmark_version`,
|
||||
`recipe_fingerprint`, `hardware_profile_id`, and `software_profile_id`. PR and
|
||||
local records are visible in the dashboard but are not baseline eligible.
|
||||
`workload_id`, `variant_id`, `benchmark_version`, `recipe_fingerprint`,
|
||||
`hardware_profile_id`, and `software_profile_id`. PR and local records are
|
||||
visible in the dashboard but are not baseline eligible.
|
||||
|
||||
## Planned Coverage
|
||||
|
||||
@@ -163,12 +164,11 @@ headroom and almost never need touching.
|
||||
|
||||
`compare_baseline.py` loads the last 5 successful, baseline-eligible records
|
||||
for the same comparison cohort from the HF dataset, computes the median for
|
||||
each available metric, and evaluates the current run with the metric's
|
||||
rolling regression policy. For v2 records, that cohort is `model_id`,
|
||||
`gpu_type`, `workload_id`, `variant_id`, `benchmark_version`,
|
||||
`recipe_fingerprint`, `hardware_profile_id`, and `software_profile_id`. For
|
||||
latency, memory, and component times, higher values are regressions. For
|
||||
throughput, lower values are regressions.
|
||||
each available metric, and evaluates the current run with the metric's rolling
|
||||
regression policy. For v2 records, that cohort is `workload_id`, `variant_id`,
|
||||
`benchmark_version`, `recipe_fingerprint`, `hardware_profile_id`, and
|
||||
`software_profile_id`. For latency, memory, and component times, higher values
|
||||
are regressions. For throughput, lower values are regressions.
|
||||
|
||||
A metric exceeds its rolling threshold when both of these are true:
|
||||
|
||||
@@ -188,10 +188,33 @@ slowly add up. Only scheduled-main successful records are baseline eligible.
|
||||
Local and pull-request runs can upload dashboard-visible records, but they do
|
||||
not update future gating baselines.
|
||||
|
||||
Comparator summaries and normalized artifacts include an explicit
|
||||
`comparison_status`:
|
||||
|
||||
| Status | Meaning | CI behavior |
|
||||
|---|---|---|
|
||||
| `PASS` | Comparable baseline exists and no gated metric regressed. Legacy records with no baseline also keep the historical initialization behavior. | Passes |
|
||||
| `REGRESSION` | The record exceeds one of its static thresholds or at least one gated metric regressed against a comparable baseline. | Fails |
|
||||
| `CALIBRATION_NEEDED` | A v2 record has no exact comparable baseline. | Passes, may upload when `PERF_UPLOAD_POLICY=pass`, never seeds a baseline |
|
||||
| `RECIPE_MISMATCH` | The same workload, variant, and benchmark version has trusted successful records under another recipe fingerprint, including records from other hardware or software profiles. | Fails |
|
||||
| `INFRA_ERROR` | The comparator cannot safely classify the record, such as a v2 record missing required identity fields. | Fails |
|
||||
|
||||
`QUALITY_BLOCKED` is reserved for a future variant-promotion workflow and is
|
||||
not emitted by normal rolling-baseline comparison.
|
||||
|
||||
For `RECIPE_MISMATCH`, trusted records are scheduled-main records or records
|
||||
already marked `baseline_eligible`. PR and local calibration uploads remain
|
||||
visible but do not authorize future CI-gating recipe mismatch failures.
|
||||
|
||||
When the baseline shifts for a legitimate reason (torch upgrade, kernel
|
||||
change, etc.) and CI starts failing, use the
|
||||
[`reseed-performance-baseline`](https://github.com/hao-ai-lab/FastVideo/blob/main/.agents/skills/reseed-performance-baseline/SKILL.md)
|
||||
agent skill to advance the rolling median.
|
||||
agent skill to advance the rolling median. To approve the first baseline for
|
||||
a new v2 exact identity, follow that skill with a reviewed scheduled-main
|
||||
full-suite `CALIBRATION_NEEDED` normalized artifact. Its prepare step uses
|
||||
`fastvideo/tests/performance/seed_baseline.py`; after a separate human gate,
|
||||
the skill rechecks the current HF revision and conditionally uploads the whole
|
||||
seed batch in one commit.
|
||||
|
||||
## Schemas
|
||||
|
||||
@@ -207,14 +230,14 @@ configs and remain loadable. New or migrated configs should use
|
||||
"config_schema_version": 2,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2
|
||||
"benchmark_version": 3
|
||||
}
|
||||
```
|
||||
|
||||
`benchmark_id` is still required in this phase because raw artifact names,
|
||||
generated-video directories, normalized record paths, and the current rolling
|
||||
baseline comparator still depend on it. The v2 identity fields are config
|
||||
metadata that make the measured workload explicit:
|
||||
`benchmark_id` is still required because raw artifact names, generated-video
|
||||
directories, normalized record paths, and legacy storage directories depend on
|
||||
it. The v2 comparator does not use it as part of the comparison cohort. The v2
|
||||
identity fields make the measured workload explicit:
|
||||
|
||||
| Field | Purpose |
|
||||
|---|---|
|
||||
@@ -225,20 +248,26 @@ metadata that make the measured workload explicit:
|
||||
If a config declares `config_schema_version: 2`, loading fails clearly when any
|
||||
required v2 identity field is missing. If v2 identity or metadata fields are
|
||||
added without `config_schema_version: 2`, loading also fails so partial
|
||||
migrations do not silently run as v1 configs. Optional v2 metadata fields
|
||||
reserved for follow-up work, such as `metric_threshold_policy` and
|
||||
`quality_metadata`, must be JSON objects when present. (`recipe` is emitted
|
||||
by the harness and is not config-declarable.)
|
||||
migrations do not silently run as v1 configs. Optional v2 `quality_metadata`
|
||||
and the v1/v2 `regression_thresholds` policy must be JSON objects when present.
|
||||
(`recipe` is emitted by the harness and is not config-declarable.)
|
||||
|
||||
Recipe fingerprinting, hardware/software profile IDs, exact-identity
|
||||
comparison, and dashboard cohort grouping land with this change: v2 records
|
||||
compare only within their identity cohort, and a record that opens a NEW
|
||||
cohort is marked `baseline_status: "initialized_new_cohort"` (regression
|
||||
gating starts once that cohort accumulates history). Legacy v1 configs still
|
||||
V2 records compare only within their exact identity cohort. A record that opens
|
||||
a new cohort is marked `baseline_status: "initialized_new_cohort"` and
|
||||
`comparison_status: "CALIBRATION_NEEDED"`; it remains ineligible until a
|
||||
reviewed scheduled-main artifact is seeded explicitly. Legacy v1 configs still
|
||||
run and are normalized for reporting, but their records skip rolling-baseline
|
||||
comparison entirely (`baseline_status: "skipped_missing_identity"`, never
|
||||
baseline eligible); only static thresholds gate them. Metric-specific
|
||||
threshold policies and promoted baselines remain separate follow-ups.
|
||||
baseline eligible); only static thresholds gate them. Metric-specific threshold
|
||||
policies are active. `QUALITY_BLOCKED` remains reserved for future variant
|
||||
promotion policy.
|
||||
|
||||
The shipped Wan benchmark uses `benchmark_version: 3` because recipe schema 2
|
||||
changed the recipe fingerprint by removing the legacy `benchmark_id` display
|
||||
name. This intentionally opens a new comparison cohort: after deployment, a
|
||||
reviewed scheduled-main full-suite `CALIBRATION_NEEDED` artifact must be seeded
|
||||
once before rolling regression gating resumes for that exact identity. Static
|
||||
thresholds remain active during calibration.
|
||||
|
||||
### Raw record (`results/perf_*.json`)
|
||||
|
||||
@@ -250,7 +279,7 @@ Written by `test_inference_performance.py`. One file per benchmark run.
|
||||
"result_schema_version": 2,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2,
|
||||
"benchmark_version": 3,
|
||||
"model_short_name": "Wan2.1-T2V-1.3B-Diffusers",
|
||||
"device": "NVIDIA L40S",
|
||||
"num_gpus": 2,
|
||||
@@ -289,12 +318,12 @@ Written by `test_inference_performance.py`. One file per benchmark run.
|
||||
"dit_time_s": 8.437,
|
||||
"vae_decode_time_s": 3.208,
|
||||
"recipe": {
|
||||
"recipe_schema_version": 1,
|
||||
"recipe_schema_version": 2,
|
||||
"benchmark": {
|
||||
"benchmark_id": "wan-t2v-1.3b-2gpu",
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2
|
||||
"benchmark_version": 3
|
||||
},
|
||||
"model": { "model_path": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers" },
|
||||
"init_kwargs": { "num_gpus": 2, "sp_size": 2, "tp_size": 1 },
|
||||
@@ -314,6 +343,9 @@ Written by `test_inference_performance.py`. One file per benchmark run.
|
||||
"python": "3.12",
|
||||
"pytorch": "2.12",
|
||||
"cuda": "13.0",
|
||||
"attention_backend": "FLASH_ATTN",
|
||||
"flash_attention_4_enabled": true,
|
||||
"container_image_version": "py3.12-cuda13.0.0",
|
||||
"packages": {
|
||||
"fastvideo_kernel": "0.3.2",
|
||||
"flashinfer": "0.2.11",
|
||||
@@ -322,7 +354,12 @@ Written by `test_inference_performance.py`. One file per benchmark run.
|
||||
}
|
||||
},
|
||||
"software_profile_id": "sw-<sha256-prefix>",
|
||||
"environment_metadata": { "env": { "IMAGE_VERSION": "py3.12-cuda13.0.0" } },
|
||||
"environment_metadata": {
|
||||
"env": {
|
||||
"IMAGE_VERSION": "py3.12-cuda13.0.0",
|
||||
"FASTVIDEO_CONTAINER_IMAGE_REF": "ghcr.io/hao-ai-lab/fastvideo/fastvideo-dev:py3.12-cuda13.0.0@sha256:<digest>"
|
||||
}
|
||||
},
|
||||
"environment_fingerprint": "env-<sha256-prefix>"
|
||||
}
|
||||
```
|
||||
@@ -338,7 +375,7 @@ result, used as the rolling-baseline source of truth.
|
||||
"result_schema_version": 2,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2,
|
||||
"benchmark_version": 3,
|
||||
"timestamp": "2026-05-08T22:00:00+00:00",
|
||||
"commit_sha": "<full sha>",
|
||||
"gpu_type": "NVIDIA L40S",
|
||||
@@ -367,6 +404,10 @@ result, used as the rolling-baseline source of truth.
|
||||
"build_id": "<buildkite-build-id>",
|
||||
"job_id": "<buildkite-job-id>",
|
||||
"quality_metadata": { "quality_status": "canonical" },
|
||||
"baseline_status": "compared",
|
||||
"comparison_status": "PASS",
|
||||
"comparison_status_reason": "Comparable baseline found with no gated regressions",
|
||||
"baseline_eligible": false,
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
@@ -384,9 +425,12 @@ Current `perf_*.json` artifacts that lack the v2 comparison identity are
|
||||
normalized for reporting but skip rolling-baseline comparison and are not marked
|
||||
baseline eligible.
|
||||
|
||||
New records compare only against the same `model_id`, `gpu_type`,
|
||||
`workload_id`, `variant_id`, `benchmark_version`, `recipe_fingerprint`,
|
||||
`hardware_profile_id`, and `software_profile_id` cohort.
|
||||
New v2 records compare only against the same `workload_id`, `variant_id`,
|
||||
`benchmark_version`, `recipe_fingerprint`, `hardware_profile_id`, and
|
||||
`software_profile_id` cohort, independent of the legacy `model_id` directory
|
||||
and `gpu_type` display string. Historical v1 records remain readable for
|
||||
reporting, but current legacy artifacts do not perform a `(model_id, gpu_type)`
|
||||
rolling comparison or seed new rolling baselines.
|
||||
`environment_metadata` and `environment_fingerprint` are audit data and are not
|
||||
part of the comparison key.
|
||||
The recipe prompt digests describe the prompts actually measured by the
|
||||
@@ -406,11 +450,16 @@ FlashInfer, Cutlass DSL, SageAttention, Triton, and xFormers when installed.
|
||||
| `HF_API_KEY`, `HUGGINGFACE_HUB_TOKEN`, `HF_TOKEN` | unset | `fastvideo/performance/hf_store.py` | Required for upload or private dataset reads. |
|
||||
| `PERF_RUN_SOURCE` | inferred | `compare_baseline.py`, `test_inference_performance.py` | Source metadata for uploaded records: `pr`, `local`, `scheduled_main`, or `unknown`. |
|
||||
| `PERF_UPLOAD_POLICY` | `never` | `compare_baseline.py` | Upload policy: `never`, `pass`, or `always`. |
|
||||
| `PERF_PYTEST_RC` | unset | `compare_baseline.py` | Static-threshold pytest exit code, used so scheduled-main failures can be uploaded with `success=false`. |
|
||||
| `PERF_PYTEST_RC` | unset | `compare_baseline.py` | Performance pytest exit code. Measured static-threshold failures are attributed per record; otherwise a nonzero code reports an infrastructure error. |
|
||||
| `TEST_SCOPE` | unset | `compare_baseline.py` | CI context used to infer scheduled-main runs together with `BUILDKITE_BRANCH=main`. |
|
||||
| `BUILDKITE_BRANCH`, `BUILDKITE_COMMIT`, `BUILDKITE_PULL_REQUEST` | unset | `compare_baseline.py`, `test_inference_performance.py` | CI metadata stamped into records. |
|
||||
| `DASHBOARD_DAYS` | `30` | `dashboard.py` | Lookback window for the Plotly trend pages. |
|
||||
| `PERFORMANCE_TRACKING_SYNC_REUSE_TTL_SECONDS` | `3600` | `fastvideo/performance/hf_store.py` | Freshness window for reusing an existing HF sync when requested by dashboard consumers. |
|
||||
| `FASTVIDEO_ATTENTION_BACKEND` | `auto` | `test_inference_performance.py` | Requested attention backend included in `software_profile_id`. |
|
||||
| `FASTVIDEO_FA4` | `0` | `test_inference_performance.py` | FlashAttention-4 toggle included in `software_profile_id`. |
|
||||
| `FASTVIDEO_PERFORMANCE_PROFILE_VERSION` | unset | `test_inference_performance.py` | Optional explicit software cohort/profile version included in `software_profile_id`. |
|
||||
| `IMAGE_VERSION` | unset | `test_inference_performance.py` | CI container image/profile version included in `software_profile_id` when available. |
|
||||
| `FASTVIDEO_CONTAINER_IMAGE_REF` | unset | `pr_test.py`, `launch_l40s_job.py`, `test_inference_performance.py` | Resolved CI container image ref or digest recorded in `environment_metadata` for audit without changing `software_profile_id`. |
|
||||
| `FASTVIDEO_STAGE_LOGGING` | set by the pytest test | `test_inference_performance.py` | Enables pipeline stage timing capture for component metrics during benchmark runs. |
|
||||
|
||||
## CI integration
|
||||
@@ -425,9 +474,11 @@ Each performance build runs pytest first. PR and direct runs only continue to
|
||||
`compare_baseline.py` when that fixed-threshold phase passes; if pytest fails,
|
||||
Markdown summaries and normalized JSON artifacts are not emitted. Scheduled
|
||||
main runs set `PERF_UPLOAD_POLICY=always`, so they still run
|
||||
`compare_baseline.py` (with `PERF_PYTEST_RC` set) after a fixed-threshold
|
||||
failure. Those failed scheduled main runs emit summaries and normalized
|
||||
records, upload records with `success=false`, and are excluded from future
|
||||
`compare_baseline.py` (with `PERF_PYTEST_RC` set) after pytest fails. Each raw
|
||||
record is checked against its own static thresholds: a measured breach reports
|
||||
`REGRESSION`, while unaffected records retain their rolling-baseline status. A
|
||||
nonzero pytest exit with no attributable static-threshold breach reports
|
||||
`INFRA_ERROR`. Failed records have `success=false` and are excluded from future
|
||||
rolling baselines. The dashboard still runs best-effort for observability.
|
||||
When the rolling-baseline phase runs, it emits:
|
||||
|
||||
@@ -487,10 +538,13 @@ When the rolling-baseline phase runs, it emits:
|
||||
2. The pytest test auto-discovers all configs — no test code needed. CI
|
||||
picks it up on the next `/test performance` run.
|
||||
|
||||
3. The first persisted main-branch run with no HF history initializes the
|
||||
baseline (passes automatically). Subsequent runs compare against it. Local
|
||||
and pull-request runs with no HF history also pass, but they do not seed the
|
||||
shared baseline.
|
||||
3. Legacy benchmarks are gated only by their static thresholds. Their current
|
||||
records skip rolling-baseline comparison and are never baseline eligible.
|
||||
V2 benchmarks with no exact comparable baseline report
|
||||
`CALIBRATION_NEEDED`; the record remains visible but does not become
|
||||
baseline eligible until a comparable scheduled-main full-suite run is
|
||||
reviewed and seeded through the prepare, review, and conditional-upload
|
||||
steps in the `reseed-performance-baseline` skill.
|
||||
|
||||
4. If the benchmark targets a GPU not currently in `thresholds`, either add
|
||||
that GPU as a key or rely on the `default` block. Note that `default` is
|
||||
@@ -510,8 +564,12 @@ When the rolling-baseline phase runs, it emits:
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**"No baseline for ... Initializing"** — first run for this comparison cohort.
|
||||
Run will pass and (if persisting) seed the first record.
|
||||
**`CALIBRATION_NEEDED` / "No baseline found for exact comparable identity"** —
|
||||
the v2 run passes, but its normalized record remains
|
||||
`baseline_eligible=false`. Review a successful scheduled-main full-suite
|
||||
normalized artifact, then follow the `reseed-performance-baseline` skill. The
|
||||
utility only prepares a digest-protected manifest; the separately confirmed
|
||||
upload rechecks remote state and commits the batch atomically.
|
||||
|
||||
**Persistent failure right after a torch / kernel / image upgrade** —
|
||||
genuine regression *or* baseline drift. Compare the failing normalized record
|
||||
|
||||
@@ -18,6 +18,7 @@ from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
from huggingface_hub import HfApi, snapshot_download
|
||||
from huggingface_hub.constants import ENDPOINT
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Configuration — read once at import time, shared across both consumers
|
||||
@@ -35,7 +36,8 @@ SYNC_REUSE_TTL_SECONDS = int(os.environ.get("PERFORMANCE_TRACKING_SYNC_REUSE_TTL
|
||||
|
||||
def sanitize(value: str) -> str:
|
||||
"""Return a filesystem- and HF-path-safe version of *value*."""
|
||||
return re.sub(r"[^A-Za-z0-9._-]", "_", value)
|
||||
sanitized = re.sub(r"[^A-Za-z0-9._-]", "_", value)
|
||||
return f"_{sanitized}" if not sanitized or sanitized.startswith(".") else sanitized
|
||||
|
||||
|
||||
def safe_float(value: Any) -> float | None:
|
||||
@@ -60,6 +62,19 @@ def is_baseline_eligible_record(record: dict[str, Any]) -> bool:
|
||||
return "baseline_eligible" not in record and "run_source" not in record
|
||||
|
||||
|
||||
def _parse_record_timestamp(record: dict[str, Any]) -> datetime | None:
|
||||
raw_ts = record.get("timestamp")
|
||||
if not raw_ts:
|
||||
return None
|
||||
try:
|
||||
ts = datetime.fromisoformat(str(raw_ts))
|
||||
except ValueError:
|
||||
return None
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
return ts
|
||||
|
||||
|
||||
def resolve_hf_token() -> str | None:
|
||||
"""Return the first configured Hugging Face token env var."""
|
||||
for env_var in HF_TOKEN_ENV_VARS:
|
||||
@@ -95,11 +110,23 @@ def _sync_marker_is_fresh(marker_path: str) -> bool:
|
||||
return age.total_seconds() <= SYNC_REUSE_TTL_SECONDS
|
||||
|
||||
|
||||
def _sync_marker_matches_request(marker_path: str, revision: str | None) -> bool:
|
||||
try:
|
||||
with open(marker_path, encoding="utf-8") as marker:
|
||||
marker_data = json.load(marker)
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return False
|
||||
if marker_data.get("endpoint") != ENDPOINT or marker_data.get("repo_id") != HF_REPO_ID:
|
||||
return False
|
||||
return marker_data.get("revision") == revision
|
||||
|
||||
|
||||
def sync_from_hf(
|
||||
local_dir: str,
|
||||
*,
|
||||
strict: bool = False,
|
||||
reuse_existing: bool = False,
|
||||
revision: str | None = None,
|
||||
) -> str:
|
||||
"""Download the HF dataset repo snapshot to *local_dir*.
|
||||
|
||||
@@ -116,14 +143,18 @@ def sync_from_hf(
|
||||
snapshot checks when compare and dashboard scripts run sequentially in the
|
||||
same CI job, without silently reusing stale data in persistent local or
|
||||
long-lived runner environments.
|
||||
|
||||
Pass ``revision`` to pin the snapshot to a previously read Hub commit. This
|
||||
is used by conditional writers that must validate one exact remote state
|
||||
before committing with that revision as their parent.
|
||||
"""
|
||||
marker_path = _sync_marker_path(local_dir)
|
||||
if reuse_existing and os.path.exists(marker_path):
|
||||
if _sync_marker_is_fresh(marker_path):
|
||||
if _sync_marker_is_fresh(marker_path) and _sync_marker_matches_request(marker_path, revision):
|
||||
print(f"hf_store: reusing existing sync at {local_dir}")
|
||||
return local_dir
|
||||
os.remove(marker_path)
|
||||
print(f"hf_store: existing sync at {local_dir} is stale; refreshing")
|
||||
print(f"hf_store: existing sync at {local_dir} is stale or mismatched; refreshing")
|
||||
|
||||
if not reuse_existing and os.path.exists(marker_path):
|
||||
os.remove(marker_path)
|
||||
@@ -143,13 +174,17 @@ def sync_from_hf(
|
||||
local_dir=local_dir,
|
||||
token=resolve_hf_token(),
|
||||
allow_patterns="*.json",
|
||||
revision=revision,
|
||||
)
|
||||
os.makedirs(local_dir, exist_ok=True)
|
||||
with open(marker_path, "w", encoding="utf-8") as marker:
|
||||
json.dump({
|
||||
"repo_id": HF_REPO_ID,
|
||||
"synced_at": datetime.now(timezone.utc).isoformat(),
|
||||
}, marker)
|
||||
json.dump(
|
||||
{
|
||||
"endpoint": ENDPOINT,
|
||||
"repo_id": HF_REPO_ID,
|
||||
"synced_at": datetime.now(timezone.utc).isoformat(),
|
||||
"revision": revision,
|
||||
}, marker)
|
||||
except Exception as exc:
|
||||
if strict:
|
||||
raise
|
||||
@@ -231,7 +266,7 @@ def load_records(
|
||||
if days is not None:
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
|
||||
records: list[dict[str, Any]] = []
|
||||
records: list[tuple[datetime, str, dict[str, Any]]] = []
|
||||
|
||||
for path in sorted(glob.glob(os.path.join(local_dir, "**", "*.json"), recursive=True)):
|
||||
try:
|
||||
@@ -246,21 +281,17 @@ def load_records(
|
||||
if baseline_eligible_only and not is_baseline_eligible_record(data):
|
||||
continue
|
||||
|
||||
if cutoff is not None:
|
||||
raw_ts = data.get("timestamp")
|
||||
if raw_ts:
|
||||
try:
|
||||
ts = datetime.fromisoformat(raw_ts)
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
if ts < cutoff:
|
||||
continue
|
||||
except ValueError:
|
||||
pass # keep records with unparsable timestamps
|
||||
ts = _parse_record_timestamp(data)
|
||||
if cutoff is not None and ts is not None and ts < cutoff:
|
||||
continue
|
||||
|
||||
records.append(data)
|
||||
records.append((
|
||||
ts or datetime.min.replace(tzinfo=timezone.utc),
|
||||
path,
|
||||
data,
|
||||
))
|
||||
|
||||
return records
|
||||
return [data for _ts, _path, data in sorted(records)]
|
||||
|
||||
|
||||
def load_records_for_model(
|
||||
@@ -332,6 +363,36 @@ def load_records_for_model(
|
||||
return records
|
||||
|
||||
|
||||
def load_records_for_identity(
|
||||
local_dir: str,
|
||||
identity_filters: dict[str, str],
|
||||
*,
|
||||
last_n: int | None = None,
|
||||
successful_only: bool = True,
|
||||
baseline_eligible_only: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Return records matching comparable identity fields.
|
||||
|
||||
V2 performance comparison is intentionally independent from the legacy
|
||||
``model_id`` directory and ``gpu_type`` display string. The comparable
|
||||
identity filters usually contain the full v2 comparison key, and may also
|
||||
contain a subset when looking for same-cohort recipe mismatches.
|
||||
"""
|
||||
records = load_records(
|
||||
local_dir,
|
||||
successful_only=successful_only,
|
||||
baseline_eligible_only=baseline_eligible_only,
|
||||
)
|
||||
|
||||
for key, expected in identity_filters.items():
|
||||
records = [r for r in records if str(r.get(key)) == str(expected)]
|
||||
|
||||
if last_n is not None:
|
||||
records = records[-last_n:]
|
||||
|
||||
return records
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DataFrame helpers (dashboard / analytics consumers)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -23,6 +23,10 @@ FRONTEND_DIST = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), "..", "..", "performance_dashboard", "frontend", "dist"))
|
||||
|
||||
|
||||
def _matches_display_filters(record: dict[str, Any], model_id: str | None, gpu_type: str | None) -> bool:
|
||||
return (not model_id or record.get("model_id") == model_id) and (not gpu_type or record.get("gpu_type") == gpu_type)
|
||||
|
||||
|
||||
class PerformanceDataStore:
|
||||
|
||||
def __init__(self, tracking_root: str | None = None) -> None:
|
||||
@@ -147,11 +151,10 @@ def create_app(store: PerformanceDataStore | None = None) -> FastAPI:
|
||||
# query is kept only so the frontend can share filter state across
|
||||
# endpoints without affecting the summary semantics.
|
||||
loaded = data_store.load_records(days=None)
|
||||
filtered = filter_records(loaded, model_id=model_id, gpu_type=gpu_type)
|
||||
rows = build_latest_summary(
|
||||
filtered,
|
||||
run_source=run_source,
|
||||
)
|
||||
rows = [
|
||||
row for row in build_latest_summary(loaded, run_source=run_source)
|
||||
if _matches_display_filters(row, model_id, gpu_type)
|
||||
]
|
||||
return {
|
||||
"rows": rows,
|
||||
"count": len(rows),
|
||||
@@ -177,8 +180,10 @@ def create_app(store: PerformanceDataStore | None = None) -> FastAPI:
|
||||
run_source: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
loaded = data_store.load_records(days=days)
|
||||
filtered = filter_records(loaded, model_id=model_id, gpu_type=gpu_type, run_source=run_source)
|
||||
groups = build_trends(filtered)
|
||||
source_filtered = filter_records(loaded, run_source=run_source)
|
||||
groups = [
|
||||
group for group in build_trends(source_filtered) if _matches_display_filters(group, model_id, gpu_type)
|
||||
]
|
||||
return {
|
||||
"groups": groups,
|
||||
"count": len(groups),
|
||||
|
||||
@@ -17,7 +17,7 @@ from fastvideo.performance.hf_store import is_baseline_eligible_record, safe_flo
|
||||
from fastvideo.performance.metric_policy import regression_delta, resolve_metric_policies
|
||||
|
||||
Record = dict[str, Any]
|
||||
CohortKey = tuple[str, str, str, str, str, str, str, str]
|
||||
CohortKey = tuple[str, ...]
|
||||
COMPARISON_COHORT_KEYS = (
|
||||
"workload_id",
|
||||
"variant_id",
|
||||
@@ -102,16 +102,18 @@ def record_comparison_metadata(record: Record) -> Record:
|
||||
return {key: _cohort_metadata_value(record.get(key)) for key in COMPARISON_COHORT_KEYS}
|
||||
|
||||
|
||||
def _record_has_complete_v2_identity(record: Record) -> bool:
|
||||
return all(_cohort_metadata_value(record.get(key)) != "" for key in COMPARISON_COHORT_KEYS)
|
||||
|
||||
|
||||
def comparison_cohort_key(record: Record) -> CohortKey:
|
||||
if _record_has_complete_v2_identity(record):
|
||||
return ("v2", *(_cohort_key_value(record.get(key)) for key in COMPARISON_COHORT_KEYS))
|
||||
return (
|
||||
"legacy",
|
||||
str(record.get("model_id") or "unknown"),
|
||||
str(record.get("gpu_type") or "unknown"),
|
||||
_cohort_key_value(record.get("workload_id")),
|
||||
_cohort_key_value(record.get("variant_id")),
|
||||
_cohort_key_value(record.get("benchmark_version")),
|
||||
_cohort_key_value(record.get("recipe_fingerprint")),
|
||||
_cohort_key_value(record.get("hardware_profile_id")),
|
||||
_cohort_key_value(record.get("software_profile_id")),
|
||||
*(_cohort_key_value(record.get(key)) for key in COMPARISON_COHORT_KEYS),
|
||||
)
|
||||
|
||||
|
||||
@@ -122,20 +124,18 @@ def group_by_comparison_cohort(records: list[Record]) -> dict[CohortKey, list[Re
|
||||
return {key: sorted(value, key=record_sort_key) for key, value in groups.items()}
|
||||
|
||||
|
||||
def comparison_sort_key(record: Record) -> CohortKey:
|
||||
return comparison_cohort_key(record)
|
||||
def comparison_sort_key(record: Record) -> tuple[str, ...]:
|
||||
return (
|
||||
str(record.get("model_id") or "unknown"),
|
||||
str(record.get("gpu_type") or "unknown"),
|
||||
*(_cohort_key_value(record.get(key)) for key in COMPARISON_COHORT_KEYS),
|
||||
)
|
||||
|
||||
|
||||
def latest_row_sort_key(row: Record) -> tuple[Any, ...]:
|
||||
return (row["status"] != "fail", *comparison_sort_key(row))
|
||||
|
||||
|
||||
def group_identity(key: CohortKey) -> tuple[str, str]:
|
||||
model_id = key[0]
|
||||
gpu_type = key[1]
|
||||
return model_id, gpu_type
|
||||
|
||||
|
||||
def baseline_value(records: list[Record], metric_key: str) -> float | None:
|
||||
values = [safe_float(record.get(metric_key)) for record in records]
|
||||
values = [value for value in values if value is not None]
|
||||
@@ -149,8 +149,7 @@ def build_latest_summary(records: list[Record],
|
||||
baseline_window: int = 5,
|
||||
run_source: str | None = None) -> list[Record]:
|
||||
rows: list[Record] = []
|
||||
for key, group in group_by_comparison_cohort(records).items():
|
||||
model_id, gpu_type = group_identity(key)
|
||||
for group in group_by_comparison_cohort(records).values():
|
||||
latest_candidates = group
|
||||
if run_source:
|
||||
latest_candidates = [record for record in group if record_run_source(record) == run_source]
|
||||
@@ -158,6 +157,8 @@ def build_latest_summary(records: list[Record],
|
||||
continue
|
||||
|
||||
latest = latest_candidates[-1]
|
||||
model_id = str(latest.get("model_id") or "unknown")
|
||||
gpu_type = str(latest.get("gpu_type") or "unknown")
|
||||
latest_index = next(index for index, record in enumerate(group) if record is latest)
|
||||
baseline_pool = [
|
||||
record for record in group[:latest_index]
|
||||
@@ -224,8 +225,10 @@ def build_latest_summary(records: list[Record],
|
||||
|
||||
def build_trends(records: list[Record]) -> list[Record]:
|
||||
trends: list[Record] = []
|
||||
for key, group in group_by_comparison_cohort(records).items():
|
||||
model_id, gpu_type = group_identity(key)
|
||||
for group in group_by_comparison_cohort(records).values():
|
||||
latest = group[-1]
|
||||
model_id = str(latest.get("model_id") or "unknown")
|
||||
gpu_type = str(latest.get("gpu_type") or "unknown")
|
||||
points = []
|
||||
for record in group:
|
||||
metric_policies = resolve_metric_policies(record.get("regression_thresholds"))
|
||||
@@ -244,7 +247,7 @@ def build_trends(records: list[Record]) -> list[Record]:
|
||||
trends.append({
|
||||
"model_id": model_id,
|
||||
"gpu_type": gpu_type,
|
||||
**record_comparison_metadata(group[-1]),
|
||||
**record_comparison_metadata(latest),
|
||||
"points": points,
|
||||
})
|
||||
return sorted(trends, key=comparison_sort_key)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Guard the Modal FA4 defaults that keep CI lanes on their intended backend.
|
||||
"""Guard Modal runtime policies that keep CI lanes on their intended backend.
|
||||
|
||||
Pure text/AST analysis: no fastvideo imports, no torch, no Modal client.
|
||||
"""
|
||||
@@ -40,6 +40,22 @@ def test_ssim_launcher_keeps_fa4_enabled_by_default():
|
||||
assert '"FASTVIDEO_FA4": os.environ.get("FASTVIDEO_FA4", "1")' in source
|
||||
|
||||
|
||||
def test_performance_identity_env_reaches_modal_runtime():
|
||||
pr_source = PR_TEST.read_text(encoding="utf-8")
|
||||
launch_source = LAUNCH_L40S_JOB.read_text(encoding="utf-8")
|
||||
runtime_secret = pr_source.split("ci_env_secret =", 1)[1].split("hf_secret =", 1)[0]
|
||||
|
||||
for key in ("FASTVIDEO_ATTENTION_BACKEND", "FASTVIDEO_PERFORMANCE_PROFILE_VERSION"):
|
||||
assert key in runtime_secret
|
||||
assert "FASTVIDEO_PERFORMANCE_PROFILE_VERSION" in launch_source.split(".env({", 1)[1]
|
||||
|
||||
|
||||
def test_performance_lane_classifies_pull_requests_before_main():
|
||||
function_strings = _function_strings(PR_TEST, "run_performance_tests")
|
||||
assert function_strings.index(
|
||||
"BUILDKITE_PULL_REQUEST") < function_strings.index("BUILDKITE_BRANCH")
|
||||
|
||||
|
||||
def test_pr_model_load_and_training_lanes_disable_fa4():
|
||||
lanes = {
|
||||
"run_transformer_tests": "pytest ./fastvideo/tests/transformers -vs",
|
||||
|
||||
@@ -95,8 +95,13 @@ image = (
|
||||
"PATH": "/root/.cargo/bin:$PATH",
|
||||
"HF_HOME": "/root/data/.cache",
|
||||
"TOKENIZERS_PARALLELISM": "false",
|
||||
"IMAGE_VERSION": IMAGE_VERSION,
|
||||
"FASTVIDEO_CONTAINER_IMAGE_REF": IMAGE_REF,
|
||||
**({"UV_TORCH_BACKEND": uv_torch_backend_override} if uv_torch_backend_override else {}),
|
||||
"FASTVIDEO_ATTENTION_BACKEND": os.environ.get("FASTVIDEO_ATTENTION_BACKEND", "FLASH_ATTN"),
|
||||
**({
|
||||
"FASTVIDEO_PERFORMANCE_PROFILE_VERSION": os.environ["FASTVIDEO_PERFORMANCE_PROFILE_VERSION"]
|
||||
} if os.environ.get("FASTVIDEO_PERFORMANCE_PROFILE_VERSION") else {}),
|
||||
# FA4 is opt-in (FASTVIDEO_FA4). Generic ad hoc jobs should follow the
|
||||
# product default unless a caller opts in through the local env or
|
||||
# --env-vars.
|
||||
|
||||
@@ -71,6 +71,15 @@ ci_env_secret = modal.Secret.from_dict({
|
||||
"BUILDKITE_JOB_ID": os.environ.get("BUILDKITE_JOB_ID", ""),
|
||||
"TEST_SCOPE": os.environ.get("TEST_SCOPE", ""),
|
||||
"IMAGE_VERSION": image_version,
|
||||
"FASTVIDEO_CONTAINER_IMAGE_REF": image_ref,
|
||||
**{
|
||||
key: os.environ[key]
|
||||
for key in (
|
||||
"FASTVIDEO_ATTENTION_BACKEND",
|
||||
"FASTVIDEO_PERFORMANCE_PROFILE_VERSION",
|
||||
)
|
||||
if os.environ.get(key)
|
||||
},
|
||||
**({
|
||||
"UV_TORCH_BACKEND": uv_torch_backend_override
|
||||
} if uv_torch_backend_override else {}),
|
||||
@@ -409,12 +418,12 @@ def run_performance_tests():
|
||||
"export HF_HOME='/root/data/.cache' && "
|
||||
"export PERFORMANCE_TRACKING_ROOT='/tmp/perf-tracking' && "
|
||||
"hf auth login --token $HF_API_KEY && "
|
||||
"if [ \"${BUILDKITE_BRANCH:-}\" = 'main' ] && ( [ \"${BUILDKITE_SOURCE:-}\" = 'schedule' ] || [ \"${TEST_SCOPE:-}\" = 'full' ] ); then "
|
||||
"export PERF_RUN_SOURCE='scheduled_main'; "
|
||||
"export PERF_UPLOAD_POLICY='always'; "
|
||||
"elif [ -n \"${BUILDKITE_PULL_REQUEST:-}\" ] && [ \"${BUILDKITE_PULL_REQUEST:-false}\" != 'false' ]; then "
|
||||
"if [ -n \"${BUILDKITE_PULL_REQUEST:-}\" ] && [ \"${BUILDKITE_PULL_REQUEST:-false}\" != 'false' ]; then "
|
||||
"export PERF_RUN_SOURCE='pr'; "
|
||||
"export PERF_UPLOAD_POLICY='pass'; "
|
||||
"elif [ \"${BUILDKITE_BRANCH:-}\" = 'main' ] && ( [ \"${BUILDKITE_SOURCE:-}\" = 'schedule' ] || [ \"${TEST_SCOPE:-}\" = 'full' ] ); then "
|
||||
"export PERF_RUN_SOURCE='scheduled_main'; "
|
||||
"export PERF_UPLOAD_POLICY='always'; "
|
||||
"elif [ \"${TEST_SCOPE:-}\" = 'direct' ]; then "
|
||||
"export PERF_RUN_SOURCE='unknown'; "
|
||||
"export PERF_UPLOAD_POLICY='pass'; "
|
||||
|
||||
@@ -23,7 +23,7 @@ from typing import Any
|
||||
|
||||
try:
|
||||
from fastvideo.performance.hf_store import (
|
||||
load_records_for_model,
|
||||
load_records_for_identity,
|
||||
safe_float,
|
||||
sanitize,
|
||||
sync_from_hf,
|
||||
@@ -40,7 +40,7 @@ except ImportError:
|
||||
if repo_root not in sys.path:
|
||||
sys.path.insert(0, repo_root)
|
||||
from fastvideo.performance.hf_store import (
|
||||
load_records_for_model,
|
||||
load_records_for_identity,
|
||||
safe_float,
|
||||
sanitize,
|
||||
sync_from_hf,
|
||||
@@ -89,6 +89,20 @@ COMPARISON_IDENTITY_KEYS = (
|
||||
"hardware_profile_id",
|
||||
"software_profile_id",
|
||||
)
|
||||
STATUS_PASS = "PASS"
|
||||
STATUS_REGRESSION = "REGRESSION"
|
||||
STATUS_CALIBRATION_NEEDED = "CALIBRATION_NEEDED"
|
||||
STATUS_RECIPE_MISMATCH = "RECIPE_MISMATCH"
|
||||
STATUS_INFRA_ERROR = "INFRA_ERROR"
|
||||
# Reserved for the promoted-baseline workflow; never emitted here.
|
||||
STATUS_QUALITY_BLOCKED = "QUALITY_BLOCKED"
|
||||
STATIC_THRESHOLD_FIELDS = (
|
||||
("avg_generation_time_s", "max_generation_time_s"),
|
||||
("max_peak_memory_mb", "max_peak_memory_mb"),
|
||||
("text_encoder_time_s", "max_text_encoder_time_s"),
|
||||
("dit_time_s", "max_dit_time_s"),
|
||||
("vae_decode_time_s", "max_vae_decode_time_s"),
|
||||
)
|
||||
|
||||
|
||||
def _should_persist_tracking() -> bool:
|
||||
@@ -122,7 +136,13 @@ def _detect_run_source() -> str:
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _is_baseline_eligible(run_source: str, success: bool) -> bool:
|
||||
def _is_baseline_eligible(
|
||||
run_source: str,
|
||||
success: bool,
|
||||
comparison_status: str | None = None,
|
||||
) -> bool:
|
||||
if comparison_status is not None and comparison_status != STATUS_PASS:
|
||||
return False
|
||||
return run_source == "scheduled_main" and success
|
||||
|
||||
|
||||
@@ -135,7 +155,7 @@ def _upload_allowed(record: dict[str, Any]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _result_failed_static_thresholds() -> bool:
|
||||
def _performance_pytest_failed() -> bool:
|
||||
value = os.environ.get("PERF_PYTEST_RC", "")
|
||||
if not value:
|
||||
return False
|
||||
@@ -193,18 +213,52 @@ def _comparison_identity_filters(record: dict[str, Any]) -> dict[str, str]:
|
||||
}
|
||||
|
||||
|
||||
def _record_uses_v2_identity(record: dict[str, Any]) -> bool:
|
||||
schema_version = record.get("result_schema_version")
|
||||
return str(schema_version) == "2" or any(key in record for key in COMPARISON_IDENTITY_KEYS)
|
||||
|
||||
|
||||
def _recipe_cohort_filters(record: dict[str, Any]) -> dict[str, str]:
|
||||
identity = _comparison_identity_filters(record)
|
||||
return {
|
||||
key: identity[key]
|
||||
for key in ("workload_id", "variant_id", "benchmark_version")
|
||||
}
|
||||
|
||||
|
||||
def _comparison_identity_filters_or_none(record: dict[str, Any]) -> dict[str, str] | None:
|
||||
try:
|
||||
return _comparison_identity_filters(record)
|
||||
except ValueError as exc:
|
||||
print("Skipping rolling baseline comparison for "
|
||||
f"{record.get('model_id', 'unknown')} on "
|
||||
f"{record.get('gpu_type', 'unknown')}: {exc}. "
|
||||
"The normalized artifact will still be written, but this record "
|
||||
"will not be baseline eligible.")
|
||||
if _record_uses_v2_identity(record):
|
||||
print(f"Invalid v2 comparison identity for {record.get('model_id', 'unknown')}: {exc}")
|
||||
else:
|
||||
print("Skipping rolling baseline comparison for "
|
||||
f"{record.get('model_id', 'unknown')} on "
|
||||
f"{record.get('gpu_type', 'unknown')}: {exc}. "
|
||||
"The normalized artifact will still be written, but this record "
|
||||
"will not be baseline eligible.")
|
||||
return None
|
||||
|
||||
|
||||
def _recipe_mismatch_records(
|
||||
record: dict[str, Any],
|
||||
cohort_records: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
current_recipe = str(record.get("recipe_fingerprint"))
|
||||
return [
|
||||
item for item in cohort_records
|
||||
if _record_can_authorize_recipe_mismatch(item)
|
||||
and item.get("recipe_fingerprint") is not None
|
||||
and str(item.get("recipe_fingerprint")).strip()
|
||||
and str(item.get("recipe_fingerprint")) != current_recipe
|
||||
]
|
||||
|
||||
|
||||
def _record_can_authorize_recipe_mismatch(record: dict[str, Any]) -> bool:
|
||||
return record.get("run_source") == "scheduled_main" or record.get("baseline_eligible") is True
|
||||
|
||||
|
||||
def _format_identity_filters(filters: dict[str, str]) -> str:
|
||||
if not filters:
|
||||
return ""
|
||||
@@ -343,12 +397,99 @@ def _check_regressions(
|
||||
return failures
|
||||
|
||||
|
||||
def _fixed_threshold_failures(raw_result: dict[str, Any]) -> list[str]:
|
||||
thresholds = raw_result.get("thresholds")
|
||||
if not isinstance(thresholds, dict):
|
||||
return []
|
||||
|
||||
failures = []
|
||||
for result_key, threshold_key in STATIC_THRESHOLD_FIELDS:
|
||||
current = safe_float(raw_result.get(result_key))
|
||||
threshold = safe_float(thresholds.get(threshold_key))
|
||||
if current is None or threshold is None or current <= threshold:
|
||||
continue
|
||||
failures.append(
|
||||
f"{raw_result.get('benchmark_id', 'unknown')} {result_key} exceeded fixed threshold "
|
||||
f"(current={current:.3f}, threshold={threshold:.3f})"
|
||||
)
|
||||
return failures
|
||||
|
||||
|
||||
def _pytest_infra_failure(record: dict[str, Any]) -> str:
|
||||
return (f"{record['model_id']} performance pytest failed without an "
|
||||
"attributable static-threshold regression "
|
||||
f"(PERF_PYTEST_RC={os.environ.get('PERF_PYTEST_RC')})")
|
||||
|
||||
|
||||
def _recipe_mismatch_failure(
|
||||
record: dict[str, Any],
|
||||
recipe_mismatch_records: list[dict[str, Any]],
|
||||
) -> str:
|
||||
seen = sorted({
|
||||
str(item.get("recipe_fingerprint"))
|
||||
for item in recipe_mismatch_records
|
||||
if item.get("recipe_fingerprint") is not None
|
||||
})
|
||||
suffix = f"; existing recipe_fingerprint values: {', '.join(seen)}" if seen else ""
|
||||
return (f"{record['model_id']} recipe_fingerprint={record.get('recipe_fingerprint')} "
|
||||
"does not match baseline records for the same workload, variant, "
|
||||
"and benchmark version across hardware and software profiles"
|
||||
f"{suffix}")
|
||||
|
||||
|
||||
def _evaluate_record_comparison(
|
||||
record: dict[str, Any],
|
||||
baseline_records: list[dict[str, Any]],
|
||||
recipe_mismatch_records: list[dict[str, Any]],
|
||||
metric_policies: tuple[MetricPolicy, ...],
|
||||
static_threshold_failures: list[str],
|
||||
unattributed_pytest_failure: bool,
|
||||
) -> tuple[list[str], str, str]:
|
||||
identity_filters = None
|
||||
if _record_uses_v2_identity(record):
|
||||
try:
|
||||
identity_filters = _comparison_identity_filters(record)
|
||||
except ValueError as exc:
|
||||
failure = f"{record['model_id']} cannot compare v2 record: {exc}"
|
||||
return [failure], STATUS_INFRA_ERROR, failure
|
||||
if not baseline_records and recipe_mismatch_records:
|
||||
failure = _recipe_mismatch_failure(record, recipe_mismatch_records)
|
||||
return [failure], STATUS_RECIPE_MISMATCH, failure
|
||||
|
||||
if static_threshold_failures:
|
||||
return static_threshold_failures, STATUS_REGRESSION, "; ".join(static_threshold_failures)
|
||||
|
||||
if unattributed_pytest_failure:
|
||||
failure = _pytest_infra_failure(record)
|
||||
return [failure], STATUS_INFRA_ERROR, failure
|
||||
|
||||
if not baseline_records:
|
||||
if identity_filters is not None:
|
||||
return [], STATUS_CALIBRATION_NEEDED, (
|
||||
"No baseline found for exact comparable identity"
|
||||
f"{_format_identity_filters(identity_filters)}"
|
||||
)
|
||||
|
||||
return [], STATUS_PASS, f"No legacy baseline for {record['model_id']} on {record['gpu_type']}"
|
||||
|
||||
failures = _check_regressions(record, baseline_records, metric_policies)
|
||||
if failures:
|
||||
return failures, STATUS_REGRESSION, "; ".join(failures)
|
||||
|
||||
return [], STATUS_PASS, "Comparable baseline found with no gated regressions"
|
||||
|
||||
|
||||
def _compact_value(value: float | None, precision: int = 3) -> str:
|
||||
if value is None:
|
||||
return "n/a"
|
||||
return f"{value:.{precision}f}"
|
||||
|
||||
|
||||
def _markdown_cell(value: Any) -> str:
|
||||
text = str(value) if value is not None else ""
|
||||
return text.replace("\n", " ").replace("|", "/")
|
||||
|
||||
|
||||
def _build_summary_row(
|
||||
record: dict[str, Any],
|
||||
baseline_records: list[dict[str, Any]],
|
||||
@@ -400,6 +541,8 @@ def _build_summary_row(
|
||||
"threshold_exceeded_metrics": threshold_exceeded_metrics,
|
||||
"failing_metrics": failing_metrics,
|
||||
"failed": has_failed,
|
||||
"status": record.get("comparison_status", STATUS_REGRESSION if has_failed else STATUS_PASS),
|
||||
"status_reason": record.get("comparison_status_reason", ""),
|
||||
}
|
||||
|
||||
|
||||
@@ -417,8 +560,8 @@ def _build_markdown_summary(
|
||||
"Throughput (curr/base) | Memory (curr/base) | "
|
||||
"Text Enc (curr/base) | DiT (curr/base) | "
|
||||
"VAE Decode (curr/base) | Worst Regression | Exceeded Metrics | "
|
||||
"Failing Metrics | Status |"),
|
||||
"|---|---|---:|---|---|---|---|---|---|---:|---|---|---|",
|
||||
"Failing Metrics | Status | Status Detail |"),
|
||||
"|---|---|---:|---|---|---|---|---|---|---:|---|---|---|---|",
|
||||
]
|
||||
|
||||
for row in summary_rows:
|
||||
@@ -435,12 +578,14 @@ def _build_markdown_summary(
|
||||
else "none"
|
||||
)
|
||||
failing_metrics = ", ".join(row["failing_metrics"]) if row["failing_metrics"] else "none"
|
||||
status = "FAIL" if row["failed"] else "PASS"
|
||||
status = row["status"]
|
||||
status_detail = row["status_reason"]
|
||||
|
||||
lines.append(f"| {row['model_id']} | {row['gpu_type']} | "
|
||||
f"{row['baseline_n']} | "
|
||||
f"{' | '.join(metric_cells)} | "
|
||||
f"{worst_reg} | {exceeded_metrics} | {failing_metrics} | {status} |")
|
||||
f"{worst_reg} | {exceeded_metrics} | {failing_metrics} | "
|
||||
f"{_markdown_cell(status)} | {_markdown_cell(status_detail)} |")
|
||||
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
@@ -470,7 +615,7 @@ def _emit_markdown_summary(markdown: str, commit_sha: str) -> None:
|
||||
def main() -> int:
|
||||
persist_tracking = _should_persist_tracking()
|
||||
upload_policy = _normalized_upload_policy()
|
||||
static_threshold_failed = _result_failed_static_thresholds()
|
||||
performance_pytest_failed = _performance_pytest_failed()
|
||||
|
||||
# Strict on upload-enabled runs: silent sync failure would make comparison
|
||||
# and upload state ambiguous.
|
||||
@@ -481,6 +626,9 @@ def main() -> int:
|
||||
print(f"No performance result files found in {RESULTS_DIR}")
|
||||
return 0
|
||||
|
||||
static_threshold_failures = [_fixed_threshold_failures(raw) for raw in current_results]
|
||||
unattributed_pytest_failure = performance_pytest_failed and not any(static_threshold_failures)
|
||||
|
||||
all_failures: list[str] = []
|
||||
summary_rows: list[dict[str, Any]] = []
|
||||
|
||||
@@ -489,61 +637,75 @@ def main() -> int:
|
||||
else:
|
||||
print("Tracking persistence disabled: PERF_UPLOAD_POLICY=never")
|
||||
|
||||
if static_threshold_failed:
|
||||
print(f"Static-threshold phase failed: PERF_PYTEST_RC={os.environ.get('PERF_PYTEST_RC')}")
|
||||
if performance_pytest_failed:
|
||||
if unattributed_pytest_failure:
|
||||
print("Performance pytest failed without a measured static-threshold regression: "
|
||||
f"PERF_PYTEST_RC={os.environ.get('PERF_PYTEST_RC')}")
|
||||
else:
|
||||
print("Performance pytest failure attributed to per-record static thresholds: "
|
||||
f"PERF_PYTEST_RC={os.environ.get('PERF_PYTEST_RC')}")
|
||||
|
||||
for raw in current_results:
|
||||
for raw, fixed_threshold_failures in zip(current_results, static_threshold_failures, strict=True):
|
||||
record = _normalize_record(raw)
|
||||
metric_policies = resolve_metric_policies(record.get("regression_thresholds"))
|
||||
identity_filters = _comparison_identity_filters_or_none(record)
|
||||
|
||||
baseline_records: list[dict[str, Any]] = []
|
||||
if identity_filters is None:
|
||||
# Records without the full v2 identity block skip rolling-baseline
|
||||
# comparison entirely: only the static thresholds gate them and
|
||||
# they never become baseline eligible.
|
||||
record["baseline_status"] = "skipped_missing_identity"
|
||||
failures: list[str] = []
|
||||
else:
|
||||
baseline_records = load_records_for_model(
|
||||
TRACKING_ROOT,
|
||||
record["model_id"],
|
||||
record["gpu_type"],
|
||||
**identity_filters,
|
||||
last_n=5,
|
||||
successful_only=True,
|
||||
baseline_eligible_only=True,
|
||||
)
|
||||
|
||||
if not baseline_records:
|
||||
# A brand-new cohort has NO regression gating until history
|
||||
# accumulates — make that loud and machine-readable instead of
|
||||
# an indistinguishable pass, so a cohort shift (intended or
|
||||
# accidental, e.g. an identity-field change) never silently
|
||||
# blinds the comparison.
|
||||
record["baseline_status"] = "initialized_new_cohort"
|
||||
print("=" * 72)
|
||||
print(f"WARNING: NO BASELINE — initializing a NEW cohort for "
|
||||
f"{record['model_id']} on {record['gpu_type']}"
|
||||
f"{_format_identity_filters(identity_filters)}")
|
||||
print("Regression gating is INACTIVE for this cohort until "
|
||||
"baseline history accumulates. If this cohort shift is "
|
||||
"unexpected, check the identity fields above.")
|
||||
print("=" * 72)
|
||||
failures = []
|
||||
recipe_mismatch_records: list[dict[str, Any]] = []
|
||||
try:
|
||||
if identity_filters is None:
|
||||
record["baseline_status"] = (
|
||||
"invalid_identity" if _record_uses_v2_identity(record) else "skipped_missing_identity"
|
||||
)
|
||||
else:
|
||||
record["baseline_status"] = "compared"
|
||||
failures = _check_regressions(record, baseline_records, metric_policies)
|
||||
if static_threshold_failed:
|
||||
failures.append(f"{record['model_id']} fixed-threshold phase failed "
|
||||
f"(PERF_PYTEST_RC={os.environ.get('PERF_PYTEST_RC')})")
|
||||
baseline_records = load_records_for_identity(
|
||||
TRACKING_ROOT,
|
||||
identity_filters,
|
||||
last_n=5,
|
||||
successful_only=True,
|
||||
baseline_eligible_only=True,
|
||||
)
|
||||
if baseline_records:
|
||||
record["baseline_status"] = "compared"
|
||||
else:
|
||||
recipe_cohort_records = load_records_for_identity(
|
||||
TRACKING_ROOT,
|
||||
_recipe_cohort_filters(record),
|
||||
successful_only=True,
|
||||
)
|
||||
recipe_mismatch_records = _recipe_mismatch_records(record, recipe_cohort_records)
|
||||
record["baseline_status"] = (
|
||||
"recipe_mismatch" if recipe_mismatch_records else "initialized_new_cohort"
|
||||
)
|
||||
|
||||
failures, comparison_status, comparison_status_reason = _evaluate_record_comparison(
|
||||
record,
|
||||
baseline_records,
|
||||
recipe_mismatch_records,
|
||||
metric_policies,
|
||||
fixed_threshold_failures,
|
||||
unattributed_pytest_failure,
|
||||
)
|
||||
except Exception as exc:
|
||||
comparison_status = STATUS_INFRA_ERROR
|
||||
comparison_status_reason = f"{record['model_id']} baseline comparison hit an infra error: {exc}"
|
||||
failures = [comparison_status_reason]
|
||||
baseline_records = []
|
||||
record["baseline_status"] = "infra_error"
|
||||
|
||||
record["comparison_status"] = comparison_status
|
||||
record["comparison_status_reason"] = comparison_status_reason
|
||||
|
||||
record["success"] = not failures
|
||||
record["baseline_eligible"] = (
|
||||
identity_filters is not None and _is_baseline_eligible(record["run_source"], record["success"])
|
||||
identity_filters is not None
|
||||
and _is_baseline_eligible(record["run_source"], record["success"], comparison_status)
|
||||
)
|
||||
all_failures.extend(failures)
|
||||
|
||||
print(f"{record['model_id']} comparison status: "
|
||||
f"{comparison_status} - {comparison_status_reason}")
|
||||
|
||||
_write_normalized_artifact(record)
|
||||
|
||||
if _upload_allowed(record):
|
||||
|
||||
@@ -37,7 +37,7 @@ COMPARISON_COHORT_KEYS = (
|
||||
"hardware_profile_id",
|
||||
"software_profile_id",
|
||||
)
|
||||
GROUP_KEYS = ("model_id", "gpu_type", *COMPARISON_COHORT_KEYS)
|
||||
GROUP_KEYS = ("_cohort_schema", "_cohort_model_id", "_cohort_gpu_type", *COMPARISON_COHORT_KEYS)
|
||||
|
||||
|
||||
def _cohort_value(value: object) -> str:
|
||||
@@ -62,35 +62,43 @@ def _short_value(value: object) -> str:
|
||||
return text[:12]
|
||||
|
||||
|
||||
def _cohort_title(group_key: tuple[object, ...]) -> str:
|
||||
workload = _display_value(group_key[2])
|
||||
variant = _display_value(group_key[3])
|
||||
version = _display_value(group_key[4])
|
||||
def _cohort_title(record: object) -> str:
|
||||
workload = _display_value(record.get("workload_id"))
|
||||
variant = _display_value(record.get("variant_id"))
|
||||
version = _display_value(record.get("benchmark_version"))
|
||||
version_label = version if version == "legacy" else f"v{version}"
|
||||
return f"{workload} / {variant} / {version_label}"
|
||||
|
||||
|
||||
def _cohort_detail(group_key: tuple[object, ...]) -> str:
|
||||
def _cohort_detail(record: object) -> str:
|
||||
return " | ".join((
|
||||
f"recipe {_short_value(group_key[5])}",
|
||||
_short_value(group_key[6]),
|
||||
_short_value(group_key[7]),
|
||||
f"recipe {_short_value(record.get('recipe_fingerprint'))}",
|
||||
_short_value(record.get("hardware_profile_id")),
|
||||
_short_value(record.get("software_profile_id")),
|
||||
))
|
||||
|
||||
|
||||
def _group_record(group_key: tuple[object, ...]) -> dict[str, str]:
|
||||
def _group_record(record: object) -> dict[str, str]:
|
||||
return {
|
||||
key: _cohort_value(value)
|
||||
for key, value in zip(GROUP_KEYS, group_key)
|
||||
key: _cohort_value(record.get(key))
|
||||
for key in ("model_id", "gpu_type", *COMPARISON_COHORT_KEYS)
|
||||
}
|
||||
|
||||
|
||||
def _has_complete_v2_identity(record: object) -> bool:
|
||||
return all(_cohort_value(record.get(key)) for key in COMPARISON_COHORT_KEYS)
|
||||
|
||||
|
||||
def _dashboard_frame(df: pd.DataFrame) -> pd.DataFrame:
|
||||
dashboard_df = df.copy()
|
||||
for key in GROUP_KEYS:
|
||||
for key in ("model_id", "gpu_type", *COMPARISON_COHORT_KEYS):
|
||||
if key not in dashboard_df.columns:
|
||||
dashboard_df[key] = ""
|
||||
dashboard_df[key] = dashboard_df[key].map(_cohort_value)
|
||||
uses_v2_identity = dashboard_df.apply(_has_complete_v2_identity, axis=1)
|
||||
dashboard_df["_cohort_schema"] = uses_v2_identity.map({True: "v2", False: "legacy"})
|
||||
dashboard_df["_cohort_model_id"] = dashboard_df["model_id"].where(~uses_v2_identity, "")
|
||||
dashboard_df["_cohort_gpu_type"] = dashboard_df["gpu_type"].where(~uses_v2_identity, "")
|
||||
return dashboard_df
|
||||
|
||||
# -----------------------------
|
||||
@@ -107,12 +115,14 @@ def build_plots(df: pd.DataFrame) -> tuple[list, list[dict[str, object]]]:
|
||||
figs = []
|
||||
skipped_metrics: list[dict[str, object]] = []
|
||||
|
||||
for group_key, g in group_data(df):
|
||||
model_id, gpu_type = group_key[:2]
|
||||
group_record = _group_record(group_key)
|
||||
cohort_title = _cohort_title(group_key)
|
||||
cohort_detail = _cohort_detail(group_key)
|
||||
for _group_key, g in group_data(df):
|
||||
g = g.sort_values("timestamp")
|
||||
display_record = g.iloc[-1]
|
||||
model_id = display_record["model_id"]
|
||||
gpu_type = display_record["gpu_type"]
|
||||
group_record = _group_record(display_record)
|
||||
cohort_title = _cohort_title(display_record)
|
||||
cohort_detail = _cohort_detail(display_record)
|
||||
|
||||
# One chart per metric so the y-axes aren't on wildly different scales
|
||||
for metric in METRICS:
|
||||
@@ -146,7 +156,7 @@ def build_plots(df: pd.DataFrame) -> tuple[list, list[dict[str, object]]]:
|
||||
x="timestamp",
|
||||
y=metric,
|
||||
markers=True,
|
||||
hover_data=["config_id", "commit_sha", *COMPARISON_COHORT_KEYS],
|
||||
hover_data=["model_id", "gpu_type", "config_id", "commit_sha", *COMPARISON_COHORT_KEYS],
|
||||
title=f"{model_id} | {gpu_type} | {cohort_title} | {cohort_detail} | {metric}",
|
||||
labels={"timestamp": "Time", metric: metric},
|
||||
)
|
||||
|
||||
@@ -17,7 +17,7 @@ from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
RECIPE_SCHEMA_VERSION = 1
|
||||
RECIPE_SCHEMA_VERSION = 2
|
||||
PROFILE_ID_LENGTH = 16
|
||||
_PATH_EXCLUDED_GENERATION_KEYS = {"output_path", "output_video_name"}
|
||||
_PROMPT_KEYS = {"prompt", "negative_prompt", "neg_prompt"}
|
||||
@@ -32,6 +32,7 @@ _PROFILE_ENV_VARS = (
|
||||
"FASTVIDEO_ATTENTION_BACKEND",
|
||||
"IMAGE_VERSION",
|
||||
"UV_TORCH_BACKEND",
|
||||
"FASTVIDEO_CONTAINER_IMAGE_REF",
|
||||
)
|
||||
_PACKAGE_DISTRIBUTIONS = {
|
||||
"fastvideo_kernel": ("fastvideo-kernel", "fastvideo_kernel"),
|
||||
@@ -87,6 +88,12 @@ def recipe_fingerprint(recipe: Mapping[str, Any]) -> str:
|
||||
# Intentional backend changes are declared via requested_backend,
|
||||
# which stays in the hash.
|
||||
attention.pop("resolved_backend", None)
|
||||
benchmark = pruned.get("benchmark")
|
||||
if isinstance(benchmark, dict):
|
||||
# benchmark_id names artifacts and storage directories, but is not one
|
||||
# of the six v2 comparison fields. Keep it in the recipe for audit
|
||||
# while allowing display-only renames to stay in the same cohort.
|
||||
benchmark.pop("benchmark_id", None)
|
||||
return sha256_hexdigest(canonical_json(pruned))
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,760 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Prepare reviewed v2 calibration artifacts as baseline seed records."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import statistics
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from huggingface_hub import CommitOperationAdd, HfApi
|
||||
from huggingface_hub.constants import ENDPOINT
|
||||
|
||||
try:
|
||||
from fastvideo.tests.performance.compare_baseline import (
|
||||
STATUS_CALIBRATION_NEEDED,
|
||||
STATUS_PASS,
|
||||
_comparison_identity_filters,
|
||||
_recipe_cohort_filters,
|
||||
_recipe_mismatch_records,
|
||||
_record_uses_v2_identity,
|
||||
)
|
||||
from fastvideo.performance.hf_store import (
|
||||
HF_REPO_ID,
|
||||
load_records_for_identity,
|
||||
resolve_hf_token,
|
||||
safe_float,
|
||||
sanitize,
|
||||
sync_from_hf,
|
||||
)
|
||||
from fastvideo.performance.metric_policy import DEFAULT_METRIC_POLICIES
|
||||
except ImportError:
|
||||
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
|
||||
if repo_root not in sys.path:
|
||||
sys.path.insert(0, repo_root)
|
||||
from fastvideo.tests.performance.compare_baseline import (
|
||||
STATUS_CALIBRATION_NEEDED,
|
||||
STATUS_PASS,
|
||||
_comparison_identity_filters,
|
||||
_recipe_cohort_filters,
|
||||
_recipe_mismatch_records,
|
||||
_record_uses_v2_identity,
|
||||
)
|
||||
from fastvideo.performance.hf_store import (
|
||||
HF_REPO_ID,
|
||||
load_records_for_identity,
|
||||
resolve_hf_token,
|
||||
safe_float,
|
||||
sanitize,
|
||||
sync_from_hf,
|
||||
)
|
||||
from fastvideo.performance.metric_policy import DEFAULT_METRIC_POLICIES
|
||||
|
||||
TRACKING_ROOT = os.environ.get("PERFORMANCE_TRACKING_ROOT", "/tmp/perf-tracking")
|
||||
STAGING_ROOT = os.environ.get("PERFORMANCE_RESEED_STAGING_ROOT", "/tmp/performance_reseed_prepared")
|
||||
DEFAULT_MAX_INTRA_BATCH_REGRESSION = 0.05
|
||||
_CORE_MEASUREMENT_FIELDS = frozenset({"latency", "throughput", "memory"})
|
||||
|
||||
|
||||
def _now_utc_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _load_json(path: str) -> dict[str, Any]:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def _write_json(path: str, payload: dict[str, Any]) -> None:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, indent=2)
|
||||
|
||||
|
||||
def _file_sha256(path: str) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _source_identity(record: dict[str, Any]) -> dict[str, str]:
|
||||
if not _record_uses_v2_identity(record):
|
||||
raise ValueError("baseline seeds require a v2 record with exact comparable identity fields")
|
||||
return _comparison_identity_filters(record)
|
||||
|
||||
|
||||
def _require_nonempty_string(record: dict[str, Any], field: str) -> str:
|
||||
value = record.get(field)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError(f"baseline seed records require a non-empty string {field}")
|
||||
return value
|
||||
|
||||
|
||||
def _source_provenance_identity(record: dict[str, Any]) -> tuple[str, ...] | None:
|
||||
job_id = str(record.get("job_id") or "")
|
||||
if job_id:
|
||||
return ("job_id", job_id)
|
||||
build_id = str(record.get("build_id") or "")
|
||||
if build_id:
|
||||
return ("build_id", build_id)
|
||||
commit_sha = str(record.get("commit_sha") or "")
|
||||
timestamp = str(record.get("timestamp") or "")
|
||||
if commit_sha or timestamp:
|
||||
return ("commit_timestamp", commit_sha, timestamp)
|
||||
return None
|
||||
|
||||
|
||||
def _validate_unique_sources(source_paths: list[str], records: list[dict[str, Any]]) -> None:
|
||||
seen_paths: set[str] = set()
|
||||
seen_contents: set[str] = set()
|
||||
seen_provenance: set[tuple[str, ...]] = set()
|
||||
|
||||
for index, (source_path, record) in enumerate(zip(source_paths, records), start=1):
|
||||
resolved_path = os.path.realpath(os.path.abspath(source_path))
|
||||
if resolved_path in seen_paths:
|
||||
raise ValueError(f"source artifact {index} duplicates a resolved source path")
|
||||
seen_paths.add(resolved_path)
|
||||
|
||||
content_identity = json.dumps(record, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
|
||||
if content_identity in seen_contents:
|
||||
raise ValueError(f"source artifact {index} duplicates source content")
|
||||
seen_contents.add(content_identity)
|
||||
|
||||
provenance_identity = _source_provenance_identity(record)
|
||||
if provenance_identity is not None:
|
||||
if provenance_identity in seen_provenance:
|
||||
raise ValueError(f"source artifact {index} duplicates source provenance")
|
||||
seen_provenance.add(provenance_identity)
|
||||
|
||||
|
||||
def _truthy_pr_number(value: Any) -> bool:
|
||||
return bool(value and str(value) not in {"false", "0", "None", "none"})
|
||||
|
||||
|
||||
def _validate_source_measurements(record: dict[str, Any]) -> None:
|
||||
for policy in DEFAULT_METRIC_POLICIES:
|
||||
raw_value = record.get(policy.key)
|
||||
if raw_value is None:
|
||||
if policy.key in _CORE_MEASUREMENT_FIELDS:
|
||||
raise ValueError(f"baseline seed records require a finite positive {policy.key} measurement")
|
||||
continue
|
||||
|
||||
value = None if isinstance(raw_value, bool) else safe_float(raw_value)
|
||||
if value is None or not math.isfinite(value):
|
||||
raise ValueError(f"baseline seed records require a finite {policy.key} measurement")
|
||||
if policy.key in _CORE_MEASUREMENT_FIELDS:
|
||||
if value <= 0:
|
||||
raise ValueError(f"baseline seed records require a positive {policy.key} measurement")
|
||||
elif value < 0:
|
||||
raise ValueError(f"baseline seed records require a non-negative {policy.key} measurement")
|
||||
|
||||
|
||||
def _validate_calibration_source(record: dict[str, Any]) -> None:
|
||||
_require_nonempty_string(record, "model_id")
|
||||
_source_identity(record)
|
||||
_validate_source_measurements(record)
|
||||
if record.get("result_schema_version") != 2:
|
||||
raise ValueError("baseline seeds require a normalized v2 source artifact")
|
||||
if record.get("comparison_status") != STATUS_CALIBRATION_NEEDED:
|
||||
raise ValueError("baseline seeds require a CALIBRATION_NEEDED source artifact")
|
||||
if record.get("success") is not True:
|
||||
raise ValueError("baseline seeds require a successful source artifact")
|
||||
if record.get("baseline_eligible") is not False:
|
||||
raise ValueError("baseline seeds require a baseline_eligible=false source artifact")
|
||||
if record.get("run_source") != "scheduled_main":
|
||||
raise ValueError("baseline seeds require a scheduled_main source artifact")
|
||||
if _truthy_pr_number(record.get("pr_number")):
|
||||
raise ValueError("baseline seeds require a non-PR source artifact")
|
||||
if record.get("branch") != "main" or record.get("test_scope") != "full":
|
||||
raise ValueError("baseline seeds require a main-branch full-suite source artifact")
|
||||
|
||||
|
||||
def build_baseline_seed_record(
|
||||
source_record: dict[str, Any],
|
||||
*,
|
||||
reason: str,
|
||||
source_result: str | None = None,
|
||||
operator: str | None = None,
|
||||
timestamp: str | None = None,
|
||||
batch_size: int = 1,
|
||||
batch_index: int = 1,
|
||||
) -> dict[str, Any]:
|
||||
"""Return an approved v2 baseline seed derived from a calibration artifact."""
|
||||
if not reason.strip():
|
||||
raise ValueError("baseline seed reason must be a non-empty string")
|
||||
_validate_calibration_source(source_record)
|
||||
|
||||
seed = dict(source_record)
|
||||
seed.update({
|
||||
"timestamp": timestamp or _now_utc_iso(),
|
||||
"success": True,
|
||||
"baseline_eligible": True,
|
||||
"comparison_status": STATUS_PASS,
|
||||
"comparison_status_reason": "Approved baseline seed from CALIBRATION_NEEDED source artifact",
|
||||
"baseline_seed": True,
|
||||
"baseline_seed_reason": reason,
|
||||
"baseline_seed_source_status": source_record.get("comparison_status"),
|
||||
"baseline_seed_source_timestamp": source_record.get("timestamp"),
|
||||
"baseline_seed_source_success": source_record.get("success"),
|
||||
"baseline_seed_source_run_source": source_record.get("run_source"),
|
||||
"baseline_seed_source_branch": source_record.get("branch"),
|
||||
"baseline_seed_source_test_scope": source_record.get("test_scope"),
|
||||
"baseline_seed_source_pr_number": source_record.get("pr_number"),
|
||||
"baseline_seed_batch_size": batch_size,
|
||||
"baseline_seed_batch_index": batch_index,
|
||||
})
|
||||
if source_result:
|
||||
seed["baseline_seed_source_result"] = source_result
|
||||
if operator:
|
||||
seed["baseline_seed_operator"] = operator
|
||||
return seed
|
||||
|
||||
|
||||
def write_seed_record(
|
||||
local_dir: str,
|
||||
record: dict[str, Any],
|
||||
*,
|
||||
suffix: str | None = None,
|
||||
) -> str:
|
||||
"""Write *record* under the staging root and return the local JSON path."""
|
||||
out_path = _seed_record_path(local_dir, record, suffix=suffix)
|
||||
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
||||
_write_json(out_path, record)
|
||||
return out_path
|
||||
|
||||
|
||||
def _seed_record_path(
|
||||
local_dir: str,
|
||||
record: dict[str, Any],
|
||||
*,
|
||||
suffix: str | None = None,
|
||||
) -> str:
|
||||
model_id = _require_nonempty_string(record, "model_id")
|
||||
timestamp = _require_nonempty_string(record, "timestamp")
|
||||
model_dir = os.path.join(local_dir, sanitize(model_id))
|
||||
commit = sanitize(record.get("commit_sha") or "unknown")
|
||||
suffix_part = f"_{sanitize(suffix)}" if suffix else ""
|
||||
return os.path.join(model_dir, f"{sanitize(timestamp)}_{commit}_seed{suffix_part}.json")
|
||||
|
||||
|
||||
def _validate_same_identity(records: list[dict[str, Any]]) -> dict[str, str]:
|
||||
first = _source_identity(records[0])
|
||||
for index, record in enumerate(records[1:], start=2):
|
||||
identity = _source_identity(record)
|
||||
if identity != first:
|
||||
raise ValueError(f"source artifact {index} does not match the first exact comparable identity")
|
||||
return first
|
||||
|
||||
|
||||
def _validate_separate_roots(tracking_root: str, staging_root: str) -> None:
|
||||
tracking_root = os.path.realpath(os.path.abspath(tracking_root))
|
||||
staging_root = os.path.realpath(os.path.abspath(staging_root))
|
||||
try:
|
||||
common_root = os.path.commonpath((tracking_root, staging_root))
|
||||
except ValueError:
|
||||
return
|
||||
if common_root in {tracking_root, staging_root}:
|
||||
raise ValueError("baseline seed staging and canonical tracking roots must be separate and non-nested")
|
||||
|
||||
|
||||
def _validate_no_existing_seed(
|
||||
records_root: str,
|
||||
record: dict[str, Any],
|
||||
*,
|
||||
source: str,
|
||||
) -> None:
|
||||
identity = _source_identity(record)
|
||||
if load_records_for_identity(
|
||||
records_root,
|
||||
identity,
|
||||
last_n=1,
|
||||
successful_only=True,
|
||||
baseline_eligible_only=True,
|
||||
):
|
||||
raise ValueError(
|
||||
f"{source} already has a baseline-eligible record for the exact comparable identity; "
|
||||
"the CALIBRATION_NEEDED source artifact is stale"
|
||||
)
|
||||
|
||||
cohort_records = load_records_for_identity(
|
||||
records_root,
|
||||
_recipe_cohort_filters(record),
|
||||
successful_only=True,
|
||||
)
|
||||
mismatches = _recipe_mismatch_records(record, cohort_records)
|
||||
if mismatches:
|
||||
recipes = sorted({str(item["recipe_fingerprint"]) for item in mismatches})
|
||||
raise ValueError(
|
||||
f"{source} already has trusted records for another recipe in this workload, "
|
||||
f"variant, and benchmark version: {', '.join(recipes)}"
|
||||
)
|
||||
|
||||
|
||||
def _repository_descriptor() -> dict[str, str]:
|
||||
return {
|
||||
"endpoint": ENDPOINT,
|
||||
"repo_id": HF_REPO_ID,
|
||||
"repo_type": "dataset",
|
||||
}
|
||||
|
||||
|
||||
def _reservation_path(staging_root: str, identity: dict[str, str]) -> str:
|
||||
payload = json.dumps({
|
||||
"identity": identity,
|
||||
"repository": _repository_descriptor(),
|
||||
}, sort_keys=True, separators=(",", ":"))
|
||||
digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||
return os.path.join(staging_root, ".seed-reservations", digest)
|
||||
|
||||
|
||||
def _reserve_staging_identity(staging_root: str, identity: dict[str, str]) -> str:
|
||||
reservation = _reservation_path(staging_root, identity)
|
||||
os.makedirs(os.path.dirname(reservation), exist_ok=True)
|
||||
try:
|
||||
os.mkdir(reservation, 0o700)
|
||||
except FileExistsError as exc:
|
||||
raise ValueError(
|
||||
"staging already has a reservation for the exact comparable identity; "
|
||||
"reuse or explicitly clean the existing preparation"
|
||||
) from exc
|
||||
return reservation
|
||||
|
||||
|
||||
def _release_failed_reservation(reservation: str, prepared_paths: list[str]) -> None:
|
||||
reservation = os.path.realpath(os.path.abspath(reservation))
|
||||
prepared_dirs: set[str] = set()
|
||||
for path in prepared_paths:
|
||||
path = os.path.realpath(os.path.abspath(path))
|
||||
if os.path.commonpath((reservation, path)) != reservation:
|
||||
continue
|
||||
try:
|
||||
os.unlink(path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
prepared_dirs.add(os.path.dirname(path))
|
||||
for name in ("manifest", "manifest.tmp"):
|
||||
try:
|
||||
os.unlink(os.path.join(reservation, name))
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
for directory in sorted(prepared_dirs, key=len, reverse=True):
|
||||
try:
|
||||
os.rmdir(directory)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.rmdir(reservation)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _write_preparation_manifest(
|
||||
reservation: str,
|
||||
staging_root: str,
|
||||
identity: dict[str, str],
|
||||
source_paths: list[str],
|
||||
source_records: list[dict[str, Any]],
|
||||
prepared_paths: list[str],
|
||||
) -> str:
|
||||
manifest_path = os.path.join(reservation, "manifest")
|
||||
temp_path = f"{manifest_path}.tmp"
|
||||
source_manifest_entries = []
|
||||
for path, expected_record in zip(source_paths, source_records, strict=True):
|
||||
with open(path, "rb") as f:
|
||||
blob = f.read()
|
||||
if json.loads(blob) != expected_record:
|
||||
raise ValueError(f"source record changed during preparation: {path}")
|
||||
source_manifest_entries.append({
|
||||
"path": os.path.realpath(os.path.abspath(path)),
|
||||
"sha256": hashlib.sha256(blob).hexdigest(),
|
||||
})
|
||||
manifest = {
|
||||
"manifest_schema_version": 1,
|
||||
"repository": _repository_descriptor(),
|
||||
"identity": identity,
|
||||
"recipe_cohort": {
|
||||
key: identity[key]
|
||||
for key in ("workload_id", "variant_id", "benchmark_version")
|
||||
},
|
||||
"staging_root": os.path.realpath(os.path.abspath(staging_root)),
|
||||
"source_records": source_manifest_entries,
|
||||
"prepared_records": [{
|
||||
"path": os.path.realpath(os.path.abspath(path)),
|
||||
"sha256": _file_sha256(path),
|
||||
} for path in prepared_paths],
|
||||
}
|
||||
_write_json(temp_path, manifest)
|
||||
os.replace(temp_path, manifest_path)
|
||||
return manifest_path
|
||||
|
||||
|
||||
def _validate_prepared_seed(record: dict[str, Any]) -> None:
|
||||
_source_identity(record)
|
||||
_require_nonempty_string(record, "model_id")
|
||||
_validate_source_measurements(record)
|
||||
if record.get("baseline_seed") is not True:
|
||||
raise ValueError("prepared records must have baseline_seed=true")
|
||||
if record.get("success") is not True or record.get("baseline_eligible") is not True:
|
||||
raise ValueError("prepared records must be successful and baseline eligible")
|
||||
if record.get("comparison_status") != STATUS_PASS:
|
||||
raise ValueError("prepared records must have comparison_status=PASS")
|
||||
if record.get("baseline_seed_source_status") != STATUS_CALIBRATION_NEEDED:
|
||||
raise ValueError("prepared records must retain CALIBRATION_NEEDED source provenance")
|
||||
if not str(record.get("baseline_seed_reason") or "").strip():
|
||||
raise ValueError("prepared records must retain a non-empty approval rationale")
|
||||
if (
|
||||
record.get("baseline_seed_source_success") is not True
|
||||
or record.get("baseline_seed_source_run_source") != "scheduled_main"
|
||||
or record.get("baseline_seed_source_branch") != "main"
|
||||
or record.get("baseline_seed_source_test_scope") != "full"
|
||||
or _truthy_pr_number(record.get("baseline_seed_source_pr_number"))
|
||||
):
|
||||
raise ValueError("prepared records must retain trusted scheduled-main source provenance")
|
||||
|
||||
|
||||
def upload_prepared_seed_manifest(manifest_path: str) -> str:
|
||||
"""Conditionally upload one reviewed manifest in a single Hub commit."""
|
||||
manifest_path = os.path.realpath(os.path.abspath(manifest_path))
|
||||
manifest = _load_json(manifest_path)
|
||||
if manifest.get("manifest_schema_version") != 1:
|
||||
raise ValueError("unsupported or missing prepared-seed manifest schema")
|
||||
expected_repository = _repository_descriptor()
|
||||
if manifest.get("repository") != expected_repository:
|
||||
raise ValueError("prepared-seed manifest repository does not match the configured Hub destination")
|
||||
|
||||
manifest_staging_root = manifest.get("staging_root")
|
||||
if not isinstance(manifest_staging_root, str) or not manifest_staging_root:
|
||||
raise ValueError("prepared-seed manifest is missing its staging root")
|
||||
staging_root = os.path.realpath(os.path.abspath(manifest_staging_root))
|
||||
source_entries = manifest.get("source_records")
|
||||
if not isinstance(source_entries, list) or not source_entries:
|
||||
raise ValueError("prepared-seed manifest must retain its reviewed source records")
|
||||
source_paths: list[str] = []
|
||||
source_records: list[dict[str, Any]] = []
|
||||
for entry in source_entries:
|
||||
if not isinstance(entry, dict):
|
||||
raise ValueError("prepared-seed manifest source entries must be objects")
|
||||
path = os.path.realpath(os.path.abspath(str(entry.get("path") or "")))
|
||||
with open(path, "rb") as f:
|
||||
blob = f.read()
|
||||
if hashlib.sha256(blob).hexdigest() != entry.get("sha256"):
|
||||
raise ValueError(f"source record changed after review: {path}")
|
||||
record = json.loads(blob)
|
||||
if not isinstance(record, dict):
|
||||
raise ValueError(f"source record must contain a JSON object: {path}")
|
||||
_validate_calibration_source(record)
|
||||
source_paths.append(path)
|
||||
source_records.append(record)
|
||||
_validate_unique_sources(source_paths, source_records)
|
||||
source_identity = _validate_same_identity(source_records)
|
||||
reservation = _reservation_path(staging_root, source_identity)
|
||||
if os.path.dirname(manifest_path) != reservation:
|
||||
raise ValueError("prepared-seed manifest is outside its identity reservation")
|
||||
|
||||
prepared_entries = manifest.get("prepared_records")
|
||||
if not isinstance(prepared_entries, list) or not prepared_entries:
|
||||
raise ValueError("prepared-seed manifest must contain at least one record")
|
||||
|
||||
prepared_paths: list[str] = []
|
||||
prepared_blobs: list[bytes] = []
|
||||
records: list[dict[str, Any]] = []
|
||||
for entry in prepared_entries:
|
||||
if not isinstance(entry, dict):
|
||||
raise ValueError("prepared-seed manifest record entries must be objects")
|
||||
path = os.path.realpath(os.path.abspath(str(entry.get("path") or "")))
|
||||
if os.path.commonpath((reservation, path)) != reservation:
|
||||
raise ValueError(f"prepared record is outside its identity reservation: {path}")
|
||||
with open(path, "rb") as f:
|
||||
blob = f.read()
|
||||
if hashlib.sha256(blob).hexdigest() != entry.get("sha256"):
|
||||
raise ValueError(f"prepared record changed after review: {path}")
|
||||
record = json.loads(blob)
|
||||
if not isinstance(record, dict):
|
||||
raise ValueError(f"prepared record must contain a JSON object: {path}")
|
||||
prepared_paths.append(path)
|
||||
prepared_blobs.append(blob)
|
||||
records.append(record)
|
||||
|
||||
for record in records:
|
||||
_validate_prepared_seed(record)
|
||||
if len(set(prepared_paths)) != len(prepared_paths):
|
||||
raise ValueError("prepared-seed manifest repeats a prepared record path")
|
||||
identity = _validate_same_identity(records)
|
||||
if source_identity != identity:
|
||||
raise ValueError("prepared records do not match their reviewed source identity")
|
||||
if manifest.get("identity") != identity:
|
||||
raise ValueError("prepared records no longer match the manifest identity")
|
||||
if manifest.get("recipe_cohort") != _recipe_cohort_filters(records[0]):
|
||||
raise ValueError("prepared records no longer match the manifest recipe cohort")
|
||||
|
||||
batch_size = len(records)
|
||||
if len(source_records) != batch_size:
|
||||
raise ValueError("prepared-seed manifest source and prepared batch sizes differ")
|
||||
if len({str(record.get("baseline_seed_reason")) for record in records}) != 1:
|
||||
raise ValueError("prepared records have inconsistent approval rationales")
|
||||
raw_batch_indices = [record.get("baseline_seed_batch_index") for record in records]
|
||||
if any(record.get("baseline_seed_batch_size") != batch_size for record in records):
|
||||
raise ValueError("prepared records have inconsistent baseline seed batch sizes")
|
||||
if any(isinstance(index, bool) or not isinstance(index, int) for index in raw_batch_indices):
|
||||
raise ValueError("prepared records have invalid baseline seed batch indices")
|
||||
batch_indices = sorted(raw_batch_indices)
|
||||
if batch_indices != list(range(1, batch_size + 1)):
|
||||
raise ValueError("prepared records have inconsistent baseline seed batch indices")
|
||||
for path, record in zip(prepared_paths, records, strict=True):
|
||||
index = record["baseline_seed_batch_index"]
|
||||
suffix = f"{index:02d}" if batch_size > 1 else None
|
||||
if path != _seed_record_path(reservation, record, suffix=suffix):
|
||||
raise ValueError(f"prepared record path does not match its reserved identity: {path}")
|
||||
|
||||
ordered_sources = _order_sources_by_timestamp(source_paths, source_records)
|
||||
records_by_index = sorted(records, key=lambda record: record["baseline_seed_batch_index"])
|
||||
for index, ((source_path, source_record), record) in enumerate(
|
||||
zip(ordered_sources, records_by_index, strict=True),
|
||||
start=1,
|
||||
):
|
||||
expected = build_baseline_seed_record(
|
||||
source_record,
|
||||
reason=str(record["baseline_seed_reason"]),
|
||||
source_result=source_path,
|
||||
operator=record.get("baseline_seed_operator"),
|
||||
timestamp=str(record["timestamp"]),
|
||||
batch_size=batch_size,
|
||||
batch_index=index,
|
||||
)
|
||||
if record != expected:
|
||||
raise ValueError(f"prepared record {index} no longer matches its reviewed source")
|
||||
|
||||
token = resolve_hf_token()
|
||||
if not token:
|
||||
raise RuntimeError("a Hugging Face write token is required to upload baseline seeds")
|
||||
api = HfApi(token=token)
|
||||
repo_info = api.repo_info(repo_id=HF_REPO_ID, repo_type="dataset", revision="main")
|
||||
parent_commit = getattr(repo_info, "sha", None)
|
||||
if not parent_commit:
|
||||
raise RuntimeError("could not resolve the current performance-tracking repository revision")
|
||||
|
||||
operations = []
|
||||
with tempfile.TemporaryDirectory(prefix="performance-seed-remote-") as remote_root:
|
||||
sync_from_hf(remote_root, strict=True, revision=parent_commit)
|
||||
_validate_no_existing_seed(remote_root, records[0], source="remote tracking history")
|
||||
|
||||
seen_destinations: set[str] = set()
|
||||
for path, blob, record in zip(prepared_paths, prepared_blobs, records, strict=True):
|
||||
destination = f"{sanitize(record['model_id'])}/{os.path.basename(path)}"
|
||||
if destination in seen_destinations:
|
||||
raise ValueError(f"prepared records collide at Hub path {destination}")
|
||||
if os.path.exists(os.path.join(remote_root, destination)):
|
||||
raise ValueError(f"Hub path already exists: {destination}")
|
||||
seen_destinations.add(destination)
|
||||
operations.append(CommitOperationAdd(path_in_repo=destination, path_or_fileobj=blob))
|
||||
|
||||
commit = api.create_commit(
|
||||
repo_id=HF_REPO_ID,
|
||||
repo_type="dataset",
|
||||
revision="main",
|
||||
parent_commit=parent_commit,
|
||||
create_pr=False,
|
||||
operations=operations,
|
||||
commit_message=f"Perf: seed {records[0]['model_id']} baseline",
|
||||
)
|
||||
|
||||
commit_id = getattr(commit, "oid", None) or getattr(commit, "commit_id", None)
|
||||
commit_id = str(commit_id or commit)
|
||||
try:
|
||||
_write_json(os.path.join(os.path.dirname(manifest_path), "uploaded"), {
|
||||
"commit_id": commit_id,
|
||||
"parent_commit": parent_commit,
|
||||
})
|
||||
except OSError as exc:
|
||||
print(f"Warning: seed commit {commit_id} succeeded but local upload marker failed: {exc}")
|
||||
return commit_id
|
||||
|
||||
|
||||
def _order_sources_by_timestamp(
|
||||
source_paths: list[str],
|
||||
records: list[dict[str, Any]],
|
||||
) -> list[tuple[str, dict[str, Any]]]:
|
||||
timestamped = []
|
||||
undated = []
|
||||
for index, (source_path, record) in enumerate(zip(source_paths, records), start=1):
|
||||
try:
|
||||
timestamp = datetime.fromisoformat(str(record.get("timestamp")))
|
||||
except (TypeError, ValueError):
|
||||
timestamp = None
|
||||
|
||||
if timestamp is None:
|
||||
print(
|
||||
f"Warning: source artifact {index} has a missing or unparsable timestamp; "
|
||||
"preserving its input order after timestamped sources."
|
||||
)
|
||||
undated.append((source_path, record))
|
||||
continue
|
||||
|
||||
if timestamp.tzinfo is None:
|
||||
timestamp = timestamp.replace(tzinfo=timezone.utc)
|
||||
timestamped.append((timestamp, index, source_path, record))
|
||||
|
||||
timestamped.sort(key=lambda item: (item[0], item[1]))
|
||||
return [(source_path, record) for _, _, source_path, record in timestamped] + undated
|
||||
|
||||
|
||||
def _nonnegative_finite_float(value: str) -> float:
|
||||
try:
|
||||
parsed = float(value)
|
||||
except ValueError as exc:
|
||||
raise argparse.ArgumentTypeError(f"expected a number, got {value!r}") from exc
|
||||
if not math.isfinite(parsed) or parsed < 0:
|
||||
raise argparse.ArgumentTypeError("value must be a finite non-negative number")
|
||||
return parsed
|
||||
|
||||
|
||||
def _validate_batch_consistency(
|
||||
records: list[dict[str, Any]],
|
||||
max_regression: float,
|
||||
) -> None:
|
||||
print(f"Source batch consistency (maximum regression {max_regression * 100:.1f}%):")
|
||||
failures = []
|
||||
for policy in DEFAULT_METRIC_POLICIES:
|
||||
values = [
|
||||
(index, value)
|
||||
for index, record in enumerate(records, start=1)
|
||||
if (value := safe_float(record.get(policy.key))) is not None
|
||||
]
|
||||
if len(values) < 2:
|
||||
continue
|
||||
|
||||
batch_median = statistics.median(value for _, value in values)
|
||||
if batch_median <= 0:
|
||||
raise ValueError(f"cannot validate {policy.key} consistency against non-positive batch median")
|
||||
|
||||
regressions = []
|
||||
for source_index, value in values:
|
||||
if policy.lower_is_better:
|
||||
regression = (value - batch_median) / batch_median
|
||||
else:
|
||||
regression = (batch_median - value) / batch_median
|
||||
regressions.append((source_index, regression))
|
||||
print(
|
||||
f" {policy.key} source={source_index} value={value:.6f} "
|
||||
f"median={batch_median:.6f} regression={regression * 100:.1f}%")
|
||||
|
||||
worst_source, worst_regression = max(regressions, key=lambda item: item[1])
|
||||
print(f" {policy.key} worst regression: {worst_regression * 100:.1f}% (source={worst_source})")
|
||||
if worst_regression > max_regression:
|
||||
failures.append(
|
||||
f"source artifact {worst_source} {policy.key} regresses by "
|
||||
f"{worst_regression * 100:.1f}% against the batch median")
|
||||
|
||||
if failures:
|
||||
raise ValueError("source batch exceeds maximum intra-batch regression: " + "; ".join(failures))
|
||||
|
||||
|
||||
def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Create reviewed baseline seed records from v2 CALIBRATION_NEEDED artifacts.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--source-result",
|
||||
dest="source_results",
|
||||
action="append",
|
||||
required=True,
|
||||
help="Path to a normalized_perf_*.json artifact. Repeat for multiple reviewed source artifacts.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--intent-rationale",
|
||||
required=True,
|
||||
help="Reviewed reason this calibration artifact should seed the baseline.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--tracking-root",
|
||||
default=TRACKING_ROOT,
|
||||
help=(
|
||||
"Operator tracking-mirror path used only to enforce staging separation; "
|
||||
"remote validation uses a fresh temporary snapshot."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--staging-root",
|
||||
default=STAGING_ROOT,
|
||||
help="Separate local root for prepared seed records.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-intra-batch-regression",
|
||||
type=_nonnegative_finite_float,
|
||||
default=DEFAULT_MAX_INTRA_BATCH_REGRESSION,
|
||||
help="Maximum regression of any source against the batch median (default: 0.05).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--operator",
|
||||
default=os.environ.get("USER"),
|
||||
help="Operator name recorded in seed provenance.",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = _parse_args(argv)
|
||||
_validate_separate_roots(args.tracking_root, args.staging_root)
|
||||
source_records = [_load_json(path) for path in args.source_results]
|
||||
for source_record in source_records:
|
||||
_validate_calibration_source(source_record)
|
||||
_validate_unique_sources(args.source_results, source_records)
|
||||
identity = _validate_same_identity(source_records)
|
||||
with tempfile.TemporaryDirectory(prefix="performance-seed-prepare-remote-") as remote_root:
|
||||
sync_from_hf(remote_root, strict=True)
|
||||
_validate_no_existing_seed(remote_root, source_records[0], source="remote tracking history")
|
||||
_validate_no_existing_seed(args.staging_root, source_records[0], source="local staging")
|
||||
_validate_batch_consistency(source_records, args.max_intra_batch_regression)
|
||||
ordered_sources = _order_sources_by_timestamp(args.source_results, source_records)
|
||||
print("Seeding exact comparable identity:")
|
||||
for key, value in identity.items():
|
||||
print(f" {key}: {value}")
|
||||
|
||||
seed_records = []
|
||||
for index, (source_path, source_record) in enumerate(ordered_sources, start=1):
|
||||
seed_record = build_baseline_seed_record(
|
||||
source_record,
|
||||
reason=args.intent_rationale,
|
||||
source_result=os.path.realpath(os.path.abspath(source_path)),
|
||||
operator=args.operator,
|
||||
batch_size=len(source_records),
|
||||
batch_index=index,
|
||||
)
|
||||
suffix = f"{index:02d}" if len(source_records) > 1 else None
|
||||
seed_records.append((seed_record, suffix))
|
||||
|
||||
reservation = _reserve_staging_identity(args.staging_root, identity)
|
||||
prepared_seeds = [
|
||||
(_seed_record_path(reservation, seed_record, suffix=suffix), seed_record, suffix)
|
||||
for seed_record, suffix in seed_records
|
||||
]
|
||||
prepared_paths = [seed_path for seed_path, _seed_record, _suffix in prepared_seeds]
|
||||
try:
|
||||
for seed_path, seed_record, suffix in prepared_seeds:
|
||||
write_seed_record(reservation, seed_record, suffix=suffix)
|
||||
print(f"Prepared baseline seed: {seed_path}")
|
||||
manifest_path = _write_preparation_manifest(
|
||||
reservation,
|
||||
args.staging_root,
|
||||
identity,
|
||||
args.source_results,
|
||||
source_records,
|
||||
prepared_paths,
|
||||
)
|
||||
except Exception:
|
||||
_release_failed_reservation(reservation, prepared_paths)
|
||||
raise
|
||||
print(f"Reserved exact identity in staging: {reservation}")
|
||||
print(f"Prepared upload manifest: {manifest_path}")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -102,15 +102,22 @@ def test_partial_v2_identity_requires_schema_version():
|
||||
|
||||
|
||||
def test_optional_v2_metadata_fields_must_be_objects():
|
||||
cfg = {
|
||||
"benchmark_id": "wan-t2v-1.3b-2gpu",
|
||||
"config_schema_version": 2,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2,
|
||||
"quality_metadata": ["not", "an", "object"],
|
||||
}
|
||||
cfg = _v2_config()
|
||||
cfg["quality_metadata"] = ["not", "an", "object"]
|
||||
|
||||
expected = "wan.json: optional v2 metadata field 'quality_metadata' must be an object"
|
||||
with pytest.raises(ValueError, match=expected):
|
||||
_validate_benchmark_config(cfg, "wan.json")
|
||||
|
||||
|
||||
def test_regression_thresholds_validate_without_forcing_v2_schema():
|
||||
cfg = {
|
||||
"benchmark_id": "legacy-benchmark",
|
||||
"regression_thresholds": {"latency": {"threshold_percent": 0.1}},
|
||||
}
|
||||
|
||||
_validate_benchmark_config(cfg, "legacy.json")
|
||||
|
||||
cfg["regression_thresholds"] = []
|
||||
with pytest.raises(ValueError, match="benchmark config field 'regression_thresholds' must be an object"):
|
||||
_validate_benchmark_config(cfg, "legacy.json")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -177,6 +177,55 @@ def test_records_and_trends_endpoints_filter_by_model_and_gpu():
|
||||
assert trends["groups"][0]["gpu_type"] == "NVIDIA L40S"
|
||||
|
||||
|
||||
def test_v2_display_filters_keep_renamed_cohort_history():
|
||||
identity = {
|
||||
"result_schema_version": 2,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2,
|
||||
"recipe_fingerprint": "recipe-a",
|
||||
"hardware_profile_id": "hw-l40s",
|
||||
"software_profile_id": "sw-cu130",
|
||||
}
|
||||
app = create_app(FakeStore([
|
||||
_record(
|
||||
"old-display",
|
||||
"NVIDIA L40S old label",
|
||||
"2026-01-01T00:00:00+00:00",
|
||||
"a" * 40,
|
||||
10.0,
|
||||
10.0,
|
||||
run_source="scheduled_main",
|
||||
baseline_eligible=True,
|
||||
**identity,
|
||||
),
|
||||
_record(
|
||||
"new-display",
|
||||
"NVIDIA L40S",
|
||||
"2026-01-02T00:00:00+00:00",
|
||||
"b" * 40,
|
||||
11.0,
|
||||
9.0,
|
||||
**identity,
|
||||
),
|
||||
]))
|
||||
client = TestClient(app)
|
||||
|
||||
filters = {"model_id": "new-display", "gpu_type": "NVIDIA L40S"}
|
||||
summary = client.get("/api/performance/summary", params=filters).json()
|
||||
trends = client.get("/api/performance/trends", params=filters).json()
|
||||
raw_old_records = client.get("/api/performance/records", params={"model_id": "old-display"}).json()
|
||||
stale_display = client.get("/api/performance/summary", params={"model_id": "old-display"}).json()
|
||||
|
||||
assert summary["count"] == 1
|
||||
assert summary["rows"][0]["baseline_n"] == 1
|
||||
assert summary["rows"][0]["metrics"]["latency"]["baseline"] == 10.0
|
||||
assert trends["count"] == 1
|
||||
assert len(trends["groups"][0]["points"]) == 2
|
||||
assert raw_old_records["count"] == 1
|
||||
assert stale_display["count"] == 0
|
||||
|
||||
|
||||
def test_refresh_endpoint_reports_sync_metadata():
|
||||
app = create_app(FakeStore([]))
|
||||
client = TestClient(app)
|
||||
|
||||
@@ -38,24 +38,69 @@ def test_group_data_uses_full_comparison_cohort():
|
||||
groups = list(dashboard.group_data(df))
|
||||
|
||||
assert len(groups) == 2
|
||||
assert {key[5] for key, _group in groups} == {"recipe-a", "recipe-b"}
|
||||
assert {key[7] for key, _group in groups} == {"sw-a", "sw-b"}
|
||||
assert {key[6] for key, _group in groups} == {"recipe-a", "recipe-b"}
|
||||
assert {key[8] for key, _group in groups} == {"sw-a", "sw-b"}
|
||||
|
||||
|
||||
def test_group_data_ignores_v2_display_name_changes():
|
||||
df = pd.DataFrame([
|
||||
_record(model_id="old-display", gpu_type="NVIDIA L40S old label"),
|
||||
_record(
|
||||
model_id="new-display",
|
||||
gpu_type="NVIDIA L40S",
|
||||
timestamp="2026-01-02T00:00:00+00:00",
|
||||
),
|
||||
])
|
||||
|
||||
groups = list(dashboard.group_data(df))
|
||||
figs, _skipped_metrics = dashboard.build_plots(df)
|
||||
|
||||
assert len(groups) == 1
|
||||
assert all("new-display | NVIDIA L40S" in fig.layout.title.text for fig in figs)
|
||||
|
||||
|
||||
def test_group_data_fills_legacy_cohort_columns():
|
||||
df = pd.DataFrame([{
|
||||
"model_id": "legacy-wan",
|
||||
"gpu_type": "NVIDIA L40S",
|
||||
"timestamp": "2026-01-01T00:00:00+00:00",
|
||||
"commit_sha": "a" * 40,
|
||||
"config_id": "aaaaaaa",
|
||||
"latency": 10.0,
|
||||
}])
|
||||
df = pd.DataFrame([
|
||||
{
|
||||
"model_id": model_id,
|
||||
"gpu_type": "NVIDIA L40S",
|
||||
"timestamp": "2026-01-01T00:00:00+00:00",
|
||||
"commit_sha": "a" * 40,
|
||||
"config_id": "aaaaaaa",
|
||||
"latency": 10.0,
|
||||
}
|
||||
for model_id in ("legacy-wan", "legacy-ltx")
|
||||
])
|
||||
|
||||
groups = list(dashboard.group_data(df))
|
||||
|
||||
assert len(groups) == 1
|
||||
assert groups[0][0][2:] == ("", "", "", "", "", "")
|
||||
assert len(groups) == 2
|
||||
assert {key[1] for key, _group in groups} == {"legacy-wan", "legacy-ltx"}
|
||||
assert all(key[3:] == ("", "", "", "", "", "") for key, _group in groups)
|
||||
|
||||
|
||||
def test_group_data_keeps_partial_v2_identity_scoped_by_display_metadata():
|
||||
partial_identity = {
|
||||
"result_schema_version": 2,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2,
|
||||
"recipe_fingerprint": "",
|
||||
"hardware_profile_id": "",
|
||||
"software_profile_id": "",
|
||||
}
|
||||
df = pd.DataFrame([
|
||||
_record(model_id="wan", gpu_type="NVIDIA L40S", **partial_identity),
|
||||
_record(model_id="ltx", gpu_type="NVIDIA H100", **partial_identity),
|
||||
])
|
||||
|
||||
groups = list(dashboard.group_data(df))
|
||||
|
||||
assert len(groups) == 2
|
||||
assert {(key[1], key[2]) for key, _group in groups} == {
|
||||
("wan", "NVIDIA L40S"),
|
||||
("ltx", "NVIDIA H100"),
|
||||
}
|
||||
|
||||
|
||||
def test_build_plots_labels_distinct_cohorts():
|
||||
|
||||
@@ -290,6 +290,103 @@ def test_build_latest_summary_keeps_variant_versions_separate():
|
||||
assert version_2_row["metrics"]["latency"]["baseline"] == 20.0
|
||||
|
||||
|
||||
def test_v2_dashboard_cohort_spans_display_name_changes():
|
||||
identity = {
|
||||
"result_schema_version": 2,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2,
|
||||
"recipe_fingerprint": "recipe-a",
|
||||
"hardware_profile_id": "hw-l40s",
|
||||
"software_profile_id": "sw-cu130",
|
||||
}
|
||||
records = [
|
||||
_record(
|
||||
"2026-01-01T00:00:00+00:00",
|
||||
"a" * 40,
|
||||
10.0,
|
||||
10.0,
|
||||
model_id="old-display-name",
|
||||
gpu_type="NVIDIA L40S old label",
|
||||
run_source="scheduled_main",
|
||||
baseline_eligible=True,
|
||||
**identity,
|
||||
),
|
||||
_record(
|
||||
"2026-01-02T00:00:00+00:00",
|
||||
"b" * 40,
|
||||
11.0,
|
||||
9.0,
|
||||
model_id="new-display-name",
|
||||
gpu_type="NVIDIA L40S",
|
||||
**identity,
|
||||
),
|
||||
]
|
||||
|
||||
rows = build_latest_summary(records)
|
||||
trends = build_trends(records)
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0]["model_id"] == "new-display-name"
|
||||
assert rows[0]["gpu_type"] == "NVIDIA L40S"
|
||||
assert rows[0]["baseline_n"] == 1
|
||||
assert rows[0]["metrics"]["latency"]["baseline"] == 10.0
|
||||
assert len(trends) == 1
|
||||
assert trends[0]["model_id"] == "new-display-name"
|
||||
assert len(trends[0]["points"]) == 2
|
||||
|
||||
|
||||
def test_legacy_dashboard_cohorts_still_use_model_and_gpu():
|
||||
records = [
|
||||
_record("2026-01-01T00:00:00+00:00", "a" * 40, 10.0, 10.0, model_id="wan"),
|
||||
_record("2026-01-02T00:00:00+00:00", "b" * 40, 20.0, 5.0, model_id="ltx"),
|
||||
]
|
||||
|
||||
rows = build_latest_summary(records)
|
||||
trends = build_trends(records)
|
||||
|
||||
assert {row["model_id"] for row in rows} == {"wan", "ltx"}
|
||||
assert len(trends) == 2
|
||||
|
||||
|
||||
def test_partial_v2_identity_does_not_cross_model_or_gpu():
|
||||
partial_identity = {
|
||||
"result_schema_version": 2,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2,
|
||||
}
|
||||
records = [
|
||||
_record(
|
||||
"2026-01-01T00:00:00+00:00",
|
||||
"a" * 40,
|
||||
10.0,
|
||||
10.0,
|
||||
model_id="wan",
|
||||
gpu_type="NVIDIA L40S",
|
||||
**partial_identity,
|
||||
),
|
||||
_record(
|
||||
"2026-01-02T00:00:00+00:00",
|
||||
"b" * 40,
|
||||
20.0,
|
||||
5.0,
|
||||
model_id="ltx",
|
||||
gpu_type="NVIDIA H100",
|
||||
**partial_identity,
|
||||
),
|
||||
]
|
||||
|
||||
rows = build_latest_summary(records)
|
||||
trends = build_trends(records)
|
||||
|
||||
assert {(row["model_id"], row["gpu_type"]) for row in rows} == {
|
||||
("wan", "NVIDIA L40S"),
|
||||
("ltx", "NVIDIA H100"),
|
||||
}
|
||||
assert len(trends) == 2
|
||||
|
||||
|
||||
def test_dashboard_identity_preserves_zero_benchmark_version():
|
||||
records = [
|
||||
_record(
|
||||
|
||||
@@ -79,6 +79,7 @@ def test_same_config_produces_same_recipe_fingerprint():
|
||||
def test_recipe_includes_first_class_benchmark_identity():
|
||||
recipe = build_recipe_from_benchmark_config(_benchmark_config())
|
||||
|
||||
assert recipe["recipe_schema_version"] == identity_module.RECIPE_SCHEMA_VERSION == 2
|
||||
assert recipe["benchmark"] == {
|
||||
"benchmark_id": "wan-t2v-1.3b-2gpu",
|
||||
"workload_id": "wan-t2v",
|
||||
|
||||
@@ -52,9 +52,9 @@ V2_REQUIRED_IDENTITY_FIELDS = (
|
||||
# declaring it now fails validation loudly instead of being silently
|
||||
# overwritten by the generated one.
|
||||
V2_OPTIONAL_METADATA_FIELDS = (
|
||||
"metric_threshold_policy",
|
||||
"quality_metadata",
|
||||
)
|
||||
COMMON_OBJECT_FIELDS = ("regression_thresholds",)
|
||||
RESULT_SCHEMA_VERSION = 2
|
||||
VALID_RUN_SOURCES = {"pr", "local", "scheduled_main", "unknown"}
|
||||
OPTIONAL_RESULT_METADATA_FIELDS = ("quality_metadata", "variant_metadata")
|
||||
@@ -96,6 +96,10 @@ def _validate_benchmark_config(cfg, path="<memory>"):
|
||||
if missing_common:
|
||||
raise ValueError(f"{path}: missing required benchmark config fields: {', '.join(missing_common)}")
|
||||
|
||||
for field in COMMON_OBJECT_FIELDS:
|
||||
if field in cfg and not isinstance(cfg[field], Mapping):
|
||||
raise ValueError(f"{path}: benchmark config field {field!r} must be an object")
|
||||
|
||||
schema_version = cfg.get("config_schema_version")
|
||||
if schema_version is None:
|
||||
if _has_v2_fields(cfg):
|
||||
@@ -245,6 +249,45 @@ def _validate_run_counts(run_config: Mapping[str, Any], benchmark_id: str) -> tu
|
||||
return num_warmup, num_measure
|
||||
|
||||
|
||||
def _resolve_num_gpus(
|
||||
init_kwargs: Mapping[str, Any],
|
||||
run_config: Mapping[str, Any],
|
||||
benchmark_id: str,
|
||||
) -> int:
|
||||
init_num_gpus = init_kwargs.get("num_gpus")
|
||||
required_gpus = run_config.get("required_gpus")
|
||||
for field, value in (
|
||||
("init_kwargs.num_gpus", init_num_gpus),
|
||||
("run_config.required_gpus", required_gpus),
|
||||
):
|
||||
if value is not None and (
|
||||
isinstance(value, bool) or not isinstance(value, int) or value < 1):
|
||||
raise ValueError(f"{benchmark_id}: {field} must be a positive integer")
|
||||
parallel_sizes = []
|
||||
for field in ("tp_size", "sp_size"):
|
||||
value = init_kwargs.get(field)
|
||||
if value is None or value == -1:
|
||||
continue
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
||||
raise ValueError(f"{benchmark_id}: init_kwargs.{field} must be -1 or a positive integer")
|
||||
parallel_sizes.append(value)
|
||||
if (
|
||||
init_num_gpus is not None
|
||||
and required_gpus is not None
|
||||
and init_num_gpus != required_gpus
|
||||
):
|
||||
raise ValueError(
|
||||
f"{benchmark_id}: init_kwargs.num_gpus ({init_num_gpus}) must match "
|
||||
f"run_config.required_gpus ({required_gpus})")
|
||||
declared_num_gpus = init_num_gpus or required_gpus
|
||||
parallel_num_gpus = max(parallel_sizes, default=1)
|
||||
if declared_num_gpus is not None and declared_num_gpus < parallel_num_gpus:
|
||||
raise ValueError(
|
||||
f"{benchmark_id}: declared GPU count ({declared_num_gpus}) must be at least "
|
||||
f"max(tp_size, sp_size) ({parallel_num_gpus})")
|
||||
return declared_num_gpus or parallel_num_gpus
|
||||
|
||||
|
||||
def _write_results(results):
|
||||
"""Write JSON results to the results directory."""
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
@@ -339,15 +382,31 @@ def _build_identity_fields(cfg, init_kwargs, prompt, runtime_identity):
|
||||
# identity fields, so v2 records always get the full identity block.
|
||||
if cfg.get("config_schema_version") is None:
|
||||
return {}
|
||||
run_config = cfg.get("run_config") or {}
|
||||
num_gpus = _resolve_num_gpus(init_kwargs, run_config, cfg["benchmark_id"])
|
||||
recipe_cfg = dict(cfg)
|
||||
recipe_cfg["init_kwargs"] = {
|
||||
**dict(init_kwargs),
|
||||
"num_gpus": num_gpus,
|
||||
}
|
||||
recipe = build_recipe_from_benchmark_config(
|
||||
cfg,
|
||||
recipe_cfg,
|
||||
resolved_attention_backend=runtime_identity.get("resolved_attention_backend"),
|
||||
resolved_model_revision=runtime_identity.get("resolved_model_revision"),
|
||||
measured_prompts=[prompt],
|
||||
)
|
||||
num_gpus = init_kwargs.get("num_gpus", cfg.get("run_config", {}).get("required_gpus", 1))
|
||||
hw_profile = hardware_profile(num_gpus=num_gpus)
|
||||
sw_profile = software_profile()
|
||||
sw_profile.update({
|
||||
"attention_backend": os.environ.get("FASTVIDEO_ATTENTION_BACKEND") or "auto",
|
||||
"flash_attention_4_enabled": os.environ.get("FASTVIDEO_FA4", "0") != "0",
|
||||
})
|
||||
performance_profile_version = os.environ.get("FASTVIDEO_PERFORMANCE_PROFILE_VERSION")
|
||||
if performance_profile_version:
|
||||
sw_profile["performance_profile_version"] = performance_profile_version
|
||||
image_version = os.environ.get("IMAGE_VERSION")
|
||||
if image_version:
|
||||
sw_profile["container_image_version"] = image_version
|
||||
env_metadata = environment_metadata(
|
||||
hardware=hw_profile,
|
||||
software=sw_profile,
|
||||
@@ -424,6 +483,7 @@ def _build_result_record(
|
||||
) -> dict[str, Any]:
|
||||
if not times or not peak_memories:
|
||||
raise ValueError("Cannot build a performance result record without measurement runs")
|
||||
num_gpus = _resolve_num_gpus(init_kwargs, cfg.get("run_config") or {}, cfg["benchmark_id"])
|
||||
avg_time = sum(times) / len(times)
|
||||
max_peak_memory = max(peak_memories)
|
||||
num_frames = gen_kwargs.get("num_frames")
|
||||
@@ -431,12 +491,18 @@ def _build_result_record(
|
||||
if isinstance(num_frames, (int, float)) and avg_time > 0:
|
||||
throughput_fps = num_frames / avg_time
|
||||
|
||||
result_schema_fields = (
|
||||
{"result_schema_version": RESULT_SCHEMA_VERSION}
|
||||
if _is_v2_config(cfg)
|
||||
else {}
|
||||
)
|
||||
|
||||
return {
|
||||
"benchmark_id": cfg["benchmark_id"],
|
||||
"result_schema_version": RESULT_SCHEMA_VERSION,
|
||||
**result_schema_fields,
|
||||
"model_short_name": model_info.get("model_short_name", ""),
|
||||
"device": device_name,
|
||||
"num_gpus": init_kwargs.get("num_gpus", 1),
|
||||
"num_gpus": num_gpus,
|
||||
"num_warmup_runs": num_warmup,
|
||||
"num_measurement_runs": num_measure,
|
||||
"avg_generation_time_s": round(avg_time, 3),
|
||||
@@ -463,14 +529,16 @@ def _build_result_record(
|
||||
# -- Test -------------------------------------------------------------------
|
||||
|
||||
def _run_benchmark(cfg):
|
||||
run_config = cfg.get("run_config", {})
|
||||
required_gpus = run_config.get("required_gpus", 1)
|
||||
available = torch.cuda.device_count()
|
||||
if available < required_gpus:
|
||||
pytest.skip(f"Need {required_gpus} GPUs, only {available} available")
|
||||
|
||||
run_config = cfg.get("run_config") or {}
|
||||
model_info = cfg["model"]
|
||||
init_kwargs = dict(cfg.get("init_kwargs", {}))
|
||||
num_gpus = _resolve_num_gpus(init_kwargs, run_config, cfg["benchmark_id"])
|
||||
init_kwargs["num_gpus"] = num_gpus
|
||||
|
||||
available = torch.cuda.device_count()
|
||||
if available < num_gpus:
|
||||
pytest.skip(f"Need {num_gpus} GPUs, only {available} available")
|
||||
|
||||
gen_kwargs = dict(cfg.get("generation_kwargs", {}))
|
||||
prompts = cfg.get("test_prompts", ["A cinematic video."])
|
||||
prompt = prompts[0]
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import copy
|
||||
|
||||
from fastvideo.tests.performance import compare_baseline
|
||||
from fastvideo.tests.performance import test_inference_performance as perf
|
||||
|
||||
|
||||
def _benchmark_config():
|
||||
return {
|
||||
"benchmark_id": "wan-t2v-1.3b-2gpu",
|
||||
"config_schema_version": perf.V2_CONFIG_SCHEMA_VERSION,
|
||||
"workload_id": "wan-t2v-1.3b",
|
||||
"variant_id": "canonical",
|
||||
"benchmark_version": 1,
|
||||
"model": {
|
||||
"model_path": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
||||
"model_short_name": "Wan2.1-T2V-1.3B",
|
||||
},
|
||||
"init_kwargs": {
|
||||
"num_gpus": 2,
|
||||
"flow_shift": 7.0,
|
||||
"sp_size": 2,
|
||||
"tp_size": 1,
|
||||
"vae_sp": True,
|
||||
"vae_tiling": True,
|
||||
"text_encoder_precisions": ["fp32"],
|
||||
},
|
||||
"generation_kwargs": {
|
||||
"height": 480,
|
||||
"width": 832,
|
||||
"num_frames": 45,
|
||||
"num_inference_steps": 4,
|
||||
"guidance_scale": 3,
|
||||
"embedded_cfg_scale": 6,
|
||||
"seed": 1024,
|
||||
"fps": 24,
|
||||
"neg_prompt": "low quality",
|
||||
},
|
||||
"run_config": {
|
||||
"num_warmup_runs": 2,
|
||||
"num_measurement_runs": 5,
|
||||
"required_gpus": 2,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_performance_producer_emits_v2_identity_from_raw_result_shape(monkeypatch):
|
||||
monkeypatch.setenv("FASTVIDEO_ATTENTION_BACKEND", "FLASH_ATTN")
|
||||
cfg = _benchmark_config()
|
||||
init_kwargs = dict(cfg["init_kwargs"])
|
||||
cfg["generation_kwargs"]["output_path"] = "/tmp/generated"
|
||||
prompt = "A cinematic video."
|
||||
|
||||
identity_fields = perf._build_identity_fields(
|
||||
cfg,
|
||||
init_kwargs,
|
||||
prompt,
|
||||
{
|
||||
"resolved_attention_backend": "FLASH_ATTN",
|
||||
"resolved_model_revision": None,
|
||||
},
|
||||
)
|
||||
raw_result = {
|
||||
"benchmark_id": cfg["benchmark_id"],
|
||||
"model_short_name": cfg["model"]["model_short_name"],
|
||||
"device": "NVIDIA L40S PCIe",
|
||||
"num_gpus": init_kwargs["num_gpus"],
|
||||
"num_warmup_runs": 2,
|
||||
"num_measurement_runs": 5,
|
||||
"avg_generation_time_s": 10.0,
|
||||
"individual_times_s": [10.0],
|
||||
"throughput_fps": 4.5,
|
||||
"max_peak_memory_mb": 10000.0,
|
||||
"individual_peak_memories_mb": [10000.0],
|
||||
"thresholds": {},
|
||||
"commit": "a" * 40,
|
||||
"pr_number": "123",
|
||||
"timestamp": "2026-06-16T00:00:00+00:00",
|
||||
"text_encoder_time_s": 1.0,
|
||||
"dit_time_s": 2.0,
|
||||
"vae_decode_time_s": 3.0,
|
||||
**identity_fields,
|
||||
}
|
||||
|
||||
record = compare_baseline.normalize_performance_result(raw_result)
|
||||
|
||||
assert record["workload_id"] == "wan-t2v-1.3b"
|
||||
assert record["variant_id"] == "canonical"
|
||||
assert record["benchmark_version"] == 1
|
||||
assert record["hardware_profile_id"].startswith("hw-")
|
||||
assert record["software_profile_id"].startswith("sw-")
|
||||
assert record["software_profile_id"] == perf.software_profile_id(record["software_profile"])
|
||||
assert len(record["recipe_fingerprint"]) == 64
|
||||
assert "output_path" not in record["recipe"]["generation_kwargs"]
|
||||
|
||||
|
||||
def test_display_benchmark_id_rename_preserves_producer_fingerprint_and_cohort(monkeypatch):
|
||||
monkeypatch.setenv("FASTVIDEO_ATTENTION_BACKEND", "FLASH_ATTN")
|
||||
original = _benchmark_config()
|
||||
renamed = copy.deepcopy(original)
|
||||
renamed["benchmark_id"] = "wan-t2v-renamed-display-id"
|
||||
|
||||
def build_identity(cfg):
|
||||
return perf._build_identity_fields(
|
||||
cfg,
|
||||
dict(cfg["init_kwargs"]),
|
||||
"A cinematic video.",
|
||||
{
|
||||
"resolved_attention_backend": "FLASH_ATTN",
|
||||
"resolved_model_revision": None,
|
||||
},
|
||||
)
|
||||
|
||||
original_identity = build_identity(original)
|
||||
renamed_identity = build_identity(renamed)
|
||||
|
||||
assert original_identity["recipe"]["benchmark"]["benchmark_id"] == original["benchmark_id"]
|
||||
assert renamed_identity["recipe"]["benchmark"]["benchmark_id"] == renamed["benchmark_id"]
|
||||
assert original_identity["recipe_fingerprint"] == renamed_identity["recipe_fingerprint"]
|
||||
assert compare_baseline._comparison_identity_filters(
|
||||
original_identity) == compare_baseline._comparison_identity_filters(renamed_identity)
|
||||
|
||||
|
||||
def test_v2_identity_tolerates_null_run_config(monkeypatch):
|
||||
monkeypatch.setenv("FASTVIDEO_ATTENTION_BACKEND", "FLASH_ATTN")
|
||||
cfg = _benchmark_config()
|
||||
cfg["run_config"] = None
|
||||
init_kwargs = dict(cfg["init_kwargs"])
|
||||
|
||||
identity_fields = perf._build_identity_fields(
|
||||
cfg,
|
||||
init_kwargs,
|
||||
"A cinematic video.",
|
||||
{
|
||||
"resolved_attention_backend": "FLASH_ATTN",
|
||||
"resolved_model_revision": None,
|
||||
},
|
||||
)
|
||||
|
||||
assert identity_fields["hardware_profile"]["gpu_count"] == 2
|
||||
|
||||
|
||||
def test_effective_gpu_count_is_recorded_in_recipe_and_hardware(monkeypatch):
|
||||
monkeypatch.setenv("FASTVIDEO_ATTENTION_BACKEND", "FLASH_ATTN")
|
||||
cfg = _benchmark_config()
|
||||
del cfg["init_kwargs"]["num_gpus"]
|
||||
init_kwargs = dict(cfg["init_kwargs"])
|
||||
|
||||
identity_fields = perf._build_identity_fields(
|
||||
cfg,
|
||||
init_kwargs,
|
||||
"A cinematic video.",
|
||||
{
|
||||
"resolved_attention_backend": "FLASH_ATTN",
|
||||
"resolved_model_revision": None,
|
||||
},
|
||||
)
|
||||
|
||||
assert identity_fields["recipe"]["init_kwargs"]["num_gpus"] == 2
|
||||
assert identity_fields["hardware_profile"]["gpu_count"] == 2
|
||||
|
||||
|
||||
def test_producer_tracks_runtime_software_identity_and_container_audit(monkeypatch):
|
||||
base_profile = {
|
||||
"python": "3.12",
|
||||
"pytorch": "2.7",
|
||||
"cuda": "12.8",
|
||||
"packages": {
|
||||
"fastvideo_kernel": "0.3.2",
|
||||
"triton": "3.2.1",
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(perf, "software_profile", lambda: dict(base_profile))
|
||||
monkeypatch.setenv("FASTVIDEO_ATTENTION_BACKEND", "SAGE_ATTN")
|
||||
monkeypatch.setenv("FASTVIDEO_FA4", "1")
|
||||
monkeypatch.setenv("FASTVIDEO_PERFORMANCE_PROFILE_VERSION", "perf-profile-v2")
|
||||
monkeypatch.setenv("IMAGE_VERSION", "py3.12-cuda13.0")
|
||||
monkeypatch.setenv(
|
||||
"FASTVIDEO_CONTAINER_IMAGE_REF",
|
||||
"ghcr.io/hao-ai-lab/fastvideo/fastvideo-dev@sha256:abc",
|
||||
)
|
||||
|
||||
cfg = _benchmark_config()
|
||||
identity_fields = perf._build_identity_fields(
|
||||
cfg,
|
||||
dict(cfg["init_kwargs"]),
|
||||
"A cinematic video.",
|
||||
{
|
||||
"resolved_attention_backend": "SAGE_ATTN",
|
||||
"resolved_model_revision": None,
|
||||
},
|
||||
)
|
||||
|
||||
expected_profile = {
|
||||
**base_profile,
|
||||
"attention_backend": "SAGE_ATTN",
|
||||
"flash_attention_4_enabled": True,
|
||||
"performance_profile_version": "perf-profile-v2",
|
||||
"container_image_version": "py3.12-cuda13.0",
|
||||
}
|
||||
assert identity_fields["software_profile"] == expected_profile
|
||||
assert identity_fields["software_profile_id"] == perf.software_profile_id(expected_profile)
|
||||
assert identity_fields["environment_metadata"]["env"]["FASTVIDEO_CONTAINER_IMAGE_REF"].endswith(
|
||||
"sha256:abc"
|
||||
)
|
||||
|
||||
first_profile_id = identity_fields["software_profile_id"]
|
||||
monkeypatch.setenv(
|
||||
"FASTVIDEO_CONTAINER_IMAGE_REF",
|
||||
"ghcr.io/hao-ai-lab/fastvideo/fastvideo-dev@sha256:def",
|
||||
)
|
||||
changed_audit = perf._build_identity_fields(
|
||||
cfg,
|
||||
dict(cfg["init_kwargs"]),
|
||||
"A cinematic video.",
|
||||
{
|
||||
"resolved_attention_backend": "SAGE_ATTN",
|
||||
"resolved_model_revision": None,
|
||||
},
|
||||
)
|
||||
assert changed_audit["software_profile_id"] == first_profile_id
|
||||
assert changed_audit["environment_metadata"]["env"]["FASTVIDEO_CONTAINER_IMAGE_REF"].endswith(
|
||||
"sha256:def"
|
||||
)
|
||||
|
||||
monkeypatch.setenv("FASTVIDEO_FA4", "0")
|
||||
changed_runtime = perf._build_identity_fields(
|
||||
cfg,
|
||||
dict(cfg["init_kwargs"]),
|
||||
"A cinematic video.",
|
||||
{
|
||||
"resolved_attention_backend": "SAGE_ATTN",
|
||||
"resolved_model_revision": None,
|
||||
},
|
||||
)
|
||||
assert changed_runtime["software_profile_id"] != first_profile_id
|
||||
@@ -8,6 +8,7 @@ from fastvideo.tests.performance import test_inference_performance as perf_test
|
||||
def _benchmark_config():
|
||||
return {
|
||||
"benchmark_id": "wan-t2v-1.3b-2gpu",
|
||||
"config_schema_version": perf_test.V2_CONFIG_SCHEMA_VERSION,
|
||||
"workload_id": "wan-t2v",
|
||||
"variant_id": "1.3b-sp2",
|
||||
"benchmark_version": 2,
|
||||
@@ -155,6 +156,33 @@ def test_validate_run_counts_returns_defaults():
|
||||
assert perf_test._validate_run_counts({}, "wan-t2v-1.3b-2gpu") == (1, 3)
|
||||
|
||||
|
||||
def test_resolve_num_gpus_uses_one_count_and_rejects_conflicts():
|
||||
assert perf_test._resolve_num_gpus(
|
||||
{},
|
||||
{"required_gpus": 2},
|
||||
"wan-t2v-1.3b-2gpu",
|
||||
) == 2
|
||||
assert perf_test._resolve_num_gpus(
|
||||
{"tp_size": 2},
|
||||
{},
|
||||
"wan-t2v-1.3b-tp2",
|
||||
) == 2
|
||||
|
||||
with pytest.raises(ValueError, match="must match"):
|
||||
perf_test._resolve_num_gpus(
|
||||
{"num_gpus": 1},
|
||||
{"required_gpus": 2},
|
||||
"wan-t2v-1.3b-2gpu",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match=r"at least max\(tp_size, sp_size\)"):
|
||||
perf_test._resolve_num_gpus(
|
||||
{"num_gpus": 1, "tp_size": 2},
|
||||
{"required_gpus": 1},
|
||||
"wan-t2v-1.3b-tp2",
|
||||
)
|
||||
|
||||
|
||||
def test_build_result_record_rejects_empty_measurements(monkeypatch):
|
||||
monkeypatch.setattr(perf_test, "_build_identity_fields", lambda *_args: _identity_fields())
|
||||
|
||||
|
||||
Reference in New Issue
Block a user