Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/pytorchsim_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ jobs:
- tests/ops/misc/test_widen_dtype.py
- tests/ops/reduce/test_batchnorm.py
- tests/ops/view/test_view3D_2D.py
- tests/system/test_bundle_reuse.py
- tests/system/test_compiler_failure.py
- tests/system/test_eager.py
- tests/system/test_patch_scope.py
Expand Down
24 changes: 13 additions & 11 deletions .github/workflows/pytorchsim_triton_backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ on:
- 'scripts/ci/triton_route_*'
- 'scripts/ci/bundle.py'
- 'scripts/ci/ptb_bundle_pr.sh'
- 'scripts/ci/previous_picks.sh'
- 'scripts/ci/previous_bundle.sh'
- '.github/workflows/pytorchsim_triton_backend.yml'
workflow_dispatch:
inputs:
Expand Down Expand Up @@ -241,34 +241,36 @@ jobs:
printf %s "$TOKEN" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
- name: Pull the base image
run: docker pull "$BASE_IMAGE"
# The record the last bundle on the branch left: a config it holds is taken without timing it.
- name: Previous picks
# The last bundle on the branch, its record and its kernels: a config the record holds is taken without
# timing it, and a workload whose key it holds is copied without building it.
- name: Previous bundle
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
run: rm -rf picks && bash scripts/ci/previous_picks.sh picks
run: rm -rf picks prev && bash scripts/ci/previous_bundle.sh picks prev
# The GEMMs and the layer (its projections are mm templates) in timing mode, their configs picked by
# TOGSim cycles where the record has none, beside the other suites without it: three runs, since a
# process keeps the timing mode it started in. The GEMMs build in four processes, largest first. The
# layer, only its rows under the compiler's CI cap, builds in four processes (87 min measured, against ~3.8 h in one: its prefill at S 4096 alone is ~85 min).
# The record, with this run's picks folded in, is uploaded beside the bundle (bundle/record) for the
# next run.
# The record, with this run's picks folded in, and the workloads' keys are uploaded beside the bundle
# (bundle/record, bundle/keys) for the next run; PTS_INPUTS are the git ids the keys hash.
- name: Build the bundle
run: |
mkdir -p bundle && chmod 777 bundle
docker run --rm -e PTS_COMMIT="$SOURCE_SHA" -e TORCHSIM_FUNCTIONAL_MODE=0 \
-v "$PWD:/src:ro" -v "$PWD/picks:/picks:ro" -v "$PWD/bundle:/bundle" "${BASE_IMAGE}" bash -lc '
PTS_INPUTS="$(git rev-parse HEAD:pytorchsim HEAD:device HEAD:scripts/ci/bundle.py | tr '\n' ' ')"
docker run --rm -e PTS_COMMIT="$SOURCE_SHA" -e PTS_INPUTS="$PTS_INPUTS" -e BASE_IMAGE -e TORCHSIM_FUNCTIONAL_MODE=0 \
-v "$PWD:/src:ro" -v "$PWD/picks:/picks:ro" -v "$PWD/prev:/prev:ro" -v "$PWD/bundle:/bundle" "${BASE_IMAGE}" bash -lc '
set -euo pipefail
mkdir -p "$TORCHSIM_DIR"
tar -C /src --exclude=./.git --exclude=./.github -cf - . | tar -C "$TORCHSIM_DIR" -xf -
(cd "$TORCHSIM_DIR/device" && python -m pip install -q --no-build-isolation -e .)
cd "$TORCHSIM_DIR"
mkdir -p pytorchsim/selection && cp /picks/*.json pytorchsim/selection/ 2>/dev/null || true
TORCHSIM_TIMING_MODE=1 TORCHSIM_DUMP_PATH=/tmp/gemm python3 scripts/ci/bundle.py /bundle/out gemm --jobs 4 \
TORCHSIM_TIMING_MODE=1 TORCHSIM_DUMP_PATH=/tmp/gemm python3 scripts/ci/bundle.py /bundle/out gemm --jobs 4 --reuse /prev \
> /bundle/gemm.log 2>&1 & gemm=$!
TORCHSIM_TIMING_MODE=1 TORCHSIM_DUMP_PATH=/tmp/layer python3 scripts/ci/bundle.py /bundle/out layer --jobs 4 \
TORCHSIM_TIMING_MODE=1 TORCHSIM_DUMP_PATH=/tmp/layer python3 scripts/ci/bundle.py /bundle/out layer --jobs 4 --reuse /prev \
> /bundle/layer.log 2>&1 & layer=$!
TORCHSIM_DUMP_PATH=/tmp/rest python3 scripts/ci/bundle.py /bundle/out vector attention \
TORCHSIM_DUMP_PATH=/tmp/rest python3 scripts/ci/bundle.py /bundle/out vector attention --reuse /prev \
> /bundle/rest.log 2>&1 & rest=$!
rc=0; wait $gemm || rc=1; wait $layer || rc=1; wait $rest || rc=1
grep "^\[bundle\]" /bundle/gemm.log /bundle/layer.log /bundle/rest.log || true
Expand Down
112 changes: 99 additions & 13 deletions scripts/ci/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,15 @@
kernel a timed run picks. One recorded without its fused epilogue ("recorded_unfused") is kept and
named in a warning. The picks the GEMMs were timed to are appended to selection.jsonl in the dump
path, for scripts/selection_merge.py.

--reuse PREV copies PREV/out/<workload> when PREV/keys/<workload>.json holds the key this run writes to
KEYS (--keys, default OUT/../keys, not in OUT): a hash of env PTS_INPUTS and BASE_IMAGE, torch, the
selection identity, the run settings and the row. Without PTS_INPUTS nothing is keyed or reused.
"""

import argparse
import csv
import hashlib
import importlib.util
import json
import multiprocessing
Expand Down Expand Up @@ -258,7 +263,7 @@ def compiler_suite(suite):


def workloads(suites=None):
"""(name, suite, dims, fn, inputs maker) per measured row of `suites` (default all); a CAPPED
"""(name, suite, dims, fn, inputs maker, csv) per measured row of `suites` (default all); a CAPPED
suite's rows over the compiler's CI cap are left out."""
for suite, csv_name, keys, program, call in SUITES:
if suites and suite not in suites:
Expand All @@ -275,7 +280,7 @@ def workloads(suites=None):
fn, make = call(dims)
name = "_".join([suite, *(dims[k] for k in keys if k in TEXT_COLUMNS),
"x".join(str(dims[k]) for k in keys if k not in TEXT_COLUMNS), DTYPE])
yield name, suite, dims, fn, make
yield name, suite, dims, fn, make, csv_name


LAUNCHED = []
Expand Down Expand Up @@ -315,24 +320,93 @@ def pts_commit():
cwd=config.CONFIG_TORCHSIM_DIR).stdout.strip()


def build(out, suite, name):
"""Build `suite`'s workload `name` into out/<name>: (name, kernels launched, unpicked, unfused, externs)."""
dims, fn, make = next(w[2:] for w in workloads({suite}) if w[0] == name)
KEYED_ENV = ("TORCHSIM_", "TORCHINDUCTOR_", "TRITON_")
PER_RUN_ENV = {"TORCHSIM_DUMP_PATH", "TORCHSIM_LOG_PATH", "TORCHINDUCTOR_CACHE_DIR", "TRITON_CACHE_DIR"}


def keyed_env():
"""The environment PyTorchSim, Inductor and Triton read, less the cache and output paths each run
picks for itself (Inductor sets TORCHINDUCTOR_CACHE_DIR and TRITON_CACHE_DIR while compiling)."""
return {k: v for k, v in os.environ.items() if k.startswith(KEYED_ENV) and k not in PER_RUN_ENV}


def key_inputs(suite, name, dims, csv_name):
"""What decides workload `name`'s kernels, as ids and values; None without env PTS_INPUTS."""
pts = os.environ.get("PTS_INPUTS", "").split()
if not pts:
return None
return {"pts": pts, "base_image": os.environ.get("BASE_IMAGE", ""), "torch": torch.__version__,
"env": keyed_env(),
"identity": select.identity(), "target": config.CONFIG_TORCHSIM_TARGET,
"run": {s: getattr(config, s) for s in config.RUN_SETTINGS},
"workload": {"suite": suite, "csv": csv_name, "name": name, "dims": dims, "dtype": DTYPE}}


def workload_key(inputs):
return hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()


def write_key(keys, name, inputs, sources, externs):
os.makedirs(keys, exist_ok=True)
with open(os.path.join(keys, f"{name}.json"), "w") as f:
json.dump({"key": workload_key(inputs), "inputs": inputs, "tile_sources": sources,
"externs": externs}, f, indent=1, sort_keys=True)


def build(out, suite, name, keys=None):
"""Build `suite`'s workload `name` into out/<name>, and its key into keys/<name>.json unless a launch
is unpicked: (name, kernels launched, unpicked, unfused, externs)."""
dims, fn, make, csv_name = next(w[2:] for w in workloads({suite}) if w[0] == name)
shutil.rmtree(os.path.join(out, name), ignore_errors=True)
if keys:
_remove(os.path.join(keys, f"{name}.json"))
launches, sources, externs = capture(name, fn, make, out)
with open(os.path.join(out, name, "manifest.json"), "w") as f:
json.dump({"workload": name, "suite": suite, **dims, "dtype": DTYPE, "launches": launches,
"externs": externs}, f, indent=1)
unpicked = [la["kernel"] for la, s in zip(launches, sources) if s == select.HEURISTIC]
unfused = [la["kernel"] for la, s in zip(launches, sources) if s == select.RECORDED_UNFUSED]
return name, [la["kernel"] for la in launches], unpicked, unfused, [e["call"] for e in externs]
calls = [e["call"] for e in externs]
inputs = key_inputs(suite, name, dims, csv_name)
if keys and inputs is not None and not unpicked:
write_key(keys, name, inputs, sources, calls)
return name, [la["kernel"] for la in launches], unpicked, unfused, calls


def _remove(path):
try:
os.remove(path)
except FileNotFoundError:
pass


def reuse(prev, out, keys, suite, name, dims, csv_name):
"""Copy prev/out/<name> into out/<name> when prev/keys/<name>.json holds today's key and no unpicked
launch: (name, kernels, [], unfused, externs), else None."""
inputs = key_inputs(suite, name, dims, csv_name)
try:
with open(os.path.join(prev, "keys", f"{name}.json")) as f:
old = json.load(f)
with open(os.path.join(prev, "out", name, "manifest.json")) as f:
manifest = json.load(f)
except (OSError, ValueError):
return None
if inputs is None or old.get("key") != workload_key(inputs) \
or select.HEURISTIC in old.get("tile_sources", [select.HEURISTIC]):
return None
shutil.rmtree(os.path.join(out, name), ignore_errors=True)
shutil.copytree(os.path.join(prev, "out", name), os.path.join(out, name))
write_key(keys, name, inputs, old["tile_sources"], old["externs"])
kernels = [la["kernel"] for la in manifest["launches"]]
unfused = [k for k, s in zip(kernels, old["tile_sources"]) if s == select.RECORDED_UNFUSED]
return name, kernels, [], unfused, old["externs"]


def largest_first(suites):
"""(suite, workload name) of `suites`, each suite's ordered by the compiler's rank where it has one."""
names = []
for suite in dict.fromkeys(s[0] for s in SUITES if not suites or s[0] in suites):
mine = [(n, d) for n, s, d, _, _ in workloads({suite})]
mine = [(w[0], w[2]) for w in workloads({suite})]
rank = _rank(suite)
names += [(suite, n) for n, d in (sorted(mine, key=lambda w: -rank(w[1])) if rank else mine)]
return names
Expand All @@ -347,21 +421,30 @@ def _rank(suite):
return (lambda d: mod.cost(d, keys)) if hasattr(mod, "cost") else None


def main(out, suites=None, jobs=1):
def main(out, suites=None, jobs=1, keys=None, prev=None):
"""Write `suites`' workloads (default all) into `out`, replacing each one's directory there, in
`jobs` processes."""
`jobs` processes; each one whose key `prev` holds is copied from it instead of built."""
os.makedirs(out, exist_ok=True)
keys = keys or os.path.join(os.path.dirname(out), "keys")
unpicked, unfused = [], []
names = largest_first(suites)
names, reused = largest_first(suites), []
if prev:
rows = {(w[1], w[0]): (w[2], w[5]) for w in workloads(suites)}
reused = [r for r in (reuse(prev, out, keys, s, n, *rows[s, n]) for s, n in names) if r]
names = [n for n in names if n[1] not in {r[0] for r in reused}]
if jobs > 1:
pool = multiprocessing.get_context("spawn").Pool(jobs)
built = pool.imap_unordered(_build, [(out, *n) for n in names])
built = pool.imap_unordered(_build, [(out, *n, keys) for n in names])
else:
pool, built = None, (build(out, *n) for n in names)
pool, built = None, (build(out, *n, keys) for n in names)
for name, kernels, up, uf, externs in reused:
unfused += [(name, k) for k in uf]
print(f"[bundle] {name}: reused {kernels}" + (f" extern {externs}" if externs else ""), flush=True)
for name, kernels, up, uf, externs in built:
unpicked += [(name, k) for k in up]
unfused += [(name, k) for k in uf]
print(f"[bundle] {name}: {kernels}" + (f" extern {externs}" if externs else ""), flush=True)
print(f"[bundle] {len(reused)} reused, {len(names)} built", flush=True)
if pool is not None:
pool.close()
pool.join()
Expand All @@ -383,5 +466,8 @@ def _build(args):
ap.add_argument("out")
ap.add_argument("suites", nargs="*", help="suites to build (default: all)")
ap.add_argument("--jobs", type=int, default=1, help="processes building workloads at once")
ap.add_argument("--keys", help="where the workloads' keys are written (default: OUT/../keys)")
ap.add_argument("--reuse", metavar="PREV", help="a previous bundle (PREV/out, PREV/keys) to copy matches from")
a = ap.parse_args()
main(os.path.abspath(a.out), set(a.suites), a.jobs)
main(os.path.abspath(a.out), set(a.suites), a.jobs, a.keys and os.path.abspath(a.keys),
a.reuse and os.path.abspath(a.reuse))
43 changes: 43 additions & 0 deletions scripts/ci/previous_bundle.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/env bash
# The newest pts-bundle on BRANCH with a selection record, whole: record/ to PICKS, out/ and keys/ to PREV (for
# bundle.py --reuse), so the picks and the kernels are one run's. Never fails; with none both stay empty.
# GH_TOKEN=... REPO=owner/name scripts/ci/previous_bundle.sh PICKS PREV
set -uo pipefail
: "${GH_TOKEN:?a token that reads the actions of this repository}"
: "${REPO:?owner/name}"
: "${BRANCH:=pytorchsim-triton-backend}"
: "${WORKFLOW:=pytorchsim_triton_backend.yml}"
: "${EVENT:=push}"
PICKS=${1:?the directory to write the record to}
PREV=${2:?the directory to write the previous bundle to}
mkdir -p "$PICKS" "$PREV"

api() { curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" "$@"; }

RUNS=$(api "https://api.github.com/repos/$REPO/actions/workflows/$WORKFLOW/runs?branch=$BRANCH&event=$EVENT&per_page=30") \
|| { echo "::warning::could not list the bundle runs on $BRANCH: every workload is built"; exit 0; }
for run in $(jq -r --arg me "${GITHUB_RUN_ID:-0}" '.workflow_runs[] | select((.id|tostring) != $me) | .id' <<<"$RUNS"); do
id=$(api "https://api.github.com/repos/$REPO/actions/runs/$run/artifacts?per_page=100" \
| jq -r '[.artifacts[] | select(.name == "pts-bundle" and (.expired|not))][0].id // empty') || continue
[ -n "$id" ] || continue
zip=$(mktemp) && api -o "$zip" "https://api.github.com/repos/$REPO/actions/artifacts/$id/zip" || { rm -f "$zip"; continue; }
python3 -I - "$zip" "$PICKS" "$PREV" <<'PY' || { rm -f "$zip"; rm -rf "${PICKS:?}"/* "${PREV:?}"/*; continue; }
import os, sys, zipfile
z, picks, prev = zipfile.ZipFile(sys.argv[1]), sys.argv[2], sys.argv[3]
names = z.namelist()
record = [n for n in names if n.startswith("record/") and n.endswith(".json")]
if not record:
sys.exit(1)
for n in record:
with open(os.path.join(picks, os.path.basename(n)), "wb") as f:
f.write(z.read(n))
for n in names:
if n.startswith(("out/", "keys/")) and not n.endswith("/"):
z.extract(n, prev)
PY
rm -f "$zip"
echo "bundle of run $run: picks $(ls "$PICKS"), $(ls "$PREV/keys" 2>/dev/null | wc -l) keyed workloads"
exit 0
done
echo "::warning::no bundle run on $BRANCH left a selection record: every workload is built"
exit 0
40 changes: 0 additions & 40 deletions scripts/ci/previous_picks.sh

This file was deleted.

1 change: 1 addition & 0 deletions scripts/ci/triton_route_passing.txt
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ tests/ops/misc/test_user_triton_kernel.py
tests/ops/misc/test_widen_dtype.py
tests/ops/reduce/test_batchnorm.py
tests/ops/view/test_view3D_2D.py
tests/system/test_bundle_reuse.py
tests/system/test_eager.py
tests/system/test_patch_scope.py
tests/system/test_togsim_exit.py
Expand Down
Loading