Repository navigation
feat(graph-store): add a conditional graph uploader #151
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SamuelReeder
wants to merge
1
commit into
main
Choose a base branch
from
users/sareeder/graph-store-uploader
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+248
−27
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"] | ||
| 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()) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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