class_docstr: Forecaster base model for lstm, seq2seq, tcn and nbeats forecasters.
class_docstr_tok: ["Forecaster","base","model","for","lstm",",","seq2seq",",","tcn","and","nbeats","forecasters","."]
docstr: This method will traverse existing optimization methods(onnxruntime, openvino, jit, ...)
  and save the model with minimum latency under the given data and search
  restrictions(accelerator, precision, accuracy_criterion) in `forecaster.accelerated_model`.
  This method is required to call before `predict` and `evaluate`.
  Now this function is only for non-distributed model.
  
  :param train_data: Data used for training model. Users should be careful with this parameter
         since this data might be exposed to the model, which causing data leak.
         The train_data support following formats:
  
         | 1. a numpy ndarray tuple (x, y):
         | x's shape is (num_samples, lookback, feature_dim) where lookback and feature_dim
         | should be the same as past_seq_len and input_feature_num.
         | y's shape is (num_samples, horizon, target_dim), where horizon and target_dim
         | should be the same as future_seq_len and output_feature_num.
         |
         | 2. pytorch dataloader:
         | the dataloader should return x, y in each iteration with the shape as following:
         | x's shape is (num_samples, lookback, feature_dim) where lookback and feature_dim
         | should be the same as past_seq_len and input_feature_num.
         | y's shape is (num_samples, horizon, target_dim), where horizon and target_dim
         | should be the same as future_seq_len and output_feature_num.
         | The batch_size of this dataloader is important as well, users may want to set it
         | to the same batch size you may want to use the model in real deploy environment.
         | E.g. batch size should be set to 1 if you would like to use the accelerated model
         | in an online service.
         |
         | 3. A bigdl.chronos.data.tsdataset.TSDataset instance:
         | Forecaster will automatically process the TSDataset.
         | By default, TSDataset will be transformed to a pytorch dataloader,
         | which is memory-friendly while a little bit slower.
         | Users may call `roll` on the TSDataset before calling `fit`
         | Then the training speed will be faster but will consume more memory.
  
  :param validation_data(optional): This is only needed when users care about the possible
         accuracy drop. The validation_data support following formats:
  
         | 1. a numpy ndarray tuple (x, y):
         | x's shape is (num_samples, lookback, feature_dim) where lookback and feature_dim
         | should be the same as past_seq_len and input_feature_num.
         | y's shape is (num_samples, horizon, target_dim), where horizon and target_dim
         | should be the same as future_seq_len and output_feature_num.
         |
         | 2. pytorch dataloader:
         | the dataloader should return x, y in each iteration with the shape as following:
         | x's shape is (num_samples, lookback, feature_dim) where lookback and feature_dim
         | should be the same as past_seq_len and input_feature_num.
         | y's shape is (num_samples, horizon, target_dim), where horizon and target_dim
         | should be the same as future_seq_len and output_feature_num.
         |
         | 3. A bigdl.chronos.data.tsdataset.TSDataset instance:
         | Forecaster will automatically process the TSDataset.
         | By default, TSDataset will be transformed to a pytorch dataloader,
         | which is memory-friendly while a little bit slower.
         | Users may call `roll` on the TSDataset before calling `fit`
         | Then the training speed will be faster but will consume more memory.
  
  :param batch_size: Number of batch size you want to use the model in real deploy
         environment. The value defaults to 32. If you input a pytorch dataloader for
         `train_data`, the batch_size will follow the batch_size setted in `train_data`.
  :param thread_num: int, the num of thread limit. The value is set to None by
         default where no limit is set.
  :param accelerator: (optional) Use accelerator 'None', 'onnxruntime',
         'openvino', 'jit', defaults to None. If not None, then will only find the
         model with this specific accelerator.
  :param precision: (optional) Supported type: 'int8', 'bf16', 'fp32'.
         Defaults to None which represents no precision limit. If not None, then will
         only find the model with this specific precision.
  :param metric: (optional) A str represent corresponding metric which is used for calculating
         accuracy.
  :param accuracy_criterion: (optional) a float represents tolerable
         accuracy drop percentage, defaults to None meaning no accuracy control.
  
  Example:
      >>> # obtain optimized model
      >>> forecaster.optimize(train_data, val_data, thread_num=1)
      >>> pred = forecaster.predict(data)
