Skip to content
80 changes: 80 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,83 @@ All contributions are expected to demonstrate:
- Evidence of real-world usage or hands-on experience with the problem

If these expectations are not met, we would prefer to implement the changes ourselves rather than spend time reviewing low-effort submissions.

## What to fill in

| Your change touches | 1. Problem | 2. Tests to run | 3. Speed |
|---|---|---|---|
| Docs only | N/A | N/A | N/A |
| Anything else (toolchain, CI, tests, examples) | required | N/A | N/A |
| `src/` | required | `./mfc.sh test --select-enforce` | required |
| Build flags or compiler versions (`CMakeLists.txt`, `cmake/`, `toolchain/cmake/`, `toolchain/modules`) | required | `./mfc.sh test` | required |

If more than one row applies, do everything each of them requires. Write N/A with a reason; don't leave blanks.

## 1. Does it solve the problem?

Show before and after with numbers, figures, or both. Delete what you don't use.

Command that shows it:

| Quantity | master | this PR | expected |
|---|---|---|---|
| | | | |

| Figure: master | Figure: this PR |
|---|---|
| | |

Why the new result is right (analytic solution, reference data, convergence, ...):

## 2. Does it create another one?

| Check | Result |
|---|---|
| Tests: command, number passed, number failed | |
| Golden files changed: count, largest difference, why | |
| Not tested | |

## 3. Is it slower?

Required for `src/` and build changes: you must benchmark your base commit and your PR on the same GPU, and report which GPU it is.
Any supported GPU will do. If you have no access to one, say so here.

GPU and compiler:

Base commit:

PR commit:

<!-- Paste build/speed.md here -->

Explain any grind speedup below 0.95 that shows up twice. If no benchmark case uses your change, add master and PR grind times for a case that does.

<details>
<summary>Commands</summary>

```bash
# Run inside a GPU job with your compiler loaded (supported clusters: source ./mfc.sh load -c <slug> -m g).
(
set -e # stop at the first failure
rm -f build/speed.md
git diff --quiet HEAD || { echo "Commit your changes first."; exit 1; }
git fetch https://github.com/MFlowCode/MFC.git master
base=$(git merge-base FETCH_HEAD HEAD) || { echo "No commit shared with master. Shallow clone? Run: git fetch --unshallow"; exit 1; }
base=$(git rev-parse --short $base)
[ $base != $(git rev-parse --short HEAD) ] || { echo "Nothing to compare: your commit is already in master."; exit 1; }
[ -d ../mfc-$base ] || git worktree add --detach ../mfc-$base $base
ngpus=1 # GPUs to use, one MPI rank each. To pick which ones, add -g <ids> to the bench line.

# NVIDIA or Cray: --gpu acc. AMD flang: --gpu mp. On a cluster, add -c <computer> after "--".
for tree in ../mfc-$base .; do
(cd $tree &&
./mfc.sh build --gpu acc -j 8 &&
./mfc.sh bench --mem 4 -o build/bench.yaml -- --gpu acc -n $ngpus)
done

GITHUB_STEP_SUMMARY=build/speed.md ./mfc.sh bench_diff ../mfc-$base/build/bench.yaml build/bench.yaml
echo "Base commit: $base"; echo "PR commit: $(git rev-parse --short HEAD)"
)
```

</details>
69 changes: 25 additions & 44 deletions toolchain/mfc/bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import rich.table

from .build import DEFAULT_TARGETS, SIMULATION, get_targets
from .build import SIMULATION, get_targets
from .common import MFC_BENCH_FILEPATH, MFC_BUILD_DIR, MFCException, console_safe, create_directory, file_dump_yaml, file_load_yaml, format_list_to_string, log_tail, system
from .gpu_diagnostics import fault_diagnostic_env, summarize_rocm_debug_agent
from .printer import cons
Expand Down Expand Up @@ -193,7 +193,7 @@ def bench(targets=None):
cons.unindent()


