Skip to content

Commit a4b4503

Browse files
jamesjwufacebook-github-bot
authored andcommitted
Log PT2 chromium events to scuba (#2424)
Summary: Pull Request resolved: #2424 X-link: pytorch/pytorch#133859 This diff implements a bunch of views for internal scuba viewing. TODOS that I might punt to another diff: - Saving cache stats via counter is definitely sus here, but there's not really a good way to track "fx graph cache hit for this compile phase" right now. Will think about this more. - We should definitely log frame id, compile id, etc - We should definitely be logging configs. That way, we can A/B test based on whether a config is turned on. - idk what I'm doing with compile_uuid yet, but it's useful when you want to look at samples for a single run. I think if we had mast job info this field is not needed, but it's nice to be able to drill down to a single run and get its chrome trace view or icicle view, so idk Reviewed By: ezyang Differential Revision: D61392607
1 parent dd54789 commit a4b4503

File tree

1 file changed

+91
-14
lines changed
  • userbenchmark/dynamo/dynamobench/_dynamo

1 file changed

+91
-14
lines changed

userbenchmark/dynamo/dynamobench/_dynamo/utils.py

+91-14
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import time
2727
import types
2828
import typing
29+
import uuid
2930
import warnings
3031
import weakref
3132
from contextlib import contextmanager
@@ -64,7 +65,7 @@
6465
from torch._dispatch.python import enable_python_dispatcher
6566
from torch._guards import TracingContext
6667
from torch._subclasses.meta_utils import is_sparse_compressed
67-
from torch._utils_internal import log_compilation_event
68+
from torch._utils_internal import log_chromium_event_internal, log_compilation_event
6869
from torch.fx._utils import _format_graph_code, lazy_format_graph_code
6970
from torch.nn.modules.lazy import LazyModuleMixin
7071
from torch.utils._triton import has_triton, has_triton_package
@@ -212,6 +213,16 @@ def _add_time_spent(key: str, phase_name: str, time_spent: float) -> None:
212213
frame_phase_timing[key][phase_name] += time_spent
213214

214215

216+
def get_cache_stats() -> Dict[str, Any]:
217+
"""Get a bunch of metadata about cache hits and misses to use in chromium events"""
218+
cache_stats = {
219+
"fxgraph_cache_hit": counters["inductor"]["fxgraph_cache_hit"],
220+
"fxgraph_cache_miss": counters["inductor"]["fxgraph_cache_miss"],
221+
"fxgraph_cache_bypass": counters["inductor"]["fxgraph_cache_bypass"],
222+
}
223+
return cache_stats
224+
225+
215226
# dynamo_timed is a context manager
216227
# By wrapping a function in dynamo_timed, we can store a record in compilation_time_metrics
217228
# where the key is the functions name.
@@ -245,6 +256,7 @@ def dynamo_timed(
245256
phase_name: Optional[str] = None,
246257
fwd_only: bool = True,
247258
):
259+
chromium_log: ChromiumEventLogger = get_chromium_event_logger()
248260
if key not in compilation_time_metrics:
249261
compilation_time_metrics[key] = []
250262

@@ -254,13 +266,22 @@ def dynamo_timed(
254266
try:
255267
with torch.profiler.record_function(f"{key} (dynamo_timed)"):
256268
t0 = time.time()
257-
ChromiumEventLogger.log_event_start(key, time.time_ns())
269+
start = time.time_ns()
270+
chromium_log.log_event_start(key, start, None)
258271
if phase_name:
259-
ChromiumEventLogger.log_event_start(phase_name, time.time_ns())
272+
chromium_log.log_event_start(phase_name, start)
260273
yield
274+
261275
if phase_name:
262-
ChromiumEventLogger.log_event_end(phase_name, time.time_ns())
263-
ChromiumEventLogger.log_event_end(key, time.time_ns())
276+
chromium_log.log_event_end(
277+
phase_name,
278+
time.time_ns(),
279+
{"cache_stats": get_cache_stats()},
280+
start,
281+
)
282+
chromium_log.log_event_end(
283+
key, time.time_ns(), {"cache_stats": get_cache_stats()}, start
284+
)
264285
time_spent = time.time() - t0
265286
compilation_time_metrics[key].append(time_spent)
266287
except Exception as e:
@@ -814,8 +835,17 @@ class ChromiumEventLogger:
814835
a specification of the Chromium Event JSON format.
815836
"""
816837

817-
@staticmethod
838+
def __init__(self):
839+
self.stack = ["__start__"]
840+
# Generate a unique id for this logger, which we can use in scuba to filter down
841+
# to a single python run.
842+
self.id_ = str(uuid.uuid4())
843+
844+
# TODO: log to init/id tlparse after I add support for it
845+
log.info("ChromiumEventLogger initialized with id %s", self.id_)
846+
818847
def log_event_start(
848+
self,
819849
event_name: str,
820850
time_ns: int,
821851
metadata: Optional[Dict[str, Any]] = None,
@@ -826,18 +856,24 @@ def log_event_start(
826856
:param time_ns Timestamp in nanoseconds
827857
:param metadata: Any extra metadata associated with this event
828858
"""
829-
ChromiumEventLogger._log_timed_event(
859+
event = self._log_timed_event(
830860
event_name,
831861
time_ns,
832862
"B",
833863
metadata,
834864
)
865+
log_chromium_event_internal(event, self.stack, self.id_)
866+
self.stack.append(event_name)
867+
868+
def reset(self) -> None:
869+
self.stack = ["__start__"]
835870

836-
@staticmethod
837871
def log_event_end(
872+
self,
838873
event_name: str,
839874
time_ns: int,
840875
metadata: Optional[Dict[str, Any]] = None,
876+
start_time_ns: Optional[int] = None,
841877
) -> None:
842878
"""
843879
Logs the end of a single event. This function should only be
@@ -846,28 +882,53 @@ def log_event_end(
846882
:param time_ns: Timestamp in nanoseconds
847883
:param metadata: Any extra metadata associated with this event
848884
"""
849-
ChromiumEventLogger._log_timed_event(
885+
# These stack health checks currently never happen,
886+
# but they're written this way to future proof any weird event
887+
# overlaps in the future.
888+
if event_name not in self.stack:
889+
# Something went wrong, we never called start on this event,
890+
# or it was skipped due to overlapping events below
891+
log.warning("ChromiumEventLogger: Start event not in stack, ignoring")
892+
return
893+
894+
event = self._log_timed_event(
850895
event_name,
851896
time_ns,
852897
"E",
853898
metadata,
854899
)
855900

856-
@staticmethod
901+
while event_name != self.stack[-1]:
902+
# If the event isn't the most recent one to end, pop
903+
# off the stack until it is.
904+
# Since event_name in self.stack, this pop is always safe
905+
log.warning(
906+
"ChromiumEventLogger: Detected overlapping events, fixing stack"
907+
)
908+
self.stack.pop()
909+
910+
log_chromium_event_internal(event, self.stack, self.id_, start_time_ns)
911+
# Finally pop the actual event off the stack
912+
self.stack.pop()
913+
857914
def _log_timed_event(
915+
self,
858916
event_name: str,
859917
time_ns: int,
860918
phase: str,
861919
metadata: Optional[Dict[str, Any]] = None,
862-
) -> None:
920+
) -> Dict[str, Any]:
863921
"""
864922
Logs a timed event in chromium format. See log_event_start, log_event_end, etc.
865923
"""
866924
event = {
867925
"name": event_name,
868-
"ts": time_ns / 1000, # Chromium events are in ms
926+
"ts": time_ns / 1000, # Chromium events are in micro seconds
869927
"args": metadata,
870928
"ph": phase,
929+
# These categories are needed in all chromium traces
930+
"cat": "dynamo_timed",
931+
"tid": 0,
871932
"pid": 0, # pid should be specified on all logs, we don't personally care about the actual process id
872933
}
873934
torch._logging.trace_structured(
@@ -876,9 +937,10 @@ def _log_timed_event(
876937
suppress_context=False,
877938
expect_trace_id=False, # Not every chromium event will have a trace_id
878939
)
940+
return event
879941

880-
@staticmethod
881942
def log_instant_event(
943+
self,
882944
event_name: str,
883945
time_ns: int,
884946
metadata: Optional[Dict[str, Any]] = None,
@@ -895,7 +957,10 @@ def log_instant_event(
895957
"ts": time_ns / 1000,
896958
"args": metadata,
897959
"ph": "i",
898-
"pid": 0, # pid should be specified on all logs, we don't personally care about the actual process id
960+
# These categories are needed in all chromium traces
961+
"cat": "dynamo_timed",
962+
"tid": 0,
963+
"pid": 0,
899964
"s": "p", # We use "process" level instant events so they all appear on the same row in the trace.
900965
}
901966
torch._logging.trace_structured(
@@ -904,6 +969,18 @@ def log_instant_event(
904969
suppress_context=False,
905970
expect_trace_id=True,
906971
)
972+
# Log an instant event with the same start and end time
973+
log_chromium_event_internal(event, self.stack, self.id_)
974+
975+
976+
CHROMIUM_EVENT_LOG: Optional[ChromiumEventLogger] = None
977+
978+
979+
def get_chromium_event_logger() -> ChromiumEventLogger:
980+
global CHROMIUM_EVENT_LOG
981+
if CHROMIUM_EVENT_LOG is None:
982+
CHROMIUM_EVENT_LOG = ChromiumEventLogger()
983+
return CHROMIUM_EVENT_LOG
907984

908985

909986
@dataclasses.dataclass

0 commit comments

Comments
 (0)