Skip to content
Open
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
54 changes: 27 additions & 27 deletions docs/graph-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,33 +75,33 @@ are different. A change to a name or a tag does not change the key.

### 4. Upload

Upload is a manual procedure. It needs write credentials. Use conditional
writes, so that two uploads of one key cannot overwrite each other.

1. Compute the key of the graph (rule 1).
2. If the key is not in the store, put the object with `If-None-Match: *`:

```bash
aws s3api put-object --bucket therock-dvc \
--key dnn-benchmarking-graphs/<key> --body <key> \
--content-type application/json --if-none-match '*'
```

3. If the key is in the store:
1. Get the object and its ETag.
2. Make the union of its tags and your tags. Keep its `name`, unless you
intend to rename it.
3. Put the result with `If-Match: <etag>`
(`aws s3api put-object ... --if-match '"<etag>"'`).
4. If the put fails with `412 Precondition Failed`, another upload
changed the object. Start again at step 3.1.
4. To change a tag, overwrite the object as in step 3. Do not delete an
object to change its tags.

Before an upload, check each object against rules 1 to 3.
`tools/sdpa_fwd_to_bwd.py` (the SDPA backward corpus) writes objects that
obey these rules into a local folder. Run a folder with
`dnn-benchmark -g <folder>` before you upload it.
Use [`tools/upload_graphs.py`](../tools/upload_graphs.py) from an environment
with `dnn-benchmarking` installed and a recent AWS CLI v2 on `PATH`. Pass
tagged graph JSON files or directories containing `*.json` files.

```bash
# Preview against the public store without AWS credentials.
python tools/upload_graphs.py /path/to/graphs

# Write with a named AWS profile that has graph-store write access.
python tools/upload_graphs.py /path/to/graphs --profile graph-writer --apply
```

The script computes the object key from each graph, not its filename. It
validates the input and reports `create`, `merge`, or `skip` for each key.
Use `--store s3://BUCKET/PREFIX/` to select another store. A private store
also needs `--profile` for the preview.
The reader needs permission to get objects and list the destination prefix
so S3 can distinguish a missing key from denied access.

The script creates new objects with `If-None-Match: *`. For existing objects,
it keeps the stored name and notes, adds only missing tags, and writes with
`If-Match` using the ETag from the read. If another writer changes an object,
the script stops. Earlier writes remain in place; run the preview again
before you retry. The script does not remove tags or delete objects.

`tools/sdpa_fwd_to_bwd.py` writes tagged graph files into a local folder. Run
`dnn-benchmark -g <folder>` to check those graphs before you upload them.

## Old `Workloads/` sets

Expand Down
58 changes: 58 additions & 0 deletions tests/unit/test_upload_graphs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright © Advanced Micro Devices, Inc., or its affiliates.
# SPDX-License-Identifier: MIT

import json
import runpy
import subprocess
from pathlib import Path


_REPO = Path(__file__).resolve().parents[2]


def test_merge_preserves_metadata_and_stops_on_stale_etag(
tmp_path, monkeypatch, capsys
):
graph = json.loads((_REPO / "graphs/sample_sdpa.json").read_text())
graph["metadata"] = {
"operation": ["sdpa"],
"dtype": ["bfloat16"],
"workload": ["microbench"],
"notes": {"source": "stored"},
}
local = {
**graph,
"name": "local name",
"metadata": {
**graph["metadata"],
"workload": ["headline"],
"notes": {"source": "local"},
},
}
graph_file = tmp_path / "local.json"
graph_file.write_text(json.dumps(local))
puts = []

def aws(command, **kwargs):
if "get-object" in command:
Path(command[-1]).write_text(json.dumps(graph))
return subprocess.CompletedProcess(command, 0, '{"ETag":"\\"old\\""}', "")
assert "put-object" in command
puts.append(command)
assert command[command.index("--if-match") + 1] == '"old"'
body = Path(command[command.index("--body") + 1])
assert json.loads(body.read_text()) == {
**graph,
"metadata": {**graph["metadata"], "workload": ["headline", "microbench"]},
}
return subprocess.CompletedProcess(command, 254, "", "(PreconditionFailed)")

monkeypatch.setattr(subprocess, "run", aws)
cli = runpy.run_path(str(_REPO / "tools/upload_graphs.py"))["main"]
args = [str(graph_file), "--profile", "test"]
assert cli(args) == 0
assert capsys.readouterr().out.startswith("would merge ")
assert not puts
assert cli([*args, "--apply"]) == 1
assert len(puts) == 1
assert "S3 object changed" in capsys.readouterr().err
163 changes: 163 additions & 0 deletions tools/upload_graphs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
#!/usr/bin/env python3
# Copyright © Advanced Micro Devices, Inc., or its affiliates.
# SPDX-License-Identifier: MIT