def _write_step_summary(lhs_path: str, rhs_path: str, rows: typing.List[typing.Tuple[str, str, str, str]], warnings: typing.List[str]):
def _write_step_summary(lhs_path: str, rhs_path: str, rows: typing.List[typing.Tuple[str, str]], warnings: typing.List[str]):
"""Put the speedup table on the workflow run's summary page.

The same numbers already go to stdout, but reading them there means expanding the
Expand All @@ -212,12 +212,12 @@ def _write_step_summary(lhs_path: str, rhs_path: str, rows: typing.List[typing.T
lines = [
heading,
"",
f"Speedups from `{lhs_path}` to `{rhs_path}`; greater than 1 is faster.",
f"Grind time speedups from `{lhs_path}` to `{rhs_path}`; greater than 1 is faster.",
"",
"| Case | Pre Process | Simulation | Post Process |",
"| --- | --- | --- | --- |",
"| Case | Grind speedup |",
"| --- | --- |",
]
lines += [f"| `{slug}` | {pre} | {sim} | {post} |" for slug, pre, sim, post in rows]
lines += [f"| `{slug}` | {speedup} |" for slug, speedup in rows]
if warnings:
lines += ["", "**Below threshold**", ""] + [f"- {w}" for w in warnings]
lines.append("")
Expand All @@ -236,9 +236,7 @@ def diff():
lhs, rhs = file_load_yaml(ARG("lhs")), file_load_yaml(ARG("rhs"))
lhs_path = os.path.relpath(ARG("lhs"))
rhs_path = os.path.relpath(ARG("rhs"))
cons.print(
f"[bold]Comparing Benchmarks: Speedups from [magenta]{lhs_path}[/magenta] to [magenta]{rhs_path}[/magenta] are displayed below. Thus, numbers > 1 represent increases in performance.[/bold]"
)
cons.print(f"[bold]Comparing Benchmarks: Grind time speedups from [magenta]{lhs_path}[/magenta] to [magenta]{rhs_path}[/magenta] are displayed below; numbers > 1 are faster.[/bold]")

if lhs["metadata"] != rhs["metadata"]:

Expand Down Expand Up @@ -267,48 +265,31 @@ def _lock_to_str(lock):

table = rich.table.Table(show_header=True, box=rich.table.box.SIMPLE)
table.add_column("[bold]Case[/bold]", justify="left")
table.add_column("[bold]Pre Process[/bold]", justify="right")
table.add_column("[bold]Simulation[/bold]", justify="right")
table.add_column("[bold]Post Process[/bold]", justify="right")
table.add_column("[bold]Grind speedup[/bold]", justify="right")

err = 0
summary_rows = []
warnings = []
for slug in slugs:
lhs_summary, rhs_summary = lhs["cases"][slug]["output_summary"], rhs["cases"][slug]["output_summary"]
speedups = ["N/A", "N/A", "N/A"]
speedup = "N/A"

for i, target in enumerate(sorted(DEFAULT_TARGETS, key=lambda t: t.runOrder)):
if (target.name not in lhs_summary) or (target.name not in rhs_summary):
cons.print(f"{target.name} not present in lhs_summary or rhs_summary - Case: {slug}")
try:
lhs_grind, rhs_grind = (side["cases"][slug]["output_summary"][SIMULATION.name]["grind"] for side in (lhs, rhs))
if not math.isfinite(lhs_grind) or not math.isfinite(rhs_grind):
err = 1
continue

if not math.isfinite(lhs_summary[target.name]["exec"]) or not math.isfinite(rhs_summary[target.name]["exec"]):
err = 1
cons.print(f"lhs_summary or rhs_summary reports non-real exec time for {target.name} - Case: {slug}")
try:
exec_time_value = lhs_summary[target.name]["exec"] / rhs_summary[target.name]["exec"]
if exec_time_value < 0.9:
cons.print(f"[bold yellow]Warning[/bold yellow]: Exec time speedup for {target.name} is less than 0.9 - Case: {slug}")
warnings.append(f"exec speedup {exec_time_value:.2f} < 0.90 for {target.name} in `{slug}`")
speedups[i] = f"Exec: {exec_time_value:.2f}"
if target == SIMULATION:
if not math.isfinite(lhs_summary[target.name]["grind"]) or not math.isfinite(rhs_summary[target.name]["grind"]):
err = 1
cons.print(f"lhs_summary or rhs_summary reports non-real grind time for {target.name} - Case: {slug}")

grind_time_value = lhs_summary[target.name]["grind"] / rhs_summary[target.name]["grind"]
speedups[i] += f" & Grind: {grind_time_value:.2f}"
if grind_time_value < 0.95:
cons.print(f"[bold yellow]Warning[/bold yellow]: Grind time speedup for {target.name} below threshold (<0.95) - Case: {slug}")
warnings.append(f"grind speedup {grind_time_value:.2f} < 0.95 for {target.name} in `{slug}`")
except Exception as e:
cons.print(f"[bold red]ERROR[/bold red]: Failed to compute speedup for {target.name} in {slug}: {e}\n{traceback.format_exc()}")
err = 1

table.add_row(f"[magenta]{slug}[/magenta]", *speedups)
summary_rows.append((slug, *speedups))
cons.print(f"lhs_summary or rhs_summary reports non-real grind time - Case: {slug}")

ratio = lhs_grind / rhs_grind
speedup = f"{ratio:.2f}"
if ratio < 0.95:
cons.print(f"[bold yellow]Warning[/bold yellow]: Grind time speedup below threshold (<0.95) - Case: {slug}")
warnings.append(f"grind speedup {ratio:.2f} < 0.95 in `{slug}`")
except Exception as e:
cons.print(f"[bold red]ERROR[/bold red]: Failed to compute grind speedup in {slug}: {e!r}\n{traceback.format_exc()}")
err = 1

table.add_row(f"[magenta]{slug}[/magenta]", speedup)
summary_rows.append((slug, speedup))

cons.raw.print(table)
_write_step_summary(lhs_path, rhs_path, summary_rows, warnings)
Expand Down
68 changes: 68 additions & 0 deletions toolchain/mfc/test_bench_diff.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
"""bench_diff compares simulation grind time and nothing else.

