class_docstr: TensorBoardChannel defines how to format and report the result of a PyText
  job to TensorBoard.
  
  Attributes:
      summary_writer: An instance of the TensorBoard SummaryWriter class, or
          an object that implements the same interface.
          https://pytorch.org/docs/stable/tensorboard.html
      metric_name: The name of the default metric to display on the
          TensorBoard dashboard, defaults to "accuracy"
      train_step: The training step count
class_docstr_tok: ["TensorBoardChannel","defines","how","to","format","and","report","the","result","of","a","PyText","job","to","TensorBoard",".","Attributes",":","summary_writer",":","An","instance","of","the","TensorBoard","SummaryWriter","class",",","or","an","object","that","implements","the","same","interface",".","https",":","\/\/pytorch.org\/docs\/stable\/tensorboard.html","metric_name",":","The","name","of","the","default","metric","to","display","on","the","TensorBoard","dashboard",",","defaults","to","``","accuracy","''","train_step",":","The","training","step","count"]
docstr: Defines how to format and report data to TensorBoard using the summary
  writer. In the current implementation, during the train/eval phase we
  recursively report each metric field as scalars, and during the test
  phase we report the final metrics to be displayed as texts.
  
  Also visualizes the internal model states (weights, biases) as
  histograms in TensorBoard.
  
  Args:
      stage (Stage): train, eval or test
      epoch (int): current epoch
      metrics (Any): all metrics
      model_select_metric (double): a single numeric metric to pick best model
      loss (double): average loss
      preds (List[Any]): list of predictions
      targets (List[Any]): list of targets
      scores (List[Any]): list of scores
      context (Dict[str, List[Any]]): dict of any additional context data,
          each context is a list of data that maps to each example
      meta (Dict[str, Any]): global metadata, such as target names
      model (nn.Module): the PyTorch neural network model
docstr_tok: ["Defines","how","to","format","and","report","data","to","TensorBoard","using","the","summary","writer",".","In","the","current","implementation",",","during","the","train\/eval","phase","we","recursively","report","each","metric","field","as","scalars",",","and","during","the","test","phase","we","report","the","final","metrics","to","be","displayed","as","texts",".","Also","visualizes","the","internal","model","states","(","weights",",","biases",")","as","histograms","in","TensorBoard",".","Args",":","stage","(","Stage",")",":","train",",","eval","or","test","epoch","(","int",")",":","current","epoch","metrics","(","Any",")",":","all","metrics","model_select_metric","(","double",")",":","a","single","numeric","metric","to","pick","best","model","loss","(","double",")",":","average","loss","preds","(","List","[","Any","]",")",":","list","of","predictions","targets","(","List","[","Any","]",")",":","list","of","targets","scores","(","List","[","Any","]",")",":","list","of","scores","context","(","Dict","[","str",",","List","[","Any","]","]",")",":","dict","of","any","additional","context","data",",","each","context","is","a","list","of","data","that","maps","to","each","example","meta","(","Dict","[","str",",","Any","]",")",":","global","metadata",",","such","as","target","names","model","(","nn.Module",")",":","the","PyTorch","neural","network","model"]
code: def report(
      self,
      stage,
      epoch,
      metrics,
      model_select_metric,
      loss,
      preds,
      targets,
      scores,
      context,
      meta,
      model,
      optimizer,
      log_gradient,
      gradients,
      *args,
  ):
      """
      Defines how to format and report data to TensorBoard using the summary
      writer. In the current implementation, during the train/eval phase we
      recursively report each metric field as scalars, and during the test
      phase we report the final metrics to be displayed as texts.
  
      Also visualizes the internal model states (weights, biases) as
      histograms in TensorBoard.
  
      Args:
          stage (Stage): train, eval or test
          epoch (int): current epoch
          metrics (Any): all metrics
          model_select_metric (double): a single numeric metric to pick best model
          loss (double): average loss
          preds (List[Any]): list of predictions
          targets (List[Any]): list of targets
          scores (List[Any]): list of scores
          context (Dict[str, List[Any]]): dict of any additional context data,
              each context is a list of data that maps to each example
          meta (Dict[str, Any]): global metadata, such as target names
          model (nn.Module): the PyTorch neural network model
      """
  
      def stage2prefix(stage: Stage):
          """
          mapping a Stage to a specific tag for printing into TB. Sometimes
          we may have a subclass of Stage that includes additional stages for
          fine-grained bookkeeping, which is mapped to "other" in TB.
          """
          if stage == Stage.TRAIN:
              return "train"
          elif stage == Stage.EVAL:
              return "eval"
          elif stage == Stage.TEST:
              return "test"
          else:
              return "others"
  
      if stage == Stage.TEST:
          tag = "test"
          self.summary_writer.add_text(tag, f"loss={loss}")
          if isinstance(metrics, (int, float)):
              self.summary_writer.add_text(
                  tag, f"{self.metric_name}={metrics}"
              )
          else:
              self.add_texts(tag, metrics)
      else:
          prefix = stage2prefix(stage)
          self.log_loss(prefix, loss, epoch)
          if isinstance(metrics, (int, float)):
              self.summary_writer.add_scalar(
                  f"{prefix}/{self.metric_name}", metrics, epoch
              )
          else:
              self.add_scalars(prefix, metrics, epoch)
  
      if stage == Stage.TRAIN:
          if optimizer is not None:
              for idx, param_group in enumerate(optimizer.param_groups):
                  self.summary_writer.add_scalar(
                      f"optimizer.lr.param_group.{idx}",
                      param_group["lr"],
                      epoch,
                  )
          if log_gradient and gradients:
              for key in gradients:
                  if len(gradients[key]):
                      sum_gradient = sum(gradients[key])
                      avg_gradient = sum_gradient / len(gradients[key])
                      grad_norms = np.array(
                          [LA.norm(g) for g in gradients[key]]
                      )
                      self.log_vector(
                          key + "_avg_gradients", avg_gradient, epoch
                      )
                      self.log_vector(
                          key + "_sum_gradients", sum_gradient, epoch
                      )
                      self.log_vector(
                          key + "_l2norm_gradients", grad_norms, epoch
                      )
  
          for key, val in model.named_parameters():
              if (
                  val is not None
                  and len(val) > 0
                  and not (val == 0).all()
              ):
                  limit = 9.9e19
                  val = torch.clamp(val.float(), -limit, limit)
                  self.log_vector(key, val, epoch)
  
imports: import csv
  import sys
  import traceback
  from typing import Tuple
  import numpy
  import torch
  from numpy import linalg
  from pytext.common.constants import Stage
  from pytext.utils.file_io import PathManager
  from torch.utils.tensorboard import SummaryWriter
label_desc: Use image node_id 3 for calling the TensorBoardChannel obj's underlying member method code with example usage: obj.report(stage, epoch, metrics, model_select_metric, loss, preds, targets, scores, context, meta, model, optimizer, log_gradient, gradients) and returns: str, str, str, str