code: def optimize(
      self,
      train_data,
      validation_data=None,
      batch_size: int = 32,
      thread_num: Optional[int] = None,
      accelerator: Optional[str] = None,
      precision: Optional[str] = None,
      metric: str = "mse",
      accuracy_criterion: Optional[float] = None,
  ):
      """
      This method will traverse existing optimization methods(onnxruntime, openvino, jit, ...)
      and save the model with minimum latency under the given data and search
      restrictions(accelerator, precision, accuracy_criterion) in `forecaster.accelerated_model`.
      This method is required to call before `predict` and `evaluate`.
      Now this function is only for non-distributed model.
  
      :param train_data: Data used for training model. Users should be careful with this parameter
             since this data might be exposed to the model, which causing data leak.
             The train_data support following formats:
  
             | 1. a numpy ndarray tuple (x, y):
             | x's shape is (num_samples, lookback, feature_dim) where lookback and feature_dim
             | should be the same as past_seq_len and input_feature_num.
             | y's shape is (num_samples, horizon, target_dim), where horizon and target_dim
             | should be the same as future_seq_len and output_feature_num.
             |
             | 2. pytorch dataloader:
             | the dataloader should return x, y in each iteration with the shape as following:
             | x's shape is (num_samples, lookback, feature_dim) where lookback and feature_dim
             | should be the same as past_seq_len and input_feature_num.
             | y's shape is (num_samples, horizon, target_dim), where horizon and target_dim
             | should be the same as future_seq_len and output_feature_num.
             | The batch_size of this dataloader is important as well, users may want to set it
             | to the same batch size you may want to use the model in real deploy environment.
             | E.g. batch size should be set to 1 if you would like to use the accelerated model
             | in an online service.
             |
             | 3. A bigdl.chronos.data.tsdataset.TSDataset instance:
             | Forecaster will automatically process the TSDataset.
             | By default, TSDataset will be transformed to a pytorch dataloader,
             | which is memory-friendly while a little bit slower.
             | Users may call `roll` on the TSDataset before calling `fit`
             | Then the training speed will be faster but will consume more memory.
  
      :param validation_data(optional): This is only needed when users care about the possible
             accuracy drop. The validation_data support following formats:
  
             | 1. a numpy ndarray tuple (x, y):
             | x's shape is (num_samples, lookback, feature_dim) where lookback and feature_dim
             | should be the same as past_seq_len and input_feature_num.
             | y's shape is (num_samples, horizon, target_dim), where horizon and target_dim
             | should be the same as future_seq_len and output_feature_num.
             |
             | 2. pytorch dataloader:
             | the dataloader should return x, y in each iteration with the shape as following:
             | x's shape is (num_samples, lookback, feature_dim) where lookback and feature_dim
             | should be the same as past_seq_len and input_feature_num.
             | y's shape is (num_samples, horizon, target_dim), where horizon and target_dim
             | should be the same as future_seq_len and output_feature_num.
             |
             | 3. A bigdl.chronos.data.tsdataset.TSDataset instance:
             | Forecaster will automatically process the TSDataset.
             | By default, TSDataset will be transformed to a pytorch dataloader,
             | which is memory-friendly while a little bit slower.
             | Users may call `roll` on the TSDataset before calling `fit`
             | Then the training speed will be faster but will consume more memory.
  
      :param batch_size: Number of batch size you want to use the model in real deploy
             environment. The value defaults to 32. If you input a pytorch dataloader for
             `train_data`, the batch_size will follow the batch_size setted in `train_data`.
      :param thread_num: int, the num of thread limit. The value is set to None by
             default where no limit is set.
      :param accelerator: (optional) Use accelerator 'None', 'onnxruntime',
             'openvino', 'jit', defaults to None. If not None, then will only find the
             model with this specific accelerator.
      :param precision: (optional) Supported type: 'int8', 'bf16', 'fp32'.
             Defaults to None which represents no precision limit. If not None, then will
             only find the model with this specific precision.
      :param metric: (optional) A str represent corresponding metric which is used for calculating
             accuracy.
      :param accuracy_criterion: (optional) a float represents tolerable
             accuracy drop percentage, defaults to None meaning no accuracy control.
  
      Example:
          >>> # obtain optimized model
          >>> forecaster.optimize(train_data, val_data, thread_num=1)
          >>> pred = forecaster.predict(data)
      """
      # check distribution
      if self.distributed:
          invalidInputError(
              False,
              "optimize has not been supported for distributed "
              "forecaster. You can call .to_local() to transform the "
              "forecaster to a non-distributed version.",
          )
      # check fit
      if not self.fitted:
          invalidInputError(
              False,
              "You must call fit or restore first before calling optimize!",
          )
  
      # turn tsdataset to dataloader
      if isinstance(train_data, TSDataset):
          _rolled = train_data.numpy_x is None
          train_data = train_data.to_torch_data_loader(
              batch_size=batch_size,
              roll=_rolled,
              lookback=self.data_config["past_seq_len"],
              horizon=self.data_config["future_seq_len"],
              feature_col=train_data.roll_feature,
              target_col=train_data.roll_target,
              shuffle=False,
          )
  
      if validation_data is not None and isinstance(
          validation_data, TSDataset
      ):
          _rolled = validation_data.numpy_x is None
          validation_data = validation_data.to_torch_data_loader(
              batch_size=batch_size,
              roll=_rolled,
              lookback=self.data_config["past_seq_len"],
              horizon=self.data_config["future_seq_len"],
              feature_col=validation_data.roll_feature,
              target_col=validation_data.roll_target,
              shuffle=False,
          )
  
      # turn numpy into dataloader
      if isinstance(train_data, (tuple, list)):
          invalidInputError(
              len(train_data) == 2,
              f"train_data should be a 2-dim tuple, but get {len(train_data)}-dim.",
          )
          train_data = DataLoader(
              TensorDataset(
                  torch.from_numpy(train_data[0]),
                  torch.from_numpy(train_data[1]),
              ),
              batch_size=batch_size,
              shuffle=False,
          )
  
      if validation_data is not None and isinstance(
          validation_data, (tuple, list)
      ):
          invalidInputError(
              len(validation_data) == 2,
              f"validation_data should be a 2-dim tuple, but get "
              f"{len(validation_data)}-dim.",
          )
          validation_data = DataLoader(
              TensorDataset(
                  torch.from_numpy(validation_data[0]),
                  torch.from_numpy(validation_data[1]),
              ),
              batch_size=batch_size,
              shuffle=False,
          )
  
      # align metric
      if metric is not None:
          if validation_data is None:
              metric = None
          else:
              try:
                  metric = _str2optimizer_metric(metric)
              except Exception:
                  invalidInputError(
                      False,
                      "Unable to recognize the metric string you passed in.",
                  )
  
      dummy_input = torch.rand(
          1,
          self.data_config["past_seq_len"],
          self.data_config["input_feature_num"],
      )
      # remove channels_last methods
      excludes = [
          "fp32_channels_last",
          "fp32_ipex_channels_last",
          "bf16_channels_last",
          "bf16_ipex_channels_last",
          "jit_fp32_channels_last",
          "jit_bf16_channels_last",
          "jit_fp32_ipex_channels_last",
          "jit_bf16_ipex_channels_last",
      ]
      if not self.quantize_available:
          excludes = excludes + [
              "static_int8",
              "openvino_int8",
              "onnxruntime_int8_qlinear",
              "bf16",
              "bf16_ipex",
              "jit_bf16",
              "jit_bf16_ipex",
          ]
      from bigdl.chronos.pytorch import (
          TSInferenceOptimizer as InferenceOptimizer,
      )
  
      opt = InferenceOptimizer()
      opt.optimize(
          model=self.internal,
          training_data=train_data,
          validation_data=validation_data,
          metric=metric,
          direction="min",
          thread_num=thread_num,
          output_tensors=False,
          excludes=excludes,
          input_sample=dummy_input,
      )
      try:
          optim_model, option = opt.get_best_model(
              accelerator=accelerator,
              precision=precision,
              accuracy_criterion=accuracy_criterion,
          )
          self.accelerated_model = optim_model
          self.accelerate_method = option
      except Exception:
          invalidInputError(
              False,
              "Unable to find an optimized model that meets your conditions."
              "Maybe you can relax your search limit.",
          )
      self.optimized_model_output_tensor = False
      self.optimized_model_thread_num = thread_num
  
imports: from bigdl.chronos.forecaster.abstract import Forecaster
  from bigdl.chronos.forecaster.utils import *
  from bigdl.chronos.metric.forecast_metrics import Evaluator
  from typing import Optional
  import numpy
  import warnings
  import os
  from tempfile import TemporaryDirectory
  import torch
  from torch.utils.data import TensorDataset, DataLoader
  from .utils_hpo import GenericLightningModule, _format_metric_str, _config_has_search_space
  from bigdl.nano.utils.common import invalidOperationError, invalidInputError
  from bigdl.chronos.data.tsdataset import TSDataset
  from bigdl.chronos.pytorch.context_manager import DummyForecasterContextManager, ForecasterContextManager
  from bigdl.chronos.pytorch.utils import _pytorch_fashion_inference
label_desc: Use image node_id 6 for calling the BasePytorchForecaster obj's underlying member method code with example usage: obj.optimize(train_data, validation_data, batch_size, thread_num, accelerator, precision, metric, accuracy_criterion) without return types