"""Preview or upload tagged graph JSON files to an S3 graph store."""

import argparse
import json
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory

from dnn_benchmarking.graph import store

DEFAULT_STORE = "s3://therock-dvc/dnn-benchmarking-graphs/"


def validate(key: str, graph: dict) -> None:
problems = store.validate_object(key, graph)
if problems:
raise ValueError("; ".join(problems))
dtype = store.DTYPES.get(graph.get("io_data_type"))
if dtype is None or graph["metadata"].get("dtype") != [dtype]:
raise ValueError("metadata.dtype must match io_data_type")


def merge_tags(current: dict, incoming: dict) -> dict:
metadata = current["metadata"].copy()
for key, values in incoming["metadata"].items():
if key != "notes":
metadata[key] = sorted(set(metadata.get(key, [])) | set(values))
return {**current, "metadata": metadata}


def read_graph(path: Path) -> dict:
graph = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(graph, dict):
raise ValueError("expected a graph JSON object")
return graph


def load_inputs(paths: list[Path]) -> dict[str, dict]:
graphs = {}
for path in paths:
files = sorted(path.glob("*.json")) if path.is_dir() else [path]
if not files:
raise ValueError(f"{path}: no graph JSON files")
for file in files:
try:
graph = read_graph(file)
key = store.geometry_key(graph)
validate(key, graph)
if key in graphs:
graph = merge_tags(graphs[key], graph)
validate(key, graph)
graphs[key] = graph
except (OSError, TypeError, ValueError) as exc:
raise ValueError(f"{file}: {exc}") from exc
return graphs


def upload_graph(
common: list[str],
object_args: list[str],
key: str,
incoming: dict,
body: Path,
apply: bool,
) -> str:
get = subprocess.run(
[*common, "get-object", *object_args, str(body)],
capture_output=True,
text=True,
)
if get.returncode == 0:
current = read_graph(body)
validate(key, current)
graph = merge_tags(current, incoming)
if graph == current:
return "skip"
etag = json.loads(get.stdout).get("ETag")
if not etag:
raise ValueError("S3 did not return an ETag for the existing graph")
condition = ["--if-match", etag]
action = "merge"
elif "(NoSuchKey)" in get.stderr:
graph = incoming
condition = ["--if-none-match", "*"]
action = "create"
else:
raise RuntimeError(
get.stderr.strip() or f"aws get-object exited {get.returncode}"
)
validate(key, graph)
payload = store.object_bytes(graph)
if apply:
body.write_bytes(payload)
put = subprocess.run(
[
*common,
"put-object",
*object_args,
"--body",
str(body),
"--content-type",
"application/json",
*condition,
],
capture_output=True,
text=True,
)
if put.returncode:
if any(
f"({code})" in put.stderr
for code in ("PreconditionFailed", "ConditionalRequestConflict")
):
raise RuntimeError(
"S3 object changed; rerun the preview before retrying"
)
raise RuntimeError(
put.stderr.strip() or f"aws put-object exited {put.returncode}"
)
return action


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"graphs", nargs="+", type=Path, help="JSON files or directories"
)
parser.add_argument("--store", default=DEFAULT_STORE, help="destination S3 URL")
parser.add_argument("--profile", help="AWS CLI profile (required with --apply)")
parser.add_argument(
"--apply", action="store_true", help="write instead of previewing"
)
args = parser.parse_args(argv)
if args.apply and not args.profile:
parser.error("--apply requires --profile")
try:
bucket, prefix = store.split_store_url(args.store)
graphs = load_inputs(args.graphs)
except (OSError, ValueError) as exc:
parser.error(str(exc))

aws = ["aws", "--no-cli-pager", "--output", "json"]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of aws cli in this python script, could we use the boto3 api.
And then we could add a requirements.txt to download the dependencies

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should just use your env to upload

aws.extend(["--profile", args.profile] if args.profile else ["--no-sign-request"])
aws.append("s3api")
with TemporaryDirectory(prefix="dnn-upload-") as directory:
body = Path(directory) / "graph.json"
for key, graph in graphs.items():
args_for_key = ["--bucket", bucket, "--key", prefix + key]
try:
action = upload_graph(aws, args_for_key, key, graph, body, args.apply)
except (OSError, TypeError, ValueError, RuntimeError) as exc:
print(f"{key}: {exc}", file=sys.stderr)
return 1
print(f"{action if args.apply else 'would ' + action} {key}")
return 0


if __name__ == "__main__":
sys.exit(main())
Loading