Skip to content

Commit e1a37d2

Browse files
authored
Replace assert with raise ImportError for optuna/ray dependency checks (#46263)
The assert statements in default_hp_space_optuna() and default_hp_space_ray() are silently stripped when Python runs with the -O (optimize) flag. This allows the functions to proceed without the required library installed, leading to confusing NameErrors downstream instead of a clear ImportError. The wandb equivalent (default_hp_space_wandb) already uses the correct if/raise ImportError pattern. This change makes the optuna and ray functions consistent.
1 parent e977b06 commit e1a37d2

1 file changed

Lines changed: 4 additions & 2 deletions

File tree

src/transformers/trainer_utils.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,8 @@ def default_compute_objective(metrics: dict[str, float]) -> float:
452452
def default_hp_space_optuna(trial) -> dict[str, float]:
453453
from .integrations import is_optuna_available
454454

455-
assert is_optuna_available(), "This function needs Optuna installed: `pip install optuna`"
455+
if not is_optuna_available():
456+
raise ImportError("This function needs Optuna installed: `pip install optuna`")
456457
return {
457458
"learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True),
458459
"num_train_epochs": trial.suggest_int("num_train_epochs", 1, 5),
@@ -464,7 +465,8 @@ def default_hp_space_optuna(trial) -> dict[str, float]:
464465
def default_hp_space_ray(trial) -> dict[str, Any]:
465466
from .integrations import is_ray_tune_available
466467

467-
assert is_ray_tune_available(), "This function needs ray installed: `pip install ray[tune]`"
468+
if not is_ray_tune_available():
469+
raise ImportError("This function needs ray installed: `pip install ray[tune]`")
468470
from ray import tune
469471

470472
return {

0 commit comments

Comments
 (0)