Skip to content

Commit 81d0bff

Browse files
committed
[not4land] Local torchao benchmark
Summary: Test Plan: Reviewers: Subscribers: Tasks: Tags:
1 parent 675fb8f commit 81d0bff

File tree

8 files changed

+184
-7
lines changed

8 files changed

+184
-7
lines changed

cron_script.sh

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/bin/bash
2+
# conda activate /home/jerryzh/anaconda3/envs/benchmark
3+
# getting the latest torchao nightly
4+
pip uninstall -y torchao
5+
pip install -I --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu124
6+
cd ~/local/cron_jobs/benchmark
7+
rm benchmark_results.json
8+
export HUGGING_FACE_HUB_TOKEN=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
9+
~/anaconda3/envs/benchmark/bin/python run_benchmark.py torchao --performance --inference --bfloat16 --inductor-compile-mode max-autotune --torchbench --ci
10+
alias with-proxy="http_proxy=http://regional-fwdproxy6-shv-01.rcco0.facebook.com:8080 https_proxy=http://regional-fwdproxy6-shv-01.rcco0.facebook.com:8080 ftp_proxy=http://regional-fwdproxy6-shv-01.rcco0.facebook.com:8080"
11+
echo "Uploading to s3"
12+
with-proxy ~/anaconda3/envs/benchmark/bin/python upload_to_s3.py --json-path benchmark_results.json
13+
echo "After running upload_to_s3"
14+
aws s3 ls ossci-benchmarks/v3/pytorch/ao/devvm2167/

manual_cron.sh

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
target_hour=03
2+
target_min=00
3+
while true
4+
do
5+
current_hour=$(date +%H)
6+
current_min=$(date +%M)
7+
if [ $current_hour -eq $target_hour ] && [ $current_min -eq $target_min ] ; then
8+
echo "Cron job started at $(date)"
9+
sh ~/local/cron_jobs/benchmark/cron_script.sh > ~/local/cron_jobs/benchmark/local_cron_log 2>~/local/cron_jobs/benchmark/local_cron_err
10+
echo "Cron job executed at $(date)"
11+
fi
12+
sleep 60
13+
done

requirements.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ pytest
99
pytest-benchmark
1010
requests
1111
tabulate
12-
git+https://github.com/huggingface/pytorch-image-models.git@730b907
12+
# git+https://github.com/huggingface/pytorch-image-models.git@730b907
1313
# this version of transformers is required by linger-kernel
1414
# https://github.com/linkedin/Liger-Kernel/blob/main/pyproject.toml#L23
1515
transformers==4.44.2

upload_to_s3.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import os
2+
import io
3+
import json
4+
from functools import lru_cache
5+
import boto3
6+
from typing import Any
7+
import gzip
8+
9+
@lru_cache
10+
def get_s3_resource() -> Any:
11+
return boto3.resource("s3")
12+
13+
def upload_to_s3(
14+
bucket_name: str,
15+
key: str,
16+
json_path: str,
17+
) -> None:
18+
print(f"Writing {json_path} documents to S3")
19+
data = []
20+
with open(f"{os.path.splitext(json_path)[0]}.json", "r") as f:
21+
for l in f.readlines():
22+
data.append(json.loads(l))
23+
24+
body = io.StringIO()
25+
for benchmark_entry in data:
26+
json.dump(benchmark_entry, body)
27+
body.write("\n")
28+
29+
try:
30+
get_s3_resource().Object(
31+
f"{bucket_name}",
32+
f"{key}",
33+
).put(
34+
Body=body.getvalue(),
35+
ContentType="application/json",
36+
)
37+
except e:
38+
print("fail to upload to s3:", e)
39+
return
40+
print("Done!")
41+
42+
if __name__ == "__main__":
43+
import argparse
44+
import datetime
45+
parser = argparse.ArgumentParser(description="Upload benchmark result json file to clickhouse")
46+
parser.add_argument("--json-path", type=str, help="json file path to upload to click house", required=True)
47+
args = parser.parse_args()
48+
today = datetime.date.today()
49+
today = datetime.datetime.combine(today, datetime.time.min)
50+
today_timestamp = str(int(today.timestamp()))
51+
print("Today timestamp:", today_timestamp)
52+
upload_to_s3("ossci-benchmarks", "v3/pytorch/ao/devvm2167/torchbenchmark-torchbench-" + today_timestamp + ".json", args.json_path)

userbenchmark/dynamo/dynamobench/torchao_backend.py

+38
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
from typing import Any, Callable
22

33
import torch
4+
from .utils import get_arch_name, write_json_result
45

6+
_OUTPUT_JSON_PATH = "benchmark_results"
57

68
def setup_baseline():
79
from torchao.quantization.utils import recommended_inductor_config_setter
@@ -11,6 +13,21 @@ def setup_baseline():
1113
torch._dynamo.config.cache_size_limit = 10000
1214

1315

