# !pip install ray[tune]
!pip install optuna==2.9.1

"""
Explanation: Running Tune experiments with Optuna
In this tutorial we introduce Optuna, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with Optuna and, as a result, allow you to seamlessly scale up a Optuna optimization process - without sacrificing performance.
Similar to Ray Tune, Optuna is an automatic hyperparameter optimization software framework, particularly designed for machine learning. It features an imperative ("how" over "what" emphasis), define-by-run style user API. With Optuna, a user has the ability to dynamically construct the search spaces for the hyperparameters. Optuna falls in the domain of "derivative-free optimization" and "black-box optimization".
In this example we minimize a simple objective to briefly demonstrate the usage of Optuna with Ray Tune via OptunaSearch, including examples of conditional search spaces (string together relationships between hyperparameters), and the multi-objective problem (measure trade-offs among all important metrics). It's useful to keep in mind that despite the emphasis on machine learning experiments, Ray Tune optimizes any implicit or explicit objective. Here we assume optuna==2.9.1 library is installed. To learn more, please refer to Optuna website.
Please note that sophisticated schedulers, such as AsyncHyperBandScheduler, may not work correctly with multi-objective optimization, since they typically expect a scalar score to compare fitness among trials.
End of explanation
"""


import time
from typing import Dict, Optional, Any

import ray
from ray import tune
from ray.tune.suggest import ConcurrencyLimiter
from ray.tune.suggest.optuna import OptunaSearch

ray.init(configure_logging=False)

"""
Explanation: Click below to see all the imports we need for this example.
You can also launch directly into a Binder instance to run this notebook yourself.
Just click on the rocket symbol at the top of the navigation.
End of explanation
"""


def evaluate(step, width, height, activation):
    time.sleep(0.1)
    activation_boost = 10 if activation=="relu" else 0
    return (0.1 + width * step / 100) ** (-1) + height * 0.1 + activation_boost

"""
Explanation: Let's start by defining a simple evaluation function.
An explicit math formula is queried here for demonstration, yet in practice this is typically a black-box function-- e.g. the performance results after training an ML model.
We artificially sleep for a bit (0.1 seconds) to simulate a long-running ML experiment.
This setup assumes that we're running multiple steps of an experiment while tuning three hyperparameters,
namely width, height, and activation.
End of explanation
"""


def objective(config):
    for step in range(config["steps"]):
        score = evaluate(step, config["width"], config["height"], config["activation"])
        tune.report(iterations=step, mean_loss=score)
              

"""
Explanation: Next, our objective function to be optimized takes a Tune config, evaluates the score of your experiment in a training loop,
and uses tune.report to report the score back to Tune.
End of explanation
"""


search_space = {
    "steps": 100,
    "width": tune.uniform(0, 20),
    "height": tune.uniform(-100, 100),
    "activation": tune.choice(["relu", "tanh"]),
}

"""
Explanation: Next we define a search space. The critical assumption is that the optimal hyperparamters live within this space. Yet, if the space is very large, then those hyperparamters may be difficult to find in a short amount of time.
The simplest case is a search space with independent dimensions. In this case, a config dictionary will suffice.
End of explanation
"""


algo = OptunaSearch()

"""
Explanation: Here we define the Optuna search algorithm:
End of explanation
"""


algo = ConcurrencyLimiter(algo, max_concurrent=4)


"""
Explanation: We also constrain the the number of concurrent trials to 4 with a ConcurrencyLimiter.
End of explanation
"""


num_samples = 1000

# We override here for our smoke tests.
num_samples = 10

"""
Explanation: The number of samples is the number of hyperparameter combinations that will be tried out. This Tune run is set to 1000 samples.
(you can decrease this if it takes too long on your machine).
End of explanation
"""


analysis = tune.run(
    objective,
    search_alg=algo,
    metric="mean_loss",
    mode="min",
    num_samples=num_samples,
    config=search_space
)

"""
Explanation: Finally, we run the experiment to "min"imize the "mean_loss" of the objective by searching search_space via algo, num_samples times. This previous sentence is fully characterizes the search problem we aim to solve. With this in mind, notice how efficient it is to execute tune.run().
End of explanation
"""


print("Best hyperparameters found were: ", analysis.best_config)

"""
Explanation: And now we have the hyperparameters found to minimize the mean loss.
End of explanation
"""


