code: def _compile(
      code: types.CodeType,
      globals: Dict[str, object],
      locals: Dict[str, object],
      builtins: Dict[str, object],
      compiler_fn: CompilerFn,
      one_graph: bool,
      export: bool,
      export_constraints,
      hooks: Hooks,
      cache_size: CacheSizeRelevantForFrame,
      frame: Optional[types.FrameType] = None,
      frame_state=None,
      compile_id=None,
  ) -> Optional[GuardedCode]:
      from torch.fx.experimental.validator import (
          bisect,
          BisectValidationException,
          translation_validation_enabled,
          ValidationException,
      )
  
      output: Optional[OutputGraph] = None
      tracer: Optional[InstructionTranslator] = None
      # This is shared across restarts
      mutated_closure_cell_contents: Set[str] = set()
      fail_type: Optional[str] = None
      fail_reason: Optional[str] = None
      fail_user_frame_filename: Optional[str] = None
      fail_user_frame_lineno: Optional[int] = None
      speculation_log = SpeculationLog()
  
      @preserve_global_state
      def transform(instructions, code_options):
          nonlocal output
          nonlocal tracer
          speculation_log.restart()
          tracer = InstructionTranslator(
              instructions,
              code,
              locals,
              globals,
              builtins,
              code_options,
              compiler_fn,
              one_graph,
              export,
              export_constraints,
              mutated_closure_cell_contents,
              frame_state=frame_state,
              speculation_log=speculation_log,
          )
  
          try:
              with tracing(
                  tracer.output.tracing_context
              ), tracer.set_current_tx():
                  tracer.run()
          except exc.UnspecializeRestartAnalysis:
              speculation_log.clear()
              raise
          except (exc.SpeculationRestartAnalysis, exc.SkipFrame):
              raise
          except Exception:
              if translation_validation_enabled():
                  bisect(tracer.output.shape_env)
              raise
          finally:
              tracer.output.call_cleanup_hooks()
  
          output = tracer.output
          assert output is not None
          assert output.output_instructions
          instructions[:] = output.output_instructions
          code_options.update(output.code_options)
  
          if config.dead_code_elimination:
              propagate_inst_exn_table_entries(instructions)
              check_inst_exn_tab_entries_valid(instructions)
              instructions[:] = remove_pointless_jumps(
                  remove_dead_code(instructions)
              )
  
      @dynamo_timed(phase_name="entire_frame_compile")
      def compile_inner(
          code: types.CodeType,
          one_graph: bool,
          hooks: Hooks,
          transform: Callable[[List[Instruction], Dict[str, Any]], Any],
      ) -> Optional[GuardedCode]:
          nonlocal output
          for attempt in itertools.count():
              CompileContext.get().attempt = attempt
              try:
                  out_code = transform_code_object(code, transform)
                  break
              except exc.RestartAnalysis as e:
                  log.info(
                      "Restarting analysis due to %s",
                      LazyString(
                          format_traceback_short, e.__traceback__
                      ),
                  )
                  if attempt > 100:
                      unimplemented("100+ RestartAnalysis() calls")
              except exc.SkipFrame as e:
                  log.debug(
                      "Skipping frame %s %s \
                      %s %s",
                      e,
                      code.co_name,
                      code.co_filename,
                      code.co_firstlineno,
                  )
                  if one_graph:
                      log.debug("No graph captured with one_graph=True")
                  return None
  
          def log_bytecode(prefix, name, filename, line_no, code):
              if bytecode_log.isEnabledFor(logging.DEBUG):
                  bytecode_log.debug(
                      format_bytecode(
                          prefix, name, filename, line_no, code
                      )
                  )
  
          log_bytecode(
              "ORIGINAL BYTECODE",
              code.co_name,
              code.co_filename,
              code.co_firstlineno,
              code,
          )
          log_bytecode(
              "MODIFIED BYTECODE",
              code.co_name,
              code.co_filename,
              code.co_firstlineno,
              out_code,
          )
  
          for hook in _bytecode_hooks.values():
              hook_output = hook(code, out_code)
              if hook_output is not None:
                  out_code = hook_output
  
          orig_code_map[out_code] = code
          output_codes.add(out_code)
  
          assert output is not None
  
          # Tests for new code objects.
          # The rationale for these tests can be found in torch/csrc/dynamo/eval_frame.c
          # Only test once the code object is created.
          # They are not tested during runtime.
  
          def count_args(code):
              import inspect
  
              return (
                  code.co_argcount
                  + code.co_kwonlyargcount
                  + bool(code.co_flags & inspect.CO_VARARGS)
                  + bool(code.co_flags & inspect.CO_VARKEYWORDS)
              )
  
          total_argcount_old = count_args(code)
          total_argcount_new = count_args(out_code)
          msg = "arg mismatch: "
          msg += f"old code object has args {code.co_varnames[:total_argcount_old]}, "
          msg += f"new code object has args {out_code.co_varnames[:total_argcount_new]}"
          assert (
              code.co_varnames[:total_argcount_old]
              == out_code.co_varnames[:total_argcount_new]
          ), msg
  
          msg = "free var mismatch: "
          msg += f"old code object has free var {code.co_freevars}, "
          msg += f"new code object has free var {out_code.co_freevars}"
          assert code.co_freevars == out_code.co_freevars, msg
  
          msg = "cell var mismatch: "
          msg += f"old code object has cell var {code.co_cellvars}, "
          msg += f"new code object has cell var {out_code.co_cellvars}"
          assert code.co_cellvars == out_code.co_cellvars, msg
  
          # Skipping Dynamo on a frame without any extracted graph.
          # This does not affect eager functionality. But this is necessary
          # for export for cases where Dynamo-reconstructed bytecode can create
          # new function frames, confusing export in thinking that there
          # are extra graphs now.
  
          if output.export and output.is_empty_graph():
              return None
  
          assert output.guards is not None
          CleanupManager.instance[out_code] = output.cleanups
          check_fn = CheckFunctionManager(
              output,
              hooks.guard_fail_fn if hooks else None,
          )
  
          guarded_code = GuardedCode(out_code, check_fn.check_fn)
  
          if (
              not output.is_empty_graph()
              and hooks.guard_export_fn is not None
          ):
              # We should not run the guard_export_fn when Dynamo does not
              # generate any graph. This can happen in export when TorchDynamo
              # generated bytecode has some reconstruction logic for mutated
              # variables which can trigger TorchDynamo on the children frames but
              # they are benign and do not generate any new graphs.
              hooks.guard_export_fn(output.guards)
  
          output.local_scope.clear()
          return guarded_code
  
      with compile_context(CompileContext(compile_id)):
          try:
              guarded_code = compile_inner(
                  code, one_graph, hooks, transform
              )
              return guarded_code
          except (
              Unsupported,
              TorchRuntimeError,
              BackendCompilerFailed,
              AssertionError,
              ConstraintViolationError,
              GuardOnDataDependentSymNode,
              ValidationException,
              UncapturedHigherOrderOpError,
              BisectValidationException,
          ) as e:
              fail_type = str(type(e))
              fail_reason = str(e)
              exception_handler(e, code, frame, export=export)
              if e.innermost_user_frame_summary is not None:  # type: ignore[union-attr]
                  fail_user_frame_filename = e.innermost_user_frame_summary.filename  # type: ignore[union-attr]
                  fail_user_frame_lineno = e.innermost_user_frame_summary.lineno  # type: ignore[union-attr]
              raise
          except Exception as e:
              fail_type = str(type(e))
              fail_reason = str(e)
              exception_handler(e, code, frame, export=export)
              if e.innermost_user_frame_summary is not None:  # type: ignore[attr-defined]
                  fail_user_frame_filename = e.innermost_user_frame_summary.filename  # type: ignore[attr-defined]
                  fail_user_frame_lineno = e.innermost_user_frame_summary.lineno  # type: ignore[attr-defined]
              raise InternalTorchDynamoError(str(e)).with_traceback(
                  e.__traceback__
              ) from None
          finally:
              if tracer:
                  tracer.output.local_scope = {}
  
              from .utils import curr_frame
  
              frame_key = str(curr_frame)
              if (
                  fail_reason is None
                  and output is not None
                  and frame_key in frame_phase_timing
              ):
                  guard_count = len(output.guards)
                  shape_env_guard_count = len(output.shape_env.guards)
                  graph_op_count = output.count_calls()
                  graph_node_count = len(output.graph.nodes)
                  graph_input_count = len(output.placeholders)
                  entire_frame_compile_time = frame_phase_timing[
                      frame_key
                  ].get("entire_frame_compile", None)
                  backend_compile_time = frame_phase_timing[
                      frame_key
                  ].get("backend_compile", None)
                  non_compliant_ops = {
                      op.__qualname__ for op in output.non_compliant_ops
                  }
                  compliant_custom_ops = {
                      op.__qualname__
                      for op in output.compliant_custom_ops
                  }
              else:
                  guard_count = None
                  shape_env_guard_count = None
                  graph_op_count = None
                  graph_node_count = None
                  graph_input_count = None
                  entire_frame_compile_time = None
                  backend_compile_time = None
                  non_compliant_ops = set({})
                  compliant_custom_ops = set({})
              metrics = CompilationMetrics(
                  frame_key,
                  code.co_name,
                  code.co_filename,
                  code.co_firstlineno,
                  cache_size.num_cache_entries_with_same_id_matched_objs,
                  cache_size.num_cache_entries,
                  guard_count,
                  shape_env_guard_count,
                  graph_op_count,
                  graph_node_count,
                  graph_input_count,
                  entire_frame_compile_time,
                  backend_compile_time,
                  fail_type,
                  fail_reason,
                  fail_user_frame_filename,
                  fail_user_frame_lineno,
                  non_compliant_ops,
                  compliant_custom_ops,
              )
              record_compilation_metrics(metrics)
  
