generated from fastai/nbdev_template
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
custom reward function support for ppo trainer #2540
Draft
August-murr
wants to merge
3
commits into
huggingface:main
Choose a base branch
from
August-murr:PPO_custom_reward_function
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+39
−15
Draft
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,7 +20,7 @@ | |
from collections import deque | ||
from dataclasses import dataclass | ||
from importlib.metadata import version | ||
from typing import Any, Literal, Optional, Union | ||
from typing import Any, Callable, Literal, Optional, Union | ||
|
||
import datasets | ||
import numpy as np | ||
|
@@ -1049,14 +1049,20 @@ def first_true_indices(bools: torch.Tensor, dtype=torch.long): | |
|
||
|
||
def get_reward( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is where the primary change are: |
||
model: torch.nn.Module, query_responses: torch.Tensor, pad_token_id: int, context_length: int | ||
model: Union[torch.nn.Module, Callable], | ||
processor: PreTrainedTokenizerBase, | ||
query_responses: torch.Tensor, | ||
pad_token_id: int, | ||
context_length: int, | ||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: | ||
""" | ||
Computes the reward logits and the rewards for a given model and query responses. | ||
Computes the reward logits and the rewards for a given model/function and query responses. | ||
|
||
Args: | ||
model (`torch.nn.Module`): | ||
The model used to compute the reward logits. | ||
model (`torch.nn.Module` or `Callable`): | ||
The model or a custom function used to compute the reward logits. | ||
processor: | ||
The processor (e.g., tokenizer) to decode the input if needed. | ||
query_responses (`torch.Tensor`): | ||
The tensor containing the query responses. | ||
pad_token_id (`int`): | ||
|
@@ -1073,29 +1079,37 @@ def get_reward( | |
- `sequence_lengths` (`torch.Tensor`): | ||
The lengths of the sequences in the query responses. | ||
""" | ||
attention_mask = query_responses != pad_token_id | ||
position_ids = attention_mask.cumsum(1) - attention_mask.long() # exclusive cumsum | ||
lm_backbone = getattr(model, model.base_model_prefix) | ||
input_ids = torch.masked_fill(query_responses, ~attention_mask, 0) | ||
output = lm_backbone( | ||
input_ids=input_ids, | ||
attention_mask=attention_mask, | ||
position_ids=position_ids, | ||
return_dict=True, | ||
output_hidden_states=True, | ||
use_cache=False, # otherwise mistral-based RM would error out | ||
) | ||
reward_logits = model.score(output.hidden_states[-1]) | ||
sequence_lengths = first_true_indices(query_responses[:, context_length:] == pad_token_id) - 1 + context_length | ||
# https://github.com/huggingface/transformers/blob/dc68a39c8111217683bf49a4912d0c9018bab33d/src/transformers/models/gpt2/modeling_gpt2.py#L1454 | ||
return ( | ||
reward_logits, | ||
reward_logits[ | ||
torch.arange(reward_logits.size(0), device=reward_logits.device), | ||
|
||
if isinstance(model, torch.nn.Module): | ||
attention_mask = query_responses != pad_token_id | ||
position_ids = attention_mask.cumsum(1) - attention_mask.long() # exclusive cumsum | ||
lm_backbone = getattr(model, model.base_model_prefix) | ||
input_ids = torch.masked_fill(query_responses, ~attention_mask, 0) | ||
output = lm_backbone( | ||
input_ids=input_ids, | ||
attention_mask=attention_mask, | ||
position_ids=position_ids, | ||
return_dict=True, | ||
output_hidden_states=True, | ||
use_cache=False, # otherwise mistral-based RM would error out | ||
) | ||
reward_logits = model.score(output.hidden_states[-1]) | ||
sequence_lengths = first_true_indices(query_responses[:, context_length:] == pad_token_id) - 1 + context_length | ||
# https://github.com/huggingface/transformers/blob/dc68a39c8111217683bf49a4912d0c9018bab33d/src/transformers/models/gpt2/modeling_gpt2.py#L1454 | ||
return ( | ||
reward_logits, | ||
reward_logits[ | ||
torch.arange(reward_logits.size(0), device=reward_logits.device), | ||
sequence_lengths, | ||
].squeeze(-1), | ||
sequence_lengths, | ||
].squeeze(-1), | ||
sequence_lengths, | ||
) | ||
) | ||
else: | ||
texts = processor.batch_decode(query_responses) | ||
rewards = model(texts) | ||
rewards = torch.tensor(rewards, dtype=torch.float) | ||
final_rewards, sequence_lengths = None, None | ||
return final_rewards, rewards, sequence_lengths | ||
|
||
|
||
def forward( | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we move the
if isinstance(model, torch.nn.Module):
here? I would allow not to introduce breaking change inget_reward
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You need to clarify what you mean.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sorry, it wasn't clear:
something like this instead:
doing such we don't introduce a breaking change in
get_reward
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I mean I changed get_reward to work either way with both a callable and an nn.Module.
So you want to add
if isinstance(model, torch.nn.Module)
there and keepget_reward
as it is without change?