Package: trl
TRL - Transformer Reinforcement LearningFull stack transformer language models with reinforcement learning.What is it?trlis a full stack library where we provide a set of tools to train transformer language models and stable diffusion models with Reinforcement Learning, from the Supervised Fine-tuning step (SFT), Reward Modeling step (RM) to the Proximal Policy Optimization (PPO) step. The library is built on top of thetransformerslibrary by  🤗 Hugging Face. Therefore, pre-trained language models can be directly loaded viatransformers. At this point, most of decoder architectures and encoder-decoder architectures are supported. Refer to the documentation or theexamples/folder for example code snippets and how to run these tools.Highlights:SFTTrainer: A light and friendly wrapper aroundtransformersTrainer to easily fine-tune language models or adapters on a custom dataset.RewardTrainer: A light wrapper aroundtransformersTrainer to easily fine-tune language models for human preferences (Reward Modeling).PPOTrainer: A PPO trainer for language models that just needs (query, response, reward) triplets to optimise the language model.AutoModelForCausalLMWithValueHead&AutoModelForSeq2SeqLMWithValueHead: A transformer model with an additional scalar output for each token which can be used as a value function in reinforcement learning.Examples: Train GPT2 to generate positive movie reviews with a BERT sentiment classifier, full RLHF using adapters only, train GPT-j to be less toxic,Stack-Llama example, etc.How PPO worksFine-tuning a language model via PPO consists of roughly three steps:Rollout: The language model generates a response or continuation based on query which could be the start of a sentence.Evaluation: The query and response are evaluated with a function, model, human feedback or some combination of them. The important thing is that this process should yield a scalar value for each query/response pair.Optimization: This is the most complex part. In the optimisation step the query/response pairs are used to calculate the log-probabilities of the tokens in the sequences. This is done with the model that is trained and a reference model, which is usually the pre-trained model before fine-tuning. The KL-divergence between the two outputs is used as an additional reward signal to make sure the generated responses don't deviate too far from the reference language model. The active language model is then trained with PPO.This process is illustrated in the sketch below:Figure:Sketch of the workflow.InstallationPython packageInstall the library with pip:pipinstalltrlFrom sourceIf you want to run the examples in the repository a few additional libraries are required. Clone the repository and install it with pip:gitclonehttps://github.com/huggingface/trl.gitcdtrl/
pipinstall.If you wish to develop TRL, you should install in editable mode:pipinstall-e.How to useSFTTrainerThis is a basic example on how to use theSFTTrainerfrom the library. TheSFTTraineris a light wrapper around thetransformersTrainer to easily fine-tune language models or adapters on a custom dataset.# importsfromdatasetsimportload_datasetfromtrlimportSFTTrainer# get datasetdataset=load_dataset("imdb",split="train")# get trainertrainer=SFTTrainer("facebook/opt-350m",train_dataset=dataset,dataset_text_field="text",max_seq_length=512,)# traintrainer.train()RewardTrainerThis is a basic example on how to use theRewardTrainerfrom the library. TheRewardTraineris a wrapper around thetransformersTrainer to easily fine-tune reward models or adapters on a custom preference dataset.# importsfromtransformersimportAutoModelForSequenceClassification,AutoTokenizerfromtrlimportRewardTrainer# load model and dataset - dataset needs to be in a specific formatmodel=AutoModelForSequenceClassification.from_pretrained("gpt2",num_labels=1)tokenizer=AutoTokenizer.from_pretrained("gpt2")...# load trainertrainer=RewardTrainer(model=model,tokenizer=tokenizer,train_dataset=dataset,)# traintrainer.train()PPOTrainerThis is a basic example on how to use thePPOTrainerfrom the library. Based on a query the language model creates a response which is then evaluated. The evaluation could be a human in the loop or another model's output.# importsimporttorchfromtransformersimportAutoTokenizerfromtrlimportPPOTrainer,PPOConfig,AutoModelForCausalLMWithValueHead,create_reference_modelfromtrl.coreimportrespond_to_batch# get modelsmodel=AutoModelForCausalLMWithValueHead.from_pretrained('gpt2')model_ref=create_reference_model(model)tokenizer=AutoTokenizer.from_pretrained('gpt2')# initialize trainerppo_config=PPOConfig(batch_size=1,)# encode a queryquery_txt="This morning I went to the "query_tensor=tokenizer.encode(query_txt,return_tensors="pt")# get model responseresponse_tensor=respond_to_batch(model,query_tensor)# create a ppo trainerppo_trainer=PPOTrainer(ppo_config,model,model_ref,tokenizer)# define a reward for response# (this could be any reward such as human feedback or output from another model)reward=[torch.tensor(1.0)]# train model for one step with ppotrain_stats=ppo_trainer.step([query_tensor[0]],[response_tensor[0]],reward)ReferencesProximal Policy OptimisationThe PPO implementation largely follows the structure introduced in the paper"Fine-Tuning Language Models from Human Preferences"by D. Ziegler et al. [paper,code].Language modelsThe language models utilize thetransformerslibrary by 🤗 Hugging Face.  Currently,trlonly supportstransformersmodelsfor text.Citation@misc{vonwerra2022trl,author={Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang},title={TRL: Transformer Reinforcement Learning},year={2020},publisher={GitHub},journal={GitHub repository},howpublished={\url{https://github.com/huggingface/trl}}}