initial_params = [
    {"width": 1, "height": 2, "activation": "relu"},
    {"width": 4, "height": 2, "activation": "relu"},
]

"""
Explanation: Providing an initial set of hyperparameters
While defining the search algorithm, we may choose to provide an initial set of hyperparameters that we believe are especially promising or informative, and
pass this information as a helpful starting point for the OptunaSearch object.
End of explanation
"""


searcher = OptunaSearch(points_to_evaluate=initial_params)
algo = ConcurrencyLimiter(searcher, max_concurrent=4)

"""
Explanation: Now the search_alg built using OptunaSearch takes points_to_evaluate.
End of explanation
"""


analysis = tune.run(
    objective,
    search_alg=algo,
    metric="mean_loss",
    mode="min",
    num_samples=num_samples,
    config=search_space
)

"""
Explanation: And run the experiment with initial hyperparameter evaluations:
End of explanation
"""


print("Best hyperparameters found were: ", analysis.best_config)

"""
Explanation: We take another look at the optimal hyperparamters.
End of explanation
"""


def define_by_run_func(trial) -> Optional[Dict[str, Any]]:
    """Define-by-run function to create the search space.

    Ensure no actual computation takes place here. That should go into
    the trainable passed to ``tune.run`` (in this example, that's
    ``objective``).

    For more information, see https://optuna.readthedocs.io/en/stable\
    /tutorial/10_key_features/002_configurations.html

    This function should either return None or a dict with constant values.
    """

    activation = trial.suggest_categorical("activation", ["relu", "tanh"])

    # Define-by-run allows for conditional search spaces.
    if activation == "relu":
        trial.suggest_float("width", 0, 20)
        trial.suggest_float("height", -100, 100)
    else:
        trial.suggest_float("width", -1, 21)
        trial.suggest_float("height", -101, 101)
        
    # Return all constants in a dictionary.
    return {"steps": 100}

"""
Explanation: Conditional search spaces
Sometimes we may want to build a more complicated search space that has conditional dependencies on other hyperparameters. In this case, we pass a define-by-run function to the search_alg argument in ray.tune().
End of explanation
"""


searcher = OptunaSearch(space=define_by_run_func, metric="mean_loss", mode="min")
algo = ConcurrencyLimiter(searcher, max_concurrent=4)

"""
Explanation: As before, we create the search_alg from OptunaSearch and ConcurrencyLimiter, this time we define the scope of search via the space argument and provide no initialization. We also must specific metric and mode when using space.
End of explanation
"""


analysis = tune.run(
    objective,
    search_alg=algo,
    num_samples=num_samples
)

"""
Explanation: Running the experiment with a define-by-run search space:
End of explanation
"""


print("Best hyperparameters for loss found were: ", analysis.get_best_config("mean_loss", "min"))

"""
Explanation: We take a look again at the optimal hyperparameters.
End of explanation
"""


def multi_objective(config):
    # Hyperparameters
    width, height = config["width"], config["height"]

    for step in range(config["steps"]):
        # Iterative training function - can be any arbitrary training procedure
        intermediate_score = evaluate(step, config["width"], config["height"], config["activation"])
        # Feed the score back back to Tune.
        tune.report(
           iterations=step, loss=intermediate_score, gain=intermediate_score * width
        )

"""
Explanation: Multi-objective optimization
Finally, let's take a look at the multi-objective case.
End of explanation
"""


searcher = OptunaSearch(metric=["loss", "gain"], mode=["min", "max"])
algo = ConcurrencyLimiter(searcher, max_concurrent=4)

analysis = tune.run(
    multi_objective,
    search_alg=algo,
    num_samples=num_samples,
    config=search_space
)

"""
Explanation: We define the OptunaSearch object this time with metric and mode as list arguments.
End of explanation
"""


ray.shutdown()

"""
Explanation: Now there are two hyperparameter sets for the two objectives.
print("Best hyperparameters for loss found were: ", analysis.get_best_config("loss", "min"))
print("Best hyperparameters for gain found were: ", analysis.get_best_config("gain", "max"))
We can mix-and-match the use of initial hyperparameter evaluations, conditional search spaces via define-by-run functions, and multi-objective tasks. This is also true of scheduler usage, with the exception of multi-objective optimization-- schedulers typically rely on a single scalar score, rather than the two scores we use here: loss, gain.
End of explanation
"""


