Skip to content

No Validation Loss logged (possibly related to train_on_responses_only?) #1019

Closed
unslothai/unsloth-zoo
#164

Description

@selalipop

Evaluations are being run, but no validation loss is logged or sent to WandB

The console shows that eval is running, but displays a table along the lines of:

eval loss validation loss
1 no log
.9 no log
.8 no log

WandB shows evidence validation run occurs, but doesn't display loss either:
image

from trl import SFTTrainer
from transformers import TrainingArguments, DataCollatorForSeq2Seq
from unsloth import is_bfloat16_supported
import os
os.environ["WANDB_PROJECT"] = "my_project"  # name your W&B project
os.environ["WANDB_LOG_MODEL"] = "checkpoint"  # log all model checkpoints


trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = train_dataset,
    eval_dataset=validation_dataset,
    dataset_text_field = "text",
    max_seq_length = max_seq_length,
    data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer),
    dataset_num_proc = 2,
    packing = False, # Can make training 5x faster for short sequences.
     args = TrainingArguments(
        fp16_full_eval = True,
        per_device_eval_batch_size = 2,
        eval_accumulation_steps = 4,
        report_to = "wandb",
        run_name = "run-name-here",
        per_device_train_batch_size = 4,
        gradient_accumulation_steps = 4,
        gradient_checkpointing=True,
        warmup_steps = 5,
        do_predict=True,
        logging_first_step=True,
        num_train_epochs = 3, # Set this for 1 full training run.
        save_steps = 88,
        evaluation_strategy="steps",
        eval_steps=88,
        do_eval=True, 
        learning_rate = 1e-4,
        fp16 = not is_bfloat16_supported(),
        bf16 = is_bfloat16_supported(),
        logging_steps = 1,
        optim = "adamw_8bit",
        weight_decay = 0.01,
        lr_scheduler_type = "linear",
        seed = 3407,
        output_dir = "outputs",
    ),
)

---

from unsloth.chat_templates import train_on_responses_only
trainer = train_on_responses_only(
    trainer,
    instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n",
    response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",
)


trainer.train()

Very similar settings work when using plain SFTTrainer in another project

Activity

  1. thak123 commented on Sep 13, 2024

    @thak123

    Yes I have been facing the same issues. I am thinking of training in parts (n-steps) and evaluating at the end of the steps and continuing the training manually for more steps until the Eval and train loss values permit.

  2. danielhanchen commented on Sep 13, 2024

    @danielhanchen
    Member

    Will investigate this asap!

  3. danielhanchen commented on Sep 21, 2024

    @danielhanchen
    Member

    Apologies just fixed!

  4. added
    fixed - pending confirmation
    and removed
    currently fixing
    URGENT BUG
    on Sep 21, 2024
  5. alexanderfrey commented on Nov 11, 2024

    @alexanderfrey

    Facing same issue. Sure this is fixed ? What is the commit hash ?

  6. alexanderfrey commented on Nov 11, 2024

    @alexanderfrey

    I'm not using train_on_completions btw. maybe I should try with that and see what comes out...

  7. alexanderfrey commented on Nov 12, 2024

    @alexanderfrey

    Ok, I tried now with train_on_completions and still no validation loss.

  8. sree-sphere commented on Feb 12, 2025

    @sree-sphere

    I fixed it by redefining the class from transformers. It worked for SFT, DPO, ORPO but not the latest GRPO which I am currently working on.
    Here's what I used

    from typing import Any, Dict, List, Optional, cast
    from transformers.trainer_callback import TrainerCallback
    import wandb
    from utils import training_state, logger
    
    
    class CustomTrainerCallback(TrainerCallback):
        def __init__(self) -> None:
            self.loss_history: List[Dict[str, Any]] = []
            self.validation_loss_history: List[Dict[str, Any]] = []
    
        def on_log(self, args: Any, state: Any, control: Any, logs: Optional[Dict[str, float]] = None, **kwargs: Any) -> None:
            if logs:
                if "loss" in logs:
                    training_state["steps"] = state.global_step
                    training_state["current_loss"] = logs["loss"]
                    if "loss_history" not in training_state:
                        training_state["loss_history"] = []
                    loss_history = training_state["loss_history"]
                    loss_history.append({"step": state.global_step, "training_loss": logs["loss"]})
                    logger.info(f"on_log (training): step {state.global_step} loss {logs['loss']}")  # debug
    
                    try:
                        wandb.log({"training_loss": logs["loss"], "step": state.global_step})
                    except Exception as e:
                        logger.warning(f"Warning: Failed to log to wandb: {str(e)}")
    
                if "eval_loss" in logs:
                    validation_loss = logs["eval_loss"]
                    if "validation_loss_history" not in training_state:
                        training_state["validation_loss_history"] = []
                    validation_loss_history = training_state["validation_loss_history"]
                    validation_loss_history.append({"step": state.global_step, "validation_loss": validation_loss})
                    logger.info(f"on_log (eval): step {state.global_step} eval_loss {validation_loss}")  # to debug
    
                    try:
                        wandb.log({"validation_loss": validation_loss, "step": state.global_step})
                    except Exception as e:
                        logger.warning(f"Warning: Failed to log validation loss to wandb: {str(e)}")
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    fixed - pending confirmationgood first issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions