code: def _evaluate_grid_hyperparameters_multiseries(
      forecaster,
      series: pd.DataFrame,
      param_grid: dict,
      steps: int,
      metric: Union[str, Callable, list],
      initial_train_size: int,
      fixed_train_size: bool = True,
      gap: int = 0,
      allow_incomplete_fold: bool = True,
      levels: Optional[Union[str, list]] = None,
      exog: Optional[Union[pd.Series, pd.DataFrame]] = None,
      lags_grid: Optional[Union[list, dict]] = None,
      refit: Optional[Union[bool, int]] = False,
      return_best: bool = True,
      n_jobs: Optional[Union[int, str]] = "auto",
      verbose: bool = True,
      show_progress: bool = True,
  ) -> pd.DataFrame:
      """
      Evaluate parameter values for a Forecaster object using multi-series backtesting.
  
      Parameters
      ----------
      forecaster : ForecasterAutoregMultiSeries, ForecasterAutoregMultiSeriesCustom, ForecasterAutoregMultiVariate
          Forecaster model.
      series : pandas DataFrame
          Training time series.
      param_grid : dict
          Dictionary with parameters names (`str`) as keys and lists of parameter
          settings to try as values.
      steps : int
          Number of steps to predict.
      metric : str, Callable, list
          Metric used to quantify the goodness of fit of the model.
  
          - If `string`: {'mean_squared_error', 'mean_absolute_error',
          'mean_absolute_percentage_error', 'mean_squared_log_error'}
          - If `Callable`: Function with arguments y_true, y_pred that returns
          a float.
          - If `list`: List containing multiple strings and/or Callables.
      initial_train_size : int
          Number of samples in the initial train split.
      fixed_train_size : bool, default `True`
          If True, train size doesn't increase but moves by `steps` in each iteration.
      gap : int, default `0`
          Number of samples to be excluded after the end of each training set and
          before the test set.
      allow_incomplete_fold : bool, default `True`
          Last fold is allowed to have a smaller number of samples than the
          `test_size`. If `False`, the last fold is excluded.
      levels : str, list, default `None`
          level (`str`) or levels (`list`) at which the forecaster is optimized.
          If `None`, all levels are taken into account. The resulting metric will be
          the average of the optimization of all levels.
      exog : pandas Series, pandas DataFrame, default `None`
          Exogenous variable/s included as predictor/s. Must have the same
          number of observations as `y` and should be aligned so that y[i] is
          regressed on exog[i].
      lags_grid : list, dict, default `None`
          Lists of lags to try, containing int, lists, numpy ndarray, or range
          objects. If `dict`, the keys are used as labels in the `results`
          DataFrame, and the values are used as the lists of lags to try. Ignored
          if the forecaster is an instance of `ForecasterAutoregCustom` or
          `ForecasterAutoregMultiSeriesCustom`.
      refit : bool, int, default `False`
          Whether to re-fit the forecaster in each iteration. If `refit` is an integer,
          the Forecaster will be trained every that number of iterations.
      return_best : bool, default `True`
          Refit the `forecaster` using the best found parameters on the whole data.
      verbose : bool, default `True`
          Print number of folds used for cv or backtesting.
  
      Returns
      -------
      results : pandas DataFrame
          Results for each combination of parameters.
  
          - column levels: levels configuration for each iteration.
          - column lags: lags configuration for each iteration.
          - column params: parameters configuration for each iteration.
          - column metric: metric value estimated for each iteration. The resulting
          metric will be the average of the optimization of all levels.
          - additional n columns with param = value.
  
      """
  
      if (
          return_best
          and exog is not None
          and (len(exog) != len(series))
      ):
          raise ValueError(
              (
                  f"`exog` must have same number of samples as `series`. "
                  f"length `exog`: ({len(exog)}), length `series`: ({len(series)})"
              )
          )
  
      levels = _initialize_levels_model_selection_multiseries(
          forecaster=forecaster, series=series, levels=levels
      )
  
      lags_grid, lags_label = initialize_lags_grid(
          forecaster, lags_grid
      )
  
      lags_list = []
      params_list = []
      if not isinstance(metric, list):
          metric = [metric]
      metric_dict = {
          (m if isinstance(m, str) else m.__name__): [] for m in metric
      }
  
      if len(metric_dict) != len(metric):
          raise ValueError(
              "When `metric` is a `list`, each metric name must be unique."
          )
  
      print(
          f"{len(param_grid)*len(lags_grid)} models compared for {len(levels)} level(s). "
          f"Number of iterations: {len(param_grid)*len(lags_grid)}."
      )
  
      if show_progress:
          lags_grid_tqdm = tqdm(
              lags_grid.items(), desc="lags grid", position=0
          )  # ncols=90
          param_grid = tqdm(
              param_grid, desc="params grid", position=1, leave=False
          )
      else:
          lags_grid_tqdm = lags_grid.items()
  
      for lags_k, lags_v in lags_grid_tqdm:
          if (
              type(forecaster).__name__
              != "ForecasterAutoregMultiSeriesCustom"
          ):
              forecaster.set_lags(lags_v)
              lags_v = (
                  lags_k
                  if lags_label == "keys"
                  else forecaster.lags.copy()
              )
  
          for params in param_grid:
              forecaster.set_params(params)
              metrics_levels = backtesting_forecaster_multiseries(
                  forecaster=forecaster,
                  series=series,
                  exog=exog,
                  steps=steps,
                  levels=levels,
                  metric=metric,
                  initial_train_size=initial_train_size,
                  fixed_train_size=fixed_train_size,
                  gap=gap,
                  allow_incomplete_fold=allow_incomplete_fold,
                  refit=refit,
                  interval=None,
                  verbose=verbose,
                  n_jobs=n_jobs,
                  show_progress=False,
              )[0]
              warnings.filterwarnings(
                  "ignore",
                  category=RuntimeWarning,
                  message="The forecaster will be fit.*",
              )
  
              lags_list.append(lags_v)
              params_list.append(params)
              for m in metric:
                  m_name = m if isinstance(m, str) else m.__name__
                  metric_dict[m_name].append(
                      metrics_levels[m_name].mean()
                  )
  
      results = pd.DataFrame(
          {
              "levels": [levels] * len(lags_list),
              "lags": lags_list,
              "params": params_list,
              **metric_dict,
          }
      )
  
      results = results.sort_values(
          by=list(metric_dict.keys())[0], ascending=True
      )
      results = pd.concat(
          [results, results["params"].apply(pd.Series)], axis=1
      )
  
      if return_best:
          best_lags = results["lags"].iloc[0]
          best_params = results["params"].iloc[0]
          best_metric = results[list(metric_dict.keys())[0]].iloc[0]
  
          if lags_label == "keys":
              best_lags = lags_grid[best_lags]
  
          if (
              type(forecaster).__name__
              != "ForecasterAutoregMultiSeriesCustom"
          ):
              forecaster.set_lags(best_lags)
              best_lags = forecaster.lags
          else:
              best_lags = "custom_predictors"
          forecaster.set_params(best_params)
  
          forecaster.fit(
              series=series, exog=exog, store_in_sample_residuals=True
          )
  
          print(
              f"`Forecaster` refitted using the best-found lags and parameters, "
              f"and the whole data set: \n"
              f"  Lags: {best_lags} \n"
              f"  Parameters: {best_params}\n"
              f"  Backtesting metric: {best_metric}\n"
              f"  Levels: {results['levels'].iloc[0]}\n"
          )
  
      return results
  
imports: from typing import Union, Tuple, Optional, Callable
  import numpy
  import pandas
  import warnings
  import logging
  from copy import deepcopy
  from joblib import Parallel, delayed, cpu_count
  from tqdm.auto import tqdm
  from sklearn.model_selection import ParameterGrid
  from sklearn.model_selection import ParameterSampler
  import optuna
  from optuna.samplers import TPESampler, RandomSampler
  from ..exceptions import LongTrainingWarning
  from ..exceptions import IgnoredArgumentWarning
  from ..model_selection.model_selection import _get_metric
  from ..model_selection.model_selection import _create_backtesting_folds
  from ..utils import check_backtesting_input
  from ..utils import initialize_lags_grid
  from ..utils import select_n_jobs_backtesting
label_desc: Use image node_id 6 for calling a global function with example usage: _evaluate_grid_hyperparameters_multiseries(forecaster, series, param_grid, steps, metric, initial_train_size, fixed_train_size, gap, allow_incomplete_fold, levels, exog, lags_grid, refit, return_best, n_jobs, verbose, show_progress) and returns: results