16+
def benchmark_and_write_json_result(model, args, kwargs, quantization, device):
17+
print(quantization + " run")
18+
from torchao.utils import benchmark_model, profiler_runner
19+
model = torch.compile(model, mode="max-autotune")
20+
benchmark_model(model, 20, args, kwargs)
21+
elapsed_time = benchmark_model(model, 100, args, kwargs)
22+
print("elapsed_time: ", elapsed_time, " milliseconds")
23+
24+
name = model._orig_mod.__class__.__name__
25+
headers = ["name", "dtype", "device", "arch", "metric", "actual", "target"]
26+
arch = get_arch_name()
27+
dtype = quantization
28+
performance_result = [name, dtype, device, arch, "time_ms(avg)", elapsed_time, None]
29+
write_json_result(_OUTPUT_JSON_PATH, headers, performance_result)
30+
1431
def torchao_optimize_ctx(quantization: str):
1532
from torchao.quantization.quant_api import (
1633
autoquant,
@@ -20,10 +37,21 @@ def torchao_optimize_ctx(quantization: str):
2037
quantize_,
2138
)
2239
from torchao.utils import unwrap_tensor_subclass
40+
import torchao
2341

2442
def inner(model_iter_fn: Callable):
2543
def _torchao_apply(module: torch.nn.Module, example_inputs: Any):
2644
if getattr(module, "_quantized", None) is None:
45+
if quantization == "noquant":
46+
if isinstance(example_inputs, dict):
47+
args = ()
48+
kwargs = example_inputs
49+
else:
50+
args = example_inputs
51+
kwargs = {}
52+
53+
benchmark_and_write_json_result(module, args, kwargs, "noquant", "cuda")
54+
2755
if quantization == "int8dynamic":
2856
quantize_(
2957
module,
@@ -47,6 +75,16 @@ def _torchao_apply(module: torch.nn.Module, example_inputs: Any):
4775
"NotAutoquantizable"
4876
f"Found no autoquantizable layers in model {type(module)}, stopping autoquantized run"
4977
)
78+
79+
if isinstance(example_inputs, dict):
80+
args = ()
81+
kwargs = example_inputs
82+
else:
83+
args = example_inputs
84+
kwargs = {}
85+
86+
torchao.quantization.utils.recommended_inductor_config_setter()
87+
benchmark_and_write_json_result(module, args, kwargs, "autoquant", "cuda")
5088
else:
5189
unwrap_tensor_subclass(module)
5290
setattr(module, "_quantized", True) # noqa: B010
+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import json
2+
import torch
3+
import platform
4+
import os
5+
import time
6+
import datetime
7+
import hashlib
8+
9+
def get_arch_name() -> str:
10+
if torch.cuda.is_available():
11+
return torch.cuda.get_device_name()
12+
else:
13+
# This returns x86_64 or arm64 (for aarch64)
14+
return platform.machine()
15+
16+
17+
def write_json_result(output_json_path, headers, row):
18+
"""
19+
Write the result into JSON format, so that it can be uploaded to the benchmark database
20+
to be displayed on OSS dashboard. The JSON format is defined at
21+
https://github.com/pytorch/pytorch/wiki/How-to-integrate-with-PyTorch-OSS-benchmark-database
22+
"""
23+
mapping_headers = {headers[i]: v for i, v in enumerate(row)}
24+
today = datetime.date.today()
25+
sha_hash = hashlib.sha256(str(today).encode("utf-8")).hexdigest()
26+
first_second = datetime.datetime.combine(today, datetime.time.min)
27+
workflow_id = int(first_second.timestamp())
28+
job_id = workflow_id + 1
29+
record = {
30+
"timestamp": int(time.time()),
31+
"schema_version": "v3",
32+
"name": "devvm local benchmark",
33+
"repo": "pytorch/ao",
34+
"head_branch": "main",
35+
"head_sha": sha_hash,
36+
"workflow_id": workflow_id,
37+
"run_attempt": 1,
38+
"job_id": job_id,
39+
"benchmark": {
40+
"name": "TorchAO benchmark",
41+
"mode": "inference",
42+
"dtype": mapping_headers["dtype"],
43+
"extra_info": {
44+
"device": mapping_headers["device"],
45+
"arch": mapping_headers["arch"],
46+
},
47+
},
48+
"model": {
49+
"name": mapping_headers["name"],
50+
"type": "model",
51+
# TODO: make this configurable
52+
"origins": ["torchbench"],
53+
},
54+
"metric": {
55+
"name": mapping_headers["metric"],
56+
"benchmark_values": [mapping_headers["actual"]],
57+
"target_value": mapping_headers["target"],
58+
},
59+
}
60+
61+
with open(f"{os.path.splitext(output_json_path)[0]}.json", "a") as f:
62+
print(json.dumps(record), file=f)

userbenchmark/group_bench/configs/torch_ao.yaml

+2-4
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,5 @@ metrics:
1010
test_group:
1111
test_batch_size_default:
1212
subgroup:
13-
- extra_args:
14-
- extra_args: --quantization int8dynamic
15-
- extra_args: --quantization int8weightonly
16-
- extra_args: --quantization int4weightonly
13+
- extra_args: --quantization noquant
14+
- extra_args: --quantization autoquant

userbenchmark/torchao/run.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@ def _get_ci_args(
3434

3535

3636
def _get_full_ci_args(modelset: str) -> List[List[str]]:
37-
backends = ["autoquant", "int8dynamic", "int8weightonly", "noquant"]
37+
backends = ["autoquant", "noquant"]
3838
modelset = [modelset]
3939
dtype = ["bfloat16"]
4040
mode = ["inference"]
4141
device = ["cuda"]
42-
experiment = ["performance", "accuracy"]
42+
experiment = ["performance"]
4343
cfgs = itertools.product(*[backends, modelset, dtype, mode, device, experiment])
4444
return [_get_ci_args(*cfg) for cfg in cfgs]
4545

0 commit comments

Comments
 (0)