Execution times and pre_process/post_process timings bury the one number a
reviewer needs, so they are neither shown, warned about, nor required.
"""

import pytest
import yaml

from mfc import state
from mfc.bench import diff
from mfc.common import MFCException


def _results(tmp_path, name, cases):
path = tmp_path / f"{name}.yaml"
path.write_text(yaml.safe_dump({"metadata": {"invocation": ["bench"], "lock": {}}, "cases": {slug: {"output_summary": s} for slug, s in cases.items()}}))
return str(path)


def _diff(tmp_path, monkeypatch, lhs, rhs):
summary = tmp_path / "summary.md"
monkeypatch.setenv("GITHUB_STEP_SUMMARY", str(summary))
monkeypatch.setitem(state.gARG, "lhs", _results(tmp_path, "lhs", lhs))
monkeypatch.setitem(state.gARG, "rhs", _results(tmp_path, "rhs", rhs))
diff()
return summary.read_text()


def _all_targets(grind, exec_time):
return {"pre_process": {"exec": exec_time}, "simulation": {"exec": exec_time, "grind": grind}, "post_process": {"exec": exec_time}}


def test_reports_only_grind_speedup(tmp_path, monkeypatch, capsys):
text = _diff(tmp_path, monkeypatch, {"ibm": _all_targets(3.0, 1.0)}, {"ibm": _all_targets(2.0, 1.0)})

assert "| Case | Grind speedup |" in text
assert "| `ibm` | 1.50 |" in text
printed = capsys.readouterr().out
for unwanted in ("Exec", "Pre Process", "Post Process"):
assert unwanted not in text
assert unwanted not in printed


def test_slower_exec_time_alone_does_not_warn(tmp_path, monkeypatch):
text = _diff(tmp_path, monkeypatch, {"ibm": _all_targets(3.0, 1.0)}, {"ibm": _all_targets(3.0, 9.0)})

assert "Below threshold" not in text


def test_slower_grind_time_warns(tmp_path, monkeypatch):
text = _diff(tmp_path, monkeypatch, {"ibm": _all_targets(3.0, 1.0)}, {"ibm": _all_targets(4.0, 1.0)})

assert "grind speedup 0.75 < 0.95 in `ibm`" in text


def test_needs_only_the_simulation_summary(tmp_path, monkeypatch):
simulation_only = {"simulation": {"grind": 3.0}}

text = _diff(tmp_path, monkeypatch, {"ibm": simulation_only}, {"ibm": simulation_only})

assert "| `ibm` | 1.00 |" in text


@pytest.mark.parametrize("broken", [{}, {"simulation": {}}, {"simulation": {"grind": float("nan")}}])
def test_missing_or_non_finite_grind_time_fails(tmp_path, monkeypatch, broken):
with pytest.raises(MFCException):
_diff(tmp_path, monkeypatch, {"ibm": _all_targets(3.0, 1.0)}, {"ibm": broken})
Loading