Please review my hyperparameter sweep (using it to optimize finetuning a Mask2Former on a custom dataset).
rom optuna.pruners import MedianPruner from transformers import Trainer, EarlyStoppingCallback, TrainerCallback
prune bad trials early, but let a few warm up
pruner = MedianPruner( n_startup_trials=5, # allow 5 random trials before pruning n_warmup_steps=3, # wait 3 epochs before pruning interval_steps=1 # check every epoch )
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
model init for sweep (no model= passed to Trainer)
def model_init(): return AutoModelForUniversalSegmentation.from_pretrained( CONFIG["pretrained_model"], id2label=CONFIG["id2label"], label2id=CONFIG["label2id"], ignore_mismatched_sizes=True, )
callback to log LR
class LogLearningRateCallback(TrainerCallback): def on_log(self, args, state, control, logs=None, **kwargs): optimizer = kwargs.get("optimizer", None) if optimizer is None or logs is None: return current_lr = optimizer.param_groups[0]["lr"] logs["lr"] = f"{current_lr:.2e}" # e.g., 3.20e-05
run sweep
def compute_objective(metrics): loss = metrics.get("eval_loss")
return loss if loss is not None else float("inf")
best_run = trainer.hyperparameter_search( direction="minimize", # minimize eval_loss compute_objective=compute_objective, hp_space=hp_space, # search space n_trials=50, # trial count backend="optuna", # use Optuna pruner=pruner, # prune )
Here's a review of your hyperparameter sweep setup for fine-tuning Mask2Former, with key observations and recommendations:
Key Issues & Recommendations
1. ReduceLROnPlateau Scheduler Parameters Are Not Tuned
Issue: The patience and threshold parameters for reduce_lr_on_plateau are not being used because they aren’t part of the TrainingArguments. The HuggingFace Trainer doesn’t expose these parameters for this scheduler.
Impact: The scheduler will use default values (not the suggested ones), rendering the tuning ineffective.
Fix:
Option 1: Remove reduce_lr_on_plateau from the scheduler options unless you can hardcode its parameters.
Option 2: Use a custom scheduler or subclass Trainer to pass parameters (complex).
2. Evaluation Frequency Must Align with Pruner
Issue: The pruner uses n_warmup_steps=3 and interval_steps=1, assuming evaluations happen every epoch. Ensure TrainingArguments has evaluation_strategy="epoch".
Fix: Verify TrainingArguments are configured with:
Issue: Using eval_loss as the objective may not be ideal for segmentation tasks like Mask2Former. Metrics like mIoU (mean Intersection over Union) are more relevant.
Fix: Modify compute_objective to use a segmentation metric:
def compute_objective(metrics):
miou = metrics.get("eval_miou")
return 1 - miou if miou is not None else float("inf") # Minimize 1-mIoU
Ensure compute_metrics_filtered returns miou.
4. Hyperparameter Space Improvements
Suggested Additions:
Batch Size: Add batch size tuning (if not fixed).
Number of Epochs: Include as a hyperparameter if not fixed.
Issue: The keys for reduce_lr_on_plateau parameters are prefixed with lr_scheduler_, which aren’t recognized. Even if parameters were tunable, this would cause errors.
Fix: Remove the prefix (though this won’t fix the underlying issue with parameter exposure):
space["patience"] = ... # Still ineffective without proper exposure in TrainingArguments