trl icon indicating copy to clipboard operation
trl copied to clipboard

PPOTrainer: Offline inference produces gibberish

Open kykim0 opened this issue 2 years ago • 6 comments

Hello,

I'm using PPOTrainer for LM fine-tuning and encountering an issue where the model generates gibberish outputs during inference. I'm wondering if this indicates a potential bug in the code, or more likely an issue with my code. To rule out any training-related issues, I generated outputs every few steps during training using PPOTrainer.generate(), and this gave fine results. However, when I load the model saved with PPOTrainer.save_pretrained() and perform inference (following the example in https://huggingface.co/docs/trl/main/en/use_model) on the same set of prompts, it produces gibberish.

I suspect that there might be a subtle issue with the offline inference setup, such as not loading the model correctly, that is causing the issue. On the other hand, the example provided in the doc is so simple that I'm struggling to identify what the issue could be.

For the training code, I mostly followed the example given in StackLLaMa. If it's helpful, here is a snippet of the training code:

model_kwargs = dict(
    revision=model_args.model_revision,
    trust_remote_code=model_args.trust_remote_code,
    use_flash_attention_2=model_args.use_flash_attention_2,
    torch_dtype=torch_dtype,
    use_cache=False if training_args.gradient_checkpointing else True,
    device_map=get_kbit_device_map(),
    quantization_config=get_quantization_config(model_args),
)

model = AutoModelForCausalLMWithValueHead.from_pretrained(
    model_args.model_name_or_path,
    load_in_8bit=True,
    peft_config=get_peft_config(model_args),
    **model_kwargs,
)
...
ppo_trainer = PPOTrainer(
    config=ppo_config,
    model=model,
    ref_model=None,
    tokenizer=tokenizer,
    dataset=train_dataset,
    data_collator=collator,
)
...

generation_kwargs = {
    "min_length": -1,
    "top_k": 0.0,
    "top_p": 1.0,
    "do_sample": True,
    "max_new_tokens": training_args.output_max_length,
    "pad_token_id": tokenizer.eos_token_id,
}
...
for step, batch in tqdm(
    enumerate(ppo_trainer.dataloader),
    desc="Train step: ",
    disable=not accelerator.is_local_main_process,
    total=min(len(ppo_trainer.dataloader), ppo_config.steps),
):
    if step >= ppo_config.steps: break

    # Do a small sanity eval for sanity check.
    if step % 5 == 0:
        small_eval(step, ppo_trainer, rmodel, eval_dataloader)

    query_tensors = batch["input_ids"]

    # Get responses from the base model.
    response_tensors = ppo_trainer.generate(
        query_tensors,
        return_prompt=False,
        **generation_kwargs,
    )
    batch["response"] = tokenizer.batch_decode(response_tensors)

    # Compute the reward scores.
    texts = [q + r for q, r in zip(batch["query"], batch["response"])]
    with torch.no_grad():
        rmodel_inputs = rmodel_tokenizer(texts, padding=True, truncation=True, return_tensors="pt")
        rewards = [r.squeeze().to(dtype=torch.float) for r in rmodel(**rmodel_inputs)]

    # Run PPO step.
    stats = ppo_trainer.step(query_tensors, response_tensors, rewards)
    ppo_trainer.log_stats(stats, batch, rewards)

The offline inference code is essentially the few lines of code given in the doc.

I would lean towards considering it more likely to be an issue within my code rather than the PPOTrainer library. But, any guidance on how to approach debugging this would be highly appreciated!

Also, on a somewhat related note, I'm curious about the correct way to save checkpoints and resume training with PPOTrainer. I've noticed that the API differs somewhat from SFTTrainer, which seems to rely on the transformers' Trainer for checkpointing in a more conventional manner.

Thanks!

kykim0 avatar Jan 26 '24 14:01 kykim0

I did a fair amount of debugging today and wanted to post a potentially interesting update.

Just to be absolutely sure that the issue is not with fine-tuning, I simply loaded a pre-trained, initialized a PPOTrainer instance, and without any training, saved the model using PPOTrainer.save_pretrained(). Upon loading the saved model for offline inference, it produced (not surprisingly) similar results as the original pre-trained model directly loaded for inference.

However, something strange happens when I create a PPOTrainer instance, make just one call to PPOTrainer.generate() method, and subsequently save the model using PPOTrainer.save_pretrained(). Loading this saved model for offline inference produces gibberish, even though I only invoked PPOTrainer.generate() without a corresponding call to PPOTrainer.step(), which, to my understanding, is responsible for parameter updates. This behavior seems very strange, and it raises the question of whether the generate() method is doing something internally to the underlying model that causes this issue.

Code like below could be used to reproduce the results

# Loading and saving, optionally with one call to generate() in between.
config = PPOConfig(model_name="meta-llama/Llama-2-7b-hf", learning_rate=1.41e-5)

dataset = build_dataset(config)

def collator(data):
    return dict((key, [d[key] for d in data]) for key in data[0])

model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name, load_in_8bit=True).to(device)
tokenizer = AutoTokenizer.from_pretrained(config.model_name)
ppo_trainer = PPOTrainer(config, model, ref_model=None, tokenizer=tokenizer, dataset=dataset, data_collator=collator)
if generate:  # If true, offline inference produces gibberish.
    prompt = "Hello, my llama is cute"
    query_tensors = torch.tensor(tokenizer.encode(prompt)).to(device)
    response_tensors = ppo_trainer.generate(query_tensors, max_new_tokens=64)
    response = tokenizer.batch_decode(response_tensors)
ppo_trainer.save_pretrained("model_outdir")

# Offline inference
generator = pipeline("text-generation", model="model_outdir")
outputs = generator(prompt, max_length=64)  # Gibberish if generate was called above.

I plan to look into the generate() method to go deeper, but if someone more familiar with the code could provide guidance, that'd be much appreciated. Thanks!

kykim0 avatar Jan 27 '24 13:01 kykim0

Could you compare the config of the two saved models? Since you are not running any optimization the only difference could be in the config files. For batched generation we do switch the padding side IIRC so if we don't unset it properly that could be an issue for example.

lvwerra avatar Jan 27 '24 14:01 lvwerra

Thank you for the suggestion. I just looked at the output files more closely and diffed all pairs of files, i.e., config.json, model.safetensors.index.json, special_tokens_map.json, tokenizer.json, generation_config.json, tokenizer_config.json, tokenizer.model, and found no diff. I'm not sure if the diff command works for binary files, but the safetensors files were in fact found to be different. So, it seems the generate() is modifying the underlying model somehow.

kykim0 avatar Jan 27 '24 14:01 kykim0

This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

github-actions[bot] avatar Feb 25 '24 15:02 github-actions[bot]

Hi, I'm experiencing the exact same issue, did you find any solutions?

Yunorga avatar Mar 25 '24 09:03 Yunorga

Unfortunately, no.. I ended up doing inference every few steps during training so that I don't need to save / load models post training. One thing I noticed was that PPOTrainer doesn't seem to inherit from transformers.Trainer when other trainers do, so the model saving logic could be slightly different somehow. Not sure why the design choice.

It could be due to a subtle bug in how I was loading model and doing offline inference, or a bug that's potentially fixed in later versions of the library -- I was using 0.7.8 back then.

kykim0 avatar Mar 25 '24 15:03 kykim0