Skip to content

Commit 062681a

Browse files
sraikund16pytorchmergebot
authored andcommitted
[Profiler] Torch Profiler distributed info is not JSON serializable (pytorch#135548)
Summary: To fix pytorch#133308 we must create an encoder for numpy values so we can serialize the distributed metadata to JSON. Test Plan: Added unit test to check that numpy values can be serialized Differential Revision: D62411619 Pull Request resolved: pytorch#135548 Approved by: https://github.com/aaronenyeshi, https://github.com/albanD
1 parent 8c356ce commit 062681a

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

torch/profiler/profiler.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,28 @@
3636
PROFILER_STEP_NAME = "ProfilerStep"
3737

3838

39+
class _NumpyEncoder(json.JSONEncoder):
40+
"""
41+
Json encoder for numpy types (np.int, np.float, np.array etc.)
42+
Returns default encoder if numpy is not available
43+
"""
44+
45+
def default(self, obj):
46+
"""Encode NumPy types to JSON"""
47+
try:
48+
import numpy as np
49+
except ImportError:
50+
return json.JSONEncoder.default(self, obj)
51+
if isinstance(obj, np.integer):
52+
return int(obj)
53+
elif isinstance(obj, np.floating):
54+
return float(obj)
55+
elif isinstance(obj, np.ndarray):
56+
return obj.tolist()
57+
else:
58+
return json.JSONEncoder.default(self, obj)
59+
60+
3961
def supported_activities():
4062
"""
4163
Returns a set of supported profiler tracing activities.
@@ -187,7 +209,9 @@ def start_trace(self):
187209
if kineto_available():
188210
dist_info = self._get_distributed_info()
189211
if dist_info:
190-
self.add_metadata_json("distributedInfo", json.dumps(dist_info))
212+
self.add_metadata_json(
213+
"distributedInfo", json.dumps(dist_info, cls=_NumpyEncoder)
214+
)
191215

192216
if hasattr(torch, "_inductor"):
193217
import torch._inductor.config as inductor_config
@@ -931,5 +955,6 @@ def _record_pg_config(self) -> None:
931955
):
932956
pg_config_info = torch.distributed.distributed_c10d._world.pg_config_info
933957
torch.autograd._record_function_with_args_enter(
934-
"## process_group:init ##", json.dumps(pg_config_info)
958+
"## process_group:init ##",
959+
json.dumps(pg_config_info, cls=_NumpyEncoder),
935960
)

0 commit comments

Comments
 (0)