imports: import collections
  import functools
  import itertools
  import logging
  import os
  import random
  import types
  import typing
  import weakref
  from typing import Any, Callable, Dict, List, Optional, Set
  import torch
  import torch._logging
  from torch._guards import compile_context, CompileContext, CompileId, tracing
  from torch._utils_internal import signpost_event
  from torch.fx.experimental.symbolic_shapes import ConstraintViolationError, GuardOnDataDependentSymNode
  from torch.fx.graph_module import _forward_from_src
  from torch.utils._traceback import format_traceback_short
  from .None import config, exc
  from .backends.registry import CompilerFn
  from .bytecode_analysis import remove_dead_code, remove_pointless_jumps
  from .bytecode_transformation import check_inst_exn_tab_entries_valid, Instruction, is_generator, propagate_inst_exn_table_entries, transform_code_object
  from .cache_size import CacheSizeRelevantForFrame, compute_cache_size, exceeds_cache_size_limit, is_recompilation
  from .eval_frame import always_optimize_code_objects, skip_code, TorchPatcher
  from .exc import augment_exc_message, BackendCompilerFailed, format_error_msg, InternalTorchDynamoError, TorchRuntimeError, UncapturedHigherOrderOpError, unimplemented, Unsupported
  from .guards import CheckFunctionManager, get_and_maybe_log_recompilation_reason, GuardedCode
  from .hooks import Hooks
  from .output_graph import OutputGraph
  from .replay_record import ExecutionRecord
  from .symbolic_convert import InstructionTranslator, SpeculationLog
  from .trace_rules import is_numpy
  from .types import BytecodeHook
  from .utils import CleanupManager, CompilationMetrics, counters, cprofile_wrapper, dynamo_timed, format_bytecode, frame_phase_timing, gen_record_file_name, increment_frame, is_namedtuple, istype, LazyString, orig_code_map, record_compilation_metrics, reset_graph_break_dup_checker, setup_compile_debug, troubleshooting_url, write_record_to_file
  from collections import OrderedDict
  from torch.utils.hooks import RemovableHandle
label_desc: Use image node_id 8 for calling a global function with example usage: _compile(code, globals, locals, builtins, compiler_fn, one_graph, export, export_constraints, hooks, cache_size, frame, frame_state, compile_id) and returns: guarded_code, unknown, None, guarded_code, None