Skip to content
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

Inference pipeline #555

Open
wants to merge 32 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
f04446d
Implementing support for dense rewards
Dahoas Jun 5, 2023
13a01fc
added "num_return_sequences" param which corresponds to n in Best-of-…
SharathRaparthy Jun 16, 2023
5421a73
updates to "num_return_sequences" param
SharathRaparthy Jun 16, 2023
2f3ac28
BoN implementation
SharathRaparthy Jun 16, 2023
2f1dace
Changed back to default.
SharathRaparthy Jun 19, 2023
f58170d
TopK sampling instead of Top1
SharathRaparthy Jun 19, 2023
be8bc1a
summed along dim=1
SharathRaparthy Jun 26, 2023
608d812
Generating samples in chunks
SharathRaparthy Jun 26, 2023
d8557e7
added gen_chunk_size parameter
SharathRaparthy Jun 26, 2023
8ef9c36
chunking in forward prop
SharathRaparthy Jun 26, 2023
4c1d82d
chunking generations in train and eval
SharathRaparthy Jun 26, 2023
ecd5107
Implementing support for dense rewards
Dahoas Jun 5, 2023
4071604
Fix distributed ref_mean, ref_var bug for dense rewards
Dahoas Jun 15, 2023
5f41413
Make generation respect max seq length
Dahoas Jun 23, 2023
22ae83f
Make experience before first round of training
Dahoas Jun 23, 2023
7d0a4be
Refactoring .generate/.generate_eval
Dahoas Jun 27, 2023
b79dd19
Fix BoN metric support
Dahoas Jun 29, 2023
cb49dc5
Enforce chunk_size param for eval generation when present
Dahoas Jul 3, 2023
e290412
Fix: Don't shuffle prompt dataset
Dahoas Jul 4, 2023
391d04c
Move inputs to device
Dahoas Jul 18, 2023
8de84e4
Fix style
Dahoas Jul 18, 2023
404ef14
Fix: Do not shuffle empty experience dataloader
Dahoas Jun 23, 2023
67b711a
Make experience before first round of training
Dahoas Jun 23, 2023
34e185a
Refactoring .generate/.generate_eval
Dahoas Jun 27, 2023
11e1e95
Refactored decode, make_experience and added support for external ref…
Dahoas Jul 14, 2023
527ba23
Fix BoN sampling after big refactor
Dahoas Jul 17, 2023
676a1cd
Fixing style
Dahoas Jul 18, 2023
e43f7b1
Fix: attention_mask indexing error
Dahoas Jul 24, 2023
1018748
Feature: Support pipelined rollouts
Dahoas Jul 25, 2023
3ec27ac
Fix: Add mask arg to advantage whitening
Dahoas Aug 7, 2023
f9bcf15
Feature: Implemented support for training on pipelined inference
Dahoas Aug 7, 2023
0832b0e
Fix style/refactor .generate
Dahoas Sep 4, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions examples/ppo_redemption.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List

import torch
from datasets import load_dataset
from transformers import pipeline

import trlx
from trlx.data.default_configs import TRLConfig, default_ppo_config


def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's output"
return dict(map(lambda x: tuple(x.values()), scores))["POSITIVE"]


def get_negative_score(scores):
return dict(map(lambda x: tuple(x.values()), scores))["NEGATIVE"]


def main(hparams={}):
# Merge sweep config with default config if given
config = TRLConfig.update(default_ppo_config().to_dict(), hparams)
config.method.cliprange_reward = False
config.method.gen_kwargs["max_new_tokens"] = 70
config.method.gen_kwargs["temperature"] = 0.3
config.train.total_steps = 20000
config.train.checkpoint_interval = 10000000
# config.method.init_kl_coef = 0

if torch.cuda.is_available():
device = int(os.environ.get("LOCAL_RANK", 0))
else:
device = -1

sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra/distilbert-imdb",
top_k=2,
truncation=True,
batch_size=256,
device=device,
)

