prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  BaseWeightsScalarHandler has side effects on random number generation
  ### Problem
  BaseWeightsScalarHandler uses `torch.rand` to test the reduction function that is passed as an argument. 
  This is very confusing, because experiments are not reproducible when tensorboard logging is switched on or off, e.g. in debug sessions. 
  
  ### Solution
  Replace the random tensor with a non random tensor. 
  
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `ignite/contrib/handlers/base_logger.py`
  Content:
  ```
  1 from abc import ABCMeta, abstractmethod
  2 import numbers
  3 import warnings
  4 
  5 import torch
  6 
  7 from ignite.engine import State, Engine
  8 from ignite._six import with_metaclass
  9 
  10 
  11 class BaseLogger(object):
  12     """
  13     Base logger handler. See implementations: TensorboardLogger, VisdomLogger, PolyaxonLogger
  14 
  15     """
  16     def attach(self, engine, log_handler, event_name):
  17         """Attach the logger to the engine and execute `log_handler` function at `event_name` events.
  18 
  19         Args:
  20             engine (Engine): engine object.
  21             log_handler (callable): a logging handler to execute
  22             event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.engine.Events`
  23                 or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
  24 
  25         """
  26         if event_name not in State.event_to_attr:
  27             raise RuntimeError("Unknown event name '{}'".format(event_name))
  28 
  29         engine.add_event_handler(event_name, log_handler, self, event_name)
  30 
  31     def __enter__(self):
  32         return self
  33 
  34     def __exit__(self, type, value, traceback):
  35         self.close()
  36 
  37     def close(self):
  38         pass
  39 
  40 
  41 class BaseHandler(with_metaclass(ABCMeta, object)):
  42 
  43     @abstractmethod
  44     def __call__(self, *args, **kwargs):
  45         pass
  46 
  47 
  48 class BaseOptimizerParamsHandler(BaseHandler):
  49     """
  50     Base handler for logging optimizer parameters
  51     """
  52 
  53     def __init__(self, optimizer, param_name="lr", tag=None):
  54         if not isinstance(optimizer, torch.optim.Optimizer):
  55             raise TypeError("Argument optimizer should be of type torch.optim.Optimizer, "
  56                             "but given {}".format(type(optimizer)))
  57 
  58         self.optimizer = optimizer
  59         self.param_name = param_name
  60         self.tag = tag
  61 
  62 
  63 class BaseOutputHandler(BaseHandler):
  64     """
  65     Helper handler to log engine's output and/or metrics
  66     """
  67 
  68     def __init__(self, tag, metric_names=None, output_transform=None, another_engine=None, global_step_transform=None):
  69 
  70         if metric_names is not None:
  71             if not (isinstance(metric_names, list) or (isinstance(metric_names, str) and metric_names == "all")):
  72                 raise TypeError("metric_names should be either a list or equal 'all', "
  73                                 "got {} instead.".format(type(metric_names)))
  74 
  75         if output_transform is not None and not callable(output_transform):
  76             raise TypeError("output_transform should be a function, got {} instead."
  77                             .format(type(output_transform)))
  78 
  79         if output_transform is None and metric_names is None:
  80             raise ValueError("Either metric_names or output_transform should be defined")
  81 
  82         if another_engine is not None:
  83             if not isinstance(another_engine, Engine):
  84                 raise TypeError("Argument another_engine should be of type Engine, "
  85                                 "but given {}".format(type(another_engine)))
  86             warnings.warn("Use of another_engine is deprecated and will be removed in 0.2.1. "
  87                           "Please use global_step_transform instead.", DeprecationWarning)
  88 
  89         if global_step_transform is not None and not callable(global_step_transform):
  90             raise TypeError("global_step_transform should be a function, got {} instead."
  91                             .format(type(global_step_transform)))
  92 
  93         if global_step_transform is None:
  94             def global_step_transform(engine, event_name):
  95                 return engine.state.get_event_attrib_value(event_name)
  96 
  97         self.tag = tag
  98         self.metric_names = metric_names
  99         self.output_transform = output_transform
  100         self.another_engine = another_engine
  101         self.global_step_transform = global_step_transform
  102 
  103     def _setup_output_metrics(self, engine):
  104         """Helper method to setup metrics to log
  105         """
  106         metrics = {}
  107         if self.metric_names is not None:
  108             if isinstance(self.metric_names, str) and self.metric_names == "all":
  109                 metrics = engine.state.metrics
  110             else:
  111                 for name in self.metric_names:
  112                     if name not in engine.state.metrics:
  113                         warnings.warn("Provided metric name '{}' is missing "
  114                                       "in engine's state metrics: {}".format(name, list(engine.state.metrics.keys())))
  115                         continue
  116                     metrics[name] = engine.state.metrics[name]
  117 
  118         if self.output_transform is not None:
  119             output_dict = self.output_transform(engine.state.output)
  120 
  121             if not isinstance(output_dict, dict):
  122                 output_dict = {"output": output_dict}
  123 
  124             metrics.update({name: value for name, value in output_dict.items()})
  125         return metrics
  126 
  127 
  128 class BaseWeightsScalarHandler(BaseHandler):
  129     """
  130     Helper handler to log model's weights as scalars.
  131     """
  132 
  133     def __init__(self, model, reduction=torch.norm, tag=None):
  134         if not isinstance(model, torch.nn.Module):
  135             raise TypeError("Argument model should be of type torch.nn.Module, "
  136                             "but given {}".format(type(model)))
  137 
  138         if not callable(reduction):
  139             raise TypeError("Argument reduction should be callable, "
  140                             "but given {}".format(type(reduction)))
  141 
  142         def _is_0D_tensor(t):
  143             return isinstance(t, torch.Tensor) and t.ndimension() == 0
  144 
  145         # Test reduction function on a random tensor
  146         o = reduction(torch.rand(4, 2))
  147         if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):
  148             raise ValueError("Output of the reduction function should be a scalar, but got {}".format(type(o)))
  149 
  150         self.model = model
  151         self.reduction = reduction
  152         self.tag = tag
  153 
  154 
  155 class BaseWeightsHistHandler(BaseHandler):
  156     """
  157     Helper handler to log model's weights as histograms.
  158     """
  159 
  160     def __init__(self, model, tag=None):
  161         if not isinstance(model, torch.nn.Module):
  162             raise TypeError("Argument model should be of type torch.nn.Module, "
  163                             "but given {}".format(type(model)))
  164 
  165         self.model = model
  166         self.tag = tag
  167
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/ignite/contrib/handlers/base_logger.py b/ignite/contrib/handlers/base_logger.py
  --- a/ignite/contrib/handlers/base_logger.py
  +++ b/ignite/contrib/handlers/base_logger.py
  @@ -142,8 +142,8 @@
           def _is_0D_tensor(t):
               return isinstance(t, torch.Tensor) and t.ndimension() == 0
   
  -        # Test reduction function on a random tensor
  -        o = reduction(torch.rand(4, 2))
  +        # Test reduction function on a tensor
  +        o = reduction(torch.ones(4, 2))
           if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):
               raise ValueError("Output of the reduction function should be a scalar, but got {}".format(type(o)))
  
verification_info: {"golden_diff": "diff --git a/ignite/contrib/handlers/base_logger.py b/ignite/contrib/handlers/base_logger.py\n--- a/ignite/contrib/handlers/base_logger.py\n+++ b/ignite/contrib/handlers/base_logger.py\n@@ -142,8 +142,8 @@\n         def _is_0D_tensor(t):\n             return isinstance(t, torch.Tensor) and t.ndimension() == 0\n \n-        # Test reduction function on a random tensor\n-        o = reduction(torch.rand(4, 2))\n+        # Test reduction function on a tensor\n+        o = reduction(torch.ones(4, 2))\n         if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):\n             raise ValueError(\"Output of the reduction function should be a scalar, but got {}\".format(type(o)))\n", "issue": "BaseWeightsScalarHandler has side effects on random number generation\n### Problem\r\nBaseWeightsScalarHandler uses `torch.rand` to test the reduction function that is passed as an argument. \r\nThis is very confusing, because experiments are not reproducible when tensorboard logging is switched on or off, e.g. in debug sessions. \r\n\r\n### Solution\r\nReplace the random tensor with a non random tensor. \r\n\r\n\n", "before_files": [{"content": "from abc import ABCMeta, abstractmethod\nimport numbers\nimport warnings\n\nimport torch\n\nfrom ignite.engine import State, Engine\nfrom ignite._six import with_metaclass\n\n\nclass BaseLogger(object):\n    \"\"\"\n    Base logger handler. See implementations: TensorboardLogger, VisdomLogger, PolyaxonLogger\n\n    \"\"\"\n    def attach(self, engine, log_handler, event_name):\n        \"\"\"Attach the logger to the engine and execute `log_handler` function at `event_name` events.\n\n        Args:\n            engine (Engine): engine object.\n            log_handler (callable): a logging handler to execute\n            event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.engine.Events`\n                or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.\n\n        \"\"\"\n        if event_name not in State.event_to_attr:\n            raise RuntimeError(\"Unknown event name '{}'\".format(event_name))\n\n        engine.add_event_handler(event_name, log_handler, self, event_name)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, type, value, traceback):\n        self.close()\n\n    def close(self):\n        pass\n\n\nclass BaseHandler(with_metaclass(ABCMeta, object)):\n\n    @abstractmethod\n    def __call__(self, *args, **kwargs):\n        pass\n\n\nclass BaseOptimizerParamsHandler(BaseHandler):\n    \"\"\"\n    Base handler for logging optimizer parameters\n    \"\"\"\n\n    def __init__(self, optimizer, param_name=\"lr\", tag=None):\n        if not isinstance(optimizer, torch.optim.Optimizer):\n            raise TypeError(\"Argument optimizer should be of type torch.optim.Optimizer, \"\n                            \"but given {}\".format(type(optimizer)))\n\n        self.optimizer = optimizer\n        self.param_name = param_name\n        self.tag = tag\n\n\nclass BaseOutputHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log engine's output and/or metrics\n    \"\"\"\n\n    def __init__(self, tag, metric_names=None, output_transform=None, another_engine=None, global_step_transform=None):\n\n        if metric_names is not None:\n            if not (isinstance(metric_names, list) or (isinstance(metric_names, str) and metric_names == \"all\")):\n                raise TypeError(\"metric_names should be either a list or equal 'all', \"\n                                \"got {} instead.\".format(type(metric_names)))\n\n        if output_transform is not None and not callable(output_transform):\n            raise TypeError(\"output_transform should be a function, got {} instead.\"\n                            .format(type(output_transform)))\n\n        if output_transform is None and metric_names is None:\n            raise ValueError(\"Either metric_names or output_transform should be defined\")\n\n        if another_engine is not None:\n            if not isinstance(another_engine, Engine):\n                raise TypeError(\"Argument another_engine should be of type Engine, \"\n                                \"but given {}\".format(type(another_engine)))\n            warnings.warn(\"Use of another_engine is deprecated and will be removed in 0.2.1. \"\n                          \"Please use global_step_transform instead.\", DeprecationWarning)\n\n        if global_step_transform is not None and not callable(global_step_transform):\n            raise TypeError(\"global_step_transform should be a function, got {} instead.\"\n                            .format(type(global_step_transform)))\n\n        if global_step_transform is None:\n            def global_step_transform(engine, event_name):\n                return engine.state.get_event_attrib_value(event_name)\n\n        self.tag = tag\n        self.metric_names = metric_names\n        self.output_transform = output_transform\n        self.another_engine = another_engine\n        self.global_step_transform = global_step_transform\n\n    def _setup_output_metrics(self, engine):\n        \"\"\"Helper method to setup metrics to log\n        \"\"\"\n        metrics = {}\n        if self.metric_names is not None:\n            if isinstance(self.metric_names, str) and self.metric_names == \"all\":\n                metrics = engine.state.metrics\n            else:\n                for name in self.metric_names:\n                    if name not in engine.state.metrics:\n                        warnings.warn(\"Provided metric name '{}' is missing \"\n                                      \"in engine's state metrics: {}\".format(name, list(engine.state.metrics.keys())))\n                        continue\n                    metrics[name] = engine.state.metrics[name]\n\n        if self.output_transform is not None:\n            output_dict = self.output_transform(engine.state.output)\n\n            if not isinstance(output_dict, dict):\n                output_dict = {\"output\": output_dict}\n\n            metrics.update({name: value for name, value in output_dict.items()})\n        return metrics\n\n\nclass BaseWeightsScalarHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log model's weights as scalars.\n    \"\"\"\n\n    def __init__(self, model, reduction=torch.norm, tag=None):\n        if not isinstance(model, torch.nn.Module):\n            raise TypeError(\"Argument model should be of type torch.nn.Module, \"\n                            \"but given {}\".format(type(model)))\n\n        if not callable(reduction):\n            raise TypeError(\"Argument reduction should be callable, \"\n                            \"but given {}\".format(type(reduction)))\n\n        def _is_0D_tensor(t):\n            return isinstance(t, torch.Tensor) and t.ndimension() == 0\n\n        # Test reduction function on a random tensor\n        o = reduction(torch.rand(4, 2))\n        if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):\n            raise ValueError(\"Output of the reduction function should be a scalar, but got {}\".format(type(o)))\n\n        self.model = model\n        self.reduction = reduction\n        self.tag = tag\n\n\nclass BaseWeightsHistHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log model's weights as histograms.\n    \"\"\"\n\n    def __init__(self, model, tag=None):\n        if not isinstance(model, torch.nn.Module):\n            raise TypeError(\"Argument model should be of type torch.nn.Module, \"\n                            \"but given {}\".format(type(model)))\n\n        self.model = model\n        self.tag = tag\n", "path": "ignite/contrib/handlers/base_logger.py"}], "after_files": [{"content": "from abc import ABCMeta, abstractmethod\nimport numbers\nimport warnings\n\nimport torch\n\nfrom ignite.engine import State, Engine\nfrom ignite._six import with_metaclass\n\n\nclass BaseLogger(object):\n    \"\"\"\n    Base logger handler. See implementations: TensorboardLogger, VisdomLogger, PolyaxonLogger\n\n    \"\"\"\n    def attach(self, engine, log_handler, event_name):\n        \"\"\"Attach the logger to the engine and execute `log_handler` function at `event_name` events.\n\n        Args:\n            engine (Engine): engine object.\n            log_handler (callable): a logging handler to execute\n            event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.engine.Events`\n                or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.\n\n        \"\"\"\n        if event_name not in State.event_to_attr:\n            raise RuntimeError(\"Unknown event name '{}'\".format(event_name))\n\n        engine.add_event_handler(event_name, log_handler, self, event_name)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, type, value, traceback):\n        self.close()\n\n    def close(self):\n        pass\n\n\nclass BaseHandler(with_metaclass(ABCMeta, object)):\n\n    @abstractmethod\n    def __call__(self, *args, **kwargs):\n        pass\n\n\nclass BaseOptimizerParamsHandler(BaseHandler):\n    \"\"\"\n    Base handler for logging optimizer parameters\n    \"\"\"\n\n    def __init__(self, optimizer, param_name=\"lr\", tag=None):\n        if not isinstance(optimizer, torch.optim.Optimizer):\n            raise TypeError(\"Argument optimizer should be of type torch.optim.Optimizer, \"\n                            \"but given {}\".format(type(optimizer)))\n\n        self.optimizer = optimizer\n        self.param_name = param_name\n        self.tag = tag\n\n\nclass BaseOutputHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log engine's output and/or metrics\n    \"\"\"\n\n    def __init__(self, tag, metric_names=None, output_transform=None, another_engine=None, global_step_transform=None):\n\n        if metric_names is not None:\n            if not (isinstance(metric_names, list) or (isinstance(metric_names, str) and metric_names == \"all\")):\n                raise TypeError(\"metric_names should be either a list or equal 'all', \"\n                                \"got {} instead.\".format(type(metric_names)))\n\n        if output_transform is not None and not callable(output_transform):\n            raise TypeError(\"output_transform should be a function, got {} instead.\"\n                            .format(type(output_transform)))\n\n        if output_transform is None and metric_names is None:\n            raise ValueError(\"Either metric_names or output_transform should be defined\")\n\n        if another_engine is not None:\n            if not isinstance(another_engine, Engine):\n                raise TypeError(\"Argument another_engine should be of type Engine, \"\n                                \"but given {}\".format(type(another_engine)))\n            warnings.warn(\"Use of another_engine is deprecated and will be removed in 0.2.1. \"\n                          \"Please use global_step_transform instead.\", DeprecationWarning)\n\n        if global_step_transform is not None and not callable(global_step_transform):\n            raise TypeError(\"global_step_transform should be a function, got {} instead.\"\n                            .format(type(global_step_transform)))\n\n        if global_step_transform is None:\n            def global_step_transform(engine, event_name):\n                return engine.state.get_event_attrib_value(event_name)\n\n        self.tag = tag\n        self.metric_names = metric_names\n        self.output_transform = output_transform\n        self.another_engine = another_engine\n        self.global_step_transform = global_step_transform\n\n    def _setup_output_metrics(self, engine):\n        \"\"\"Helper method to setup metrics to log\n        \"\"\"\n        metrics = {}\n        if self.metric_names is not None:\n            if isinstance(self.metric_names, str) and self.metric_names == \"all\":\n                metrics = engine.state.metrics\n            else:\n                for name in self.metric_names:\n                    if name not in engine.state.metrics:\n                        warnings.warn(\"Provided metric name '{}' is missing \"\n                                      \"in engine's state metrics: {}\".format(name, list(engine.state.metrics.keys())))\n                        continue\n                    metrics[name] = engine.state.metrics[name]\n\n        if self.output_transform is not None:\n            output_dict = self.output_transform(engine.state.output)\n\n            if not isinstance(output_dict, dict):\n                output_dict = {\"output\": output_dict}\n\n            metrics.update({name: value for name, value in output_dict.items()})\n        return metrics\n\n\nclass BaseWeightsScalarHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log model's weights as scalars.\n    \"\"\"\n\n    def __init__(self, model, reduction=torch.norm, tag=None):\n        if not isinstance(model, torch.nn.Module):\n            raise TypeError(\"Argument model should be of type torch.nn.Module, \"\n                            \"but given {}\".format(type(model)))\n\n        if not callable(reduction):\n            raise TypeError(\"Argument reduction should be callable, \"\n                            \"but given {}\".format(type(reduction)))\n\n        def _is_0D_tensor(t):\n            return isinstance(t, torch.Tensor) and t.ndimension() == 0\n\n        # Test reduction function on a tensor\n        o = reduction(torch.ones(4, 2))\n        if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):\n            raise ValueError(\"Output of the reduction function should be a scalar, but got {}\".format(type(o)))\n\n        self.model = model\n        self.reduction = reduction\n        self.tag = tag\n\n\nclass BaseWeightsHistHandler(BaseHandler):\n    \"\"\"\n    Helper handler to log model's weights as histograms.\n    \"\"\"\n\n    def __init__(self, model, tag=None):\n        if not isinstance(model, torch.nn.Module):\n            raise TypeError(\"Argument model should be of type torch.nn.Module, \"\n                            \"but given {}\".format(type(model)))\n\n        self.model = model\n        self.tag = tag\n", "path": "ignite/contrib/handlers/base_logger.py"}]}