def dense_reward_fn(samples: List[str], prompts: List[str], outputs: List[str], model_tok, **kwargs) -> List[float]:
# Reward positively for initially negative then positive review
# Reward functions should never receive padded text except for a singel EOS at the end
# Reward function should return token rewards for just the response
first_halves = [".".join(sample.split(".")[: len(sample.split(".")) // 2]) for sample in samples]
negative_first_halves = list(map(get_negative_score, sentiment_fn(first_halves)))
second_halves = [".".join(sample.split(".")[len(sample.split(".")) // 2 :]) for sample in samples]
positive_second_halves = list(map(get_positive_score, sentiment_fn(second_halves)))
text_scores = [[f, s] for f, s in zip(negative_first_halves, positive_second_halves)]
tok_scores = []
for sample, prompt, response, text_score in zip(samples, prompts, outputs, text_scores):
toks = model_tok(response).input_ids
tok_score = [0] * len(toks)
# Hacky way of assigning intermediate score
tok_score[len(tok_score) // 2] = text_score[0]
tok_score[-1] = text_score[1]
tok_scores.append(tok_score)
return tok_scores

# Take few words off of movies reviews as prompts
imdb = load_dataset("imdb", split="train+test")
prompts = [" ".join(review.split()[:4]) for review in imdb["text"]]

trlx.train(
reward_fn=dense_reward_fn,
prompts=prompts,
eval_prompts=["I don't know much about Hungarian underground"] * 256,
config=config,
)


if __name__ == "__main__":
hparams = {} if len(sys.argv) == 1 else json.loads(sys.argv[1])
main(hparams)
2 changes: 2 additions & 0 deletions trlx/data/default_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,13 @@ def default_ppo_config():
ref_mean=None,
ref_std=None,
cliprange_reward=10,
num_train_sequences=1,
gen_kwargs=dict(
max_new_tokens=40,
top_k=0,
top_p=1.0,
do_sample=True,
num_return_sequences=1,
),
),
)
Expand Down
5 changes: 5 additions & 0 deletions trlx/data/ppo_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class PPORLElement:
logprobs: TensorType["response_size"]
values: TensorType["response_size"]
rewards: TensorType["response_size"]
loss_mask: TensorType["response_size"]


@dataclass
Expand All @@ -54,10 +55,14 @@ class PPORLBatch:

:param rewards: A batch of rewards
:type rewards: torch.Tensor

:param loss_masks: A mask for tokens during the loss computation
:type loss_masks: torch.Tensor
"""

query_tensors: TensorType["batch_size", "query_size"]
response_tensors: TensorType["batch_size", "response_size"]
logprobs: TensorType["batch_size", "response_size"]
values: TensorType["batch_size", "response_size"]
rewards: TensorType["batch_size", "response_size"]
loss_masks: TensorType["batch_size", "response_size"]
8 changes: 7 additions & 1 deletion trlx/models/modeling_ppo.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ class PPOConfig(MethodConfig):

:param gen_experience_kwargs: if this is not None, then the experience is generated using this
:type gen_experience_kwargs: Dict[str, Any]

:param num_train_sequences: top_k of n sampled sequences from prompt
:type num_train_sequences: int
"""

ppo_epochs: int
Expand All @@ -131,12 +134,15 @@ class PPOConfig(MethodConfig):
cliprange_reward: float
gen_kwargs: dict
gen_experience_kwargs: Optional[dict] = None
num_train_sequences: int = 1
dist_ref_model: bool = False

def get_advantages_and_returns(
self,
values: TensorType["batch_size", "response_size"],
rewards: TensorType["batch_size", "response_size"],
response_length: int,
mask: TensorType["batch_size", "response_size"],
use_whitening: Optional[bool] = True,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function that computes advantages and returns from rewards and values.
Expand Down Expand Up @@ -168,7 +174,7 @@ def get_advantages_and_returns(
advantages = torch.stack(advantages_reversed[::-1], dim=1)
returns = advantages + values
if use_whitening:
advantages = whiten(advantages)
advantages = whiten(advantages, mask)
return advantages.detach(), returns

def loss(
Expand Down
1 change: 1 addition & 0 deletions trlx/pipeline/ppo_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ def ppo_collate_fn(padding_side: str, pad_token_id: int, elems: Iterable[PPORLEl
padding_value=0.0,
batch_first=True,
),
pad_sequence([elem.loss_mask for elem in elems], batch_first=True, padding_value=0.0),
)


Expand Down
1 change: 1 addition & 0 deletions trlx/trainer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def __init__(
logit_mask=None,
stop_sequences=None,
train_mode=False,
inference_pipeline=None,
):
self.store: BaseRolloutStore = None
self.config = config
Expand Down
Loading