{"id":13498774,"url":"https://github.com/voidful/TextRL","last_synced_at":"2025-03-29T01:32:34.851Z","repository":{"id":37425765,"uuid":"349008051","full_name":"voidful/TextRL","owner":"voidful","description":"Implementation of ChatGPT RLHF (Reinforcement Learning with Human Feedback) on any generation model in huggingface's transformer (blommz-176B/bloom/gpt/bart/T5/MetaICL)","archived":false,"fork":false,"pushed_at":"2024-05-09T17:37:44.000Z","size":410,"stargazers_count":555,"open_issues_count":4,"forks_count":59,"subscribers_count":10,"default_branch":"main","last_synced_at":"2025-03-26T09:07:35.634Z","etag":null,"topics":["chatgpt","controlled-nlg","gpt-2","gpt-3","language-model","nlg","nlp","pytorch","reinforcement-learning","rlhf"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/voidful.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-18T09:11:36.000Z","updated_at":"2025-03-18T13:30:13.000Z","dependencies_parsed_at":"2023-11-21T17:01:16.990Z","dependency_job_id":"50fe662c-393f-4e65-a146-0fc848574b0e","html_url":"https://github.com/voidful/TextRL","commit_stats":{"total_commits":66,"total_committers":2,"mean_commits":33.0,"dds":"0.015151515151515138","last_synced_commit":"5c9882467b8c0200be23e17ae2f01e5b4a204236"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/voidful%2FTextRL","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/voidful%2FTextRL/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/voidful%2FTextRL/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/voidful%2FTextRL/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/voidful","download_url":"https://codeload.github.com/voidful/TextRL/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245623078,"owners_count":20645680,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chatgpt","controlled-nlg","gpt-2","gpt-3","language-model","nlg","nlp","pytorch","reinforcement-learning","rlhf"],"created_at":"2024-07-31T21:00:43.410Z","updated_at":"2025-03-29T01:32:34.538Z","avatar_url":"https://github.com/voidful.png","language":"Python","funding_links":[],"categories":["Developer Libraries, SDKs, and APIs","Python","Codebases","Awesome RHLF","SDK, Libraries, Frameworks"],"sub_categories":["Python","2020 and before","Tools and Resources","Python library, sdk or frameworks"],"readme":"# TextRL: Text Generation with Reinforcement Learning\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://pypi.org/project/textrl/\"\u003e\n        \u003cimg alt=\"PyPI\" src=\"https://img.shields.io/pypi/v/textrl\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/voidful/tfkit\"\u003e\n        \u003cimg alt=\"Download\" src=\"https://img.shields.io/pypi/dm/textrl\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/voidful/tfkit\"\u003e\n        \u003cimg alt=\"Last Commit\" src=\"https://img.shields.io/github/last-commit/voidful/textrl\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://www.codefactor.io/repository/github/voidful/textrl\"\u003e\n        \u003cimg src=\"https://www.codefactor.io/repository/github/voidful/textrl/badge\" alt=\"CodeFactor\" /\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/voidful/textrl\"\u003e\n        \u003cimg src=\"https://visitor-badge.glitch.me/badge?page_id=voidful.textrl\" alt=\"Visitor\" /\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\nTextRL is a Python library that aims to improve text generation using reinforcement learning, building upon Hugging Face's Transformers, PFRL, and OpenAI GYM. TextRL is designed to be easily customizable and can be applied to various text-generation models.\n\n![TextRL](https://github.com/voidful/TextRL/raw/main/img/Designer.png)\n\n## Table of Contents\n\n- [Introduction](#introduction)\n- [Examples](#examples)\n  - [GPT-2 Example](#gpt-2-example)\n  - [FLAN-T5 Example](#flan-t5-example)\n  - [Bigscience/BLOOMZ-7B1-MT Example](#bigsciencebloomz-7b1-mt-example)\n  - [176B BLOOM Example](#176b-bloom-example)\n  - [Controllable Generation via RL Example](#controllable-generation-via-rl-example)\n- [Installation](#installation)\n  - [Pip Install](#pip-install)\n  - [Build from Source](#build-from-source)\n- [Usage](#usage)\n  - [Initialize Agent and Environment](#initialize-agent-and-environment)\n  - [Setup Reward Function for Environment](#setup-reward-function-for-environment)\n  - [Prepare for Training](#prepare-for-training)\n  - [Training](#training)\n- [Dump Model](#dump-trained-model-to-huggingfaces-model)\n- [Key Parameters for RL Training](#key-parameters-for-rl-training)\n\n## Introduction\n\nTextRL utilizes reinforcement learning to fine-tune text generation models. It is built upon the following libraries:\n\n- [Hugging Face's Transformers](https://github.com/huggingface/transformers)\n- [PFRL](https://github.com/pfnet/pfrl)\n- [OpenAI GYM](https://gym.openai.com)\n\n\n\n## Example - `gpt2`\n\n\u003cdetails\u003e\u003csummary\u003eCLICK ME\u003c/summary\u003e\n\u003cp\u003e\n\n#### GPT2 Example\n\n```python\nimport pfrl\nfrom textrl import TextRLEnv, TextRLActor, train_agent_with_evaluation\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport logging\nimport sys\n\nlogging.basicConfig(level=logging.INFO, stream=sys.stdout, format='')\n\ncheckpoint = \"gpt2\"\n\ntokenizer = AutoTokenizer.from_pretrained(checkpoint)\nmodel = AutoModelForCausalLM.from_pretrained(checkpoint, torch_dtype=\"auto\", device_map=\"auto\")\n\nmodel = model.cuda()\n\n\nclass MyRLEnv(TextRLEnv):\n    def get_reward(self, input_item, predicted_list, finish):  # predicted will be the list of predicted token\n        reward = [0]\n        if finish:\n            reward = [1]  # calculate reward score base on predicted_list\n        return reward\n\n\nobservaton_list = [{\"input\":\"explain how attention work in seq2seq model\"}]\nenv = TextRLEnv(model, tokenizer, observation_input=observaton_list, max_length=20, compare_sample=2)\nactor = TextRLActor(env, model, tokenizer,\n                    act_deterministically=False,\n                    temperature=1.0,\n                    top_k=0,\n                    top_p=1.0,\n                    repetition_penalty=2)\nagent = actor.agent_ppo(update_interval=2, minibatch_size=2, epochs=10)\nprint(actor.predict(observaton_list[0]))\n\ntrain_agent_with_evaluation(\n    agent,\n    env,\n    steps=100,\n    eval_n_steps=None,\n    eval_n_episodes=1,\n    eval_interval=2,\n    outdir='bloom—test',\n)\n\nprint(actor.predict(observaton_list[0]))\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n## Example - `flan-t5`\n\n\n\u003cdetails\u003e\u003csummary\u003eCLICK ME\u003c/summary\u003e\n\u003cp\u003e\n\n#### Example Code\n\ncolab\nexample: [google/flan-t5-base](https://colab.research.google.com/drive/1DYHt0mi6cyl8ZTMJEkMNpsSZCCvR4jM1?usp=sharing)\n\n```python\nimport pfrl\nfrom textrl import TextRLEnv, TextRLActor, train_agent_with_evaluation\nfrom transformers import AutoModelForSeq2SeqLM, AutoTokenizer\nimport logging\nimport sys\n\nlogging.basicConfig(level=logging.INFO, stream=sys.stdout, format='')\n\n\ntokenizer = AutoTokenizer.from_pretrained(\"google/flan-t5-base\")  \nmodel = AutoModelForSeq2SeqLM.from_pretrained(\"google/flan-t5-base\")\nmodel.eval()\nmodel.cuda()\n\nsentiment = pipeline('sentiment-analysis',model=\"cardiffnlp/twitter-roberta-base-sentiment\",tokenizer=\"cardiffnlp/twitter-roberta-base-sentiment\",device=0,return_all_scores=True)\n\nclass MyRLEnv(TextRLEnv):\n    def get_reward(self, input_item, predicted_list, finish): # predicted will be the list of predicted token\n      reward = 0\n      if finish or len(predicted_list[0]) \u003e= self.env_max_length:\n        predicted_text = tokenizer.convert_tokens_to_string(predicted_list[0])\n        # sentiment classifier\n        reward = sentiment(input_item['input']+predicted_text)[0][0]['score'] * 10\n      return reward\n\nobservaton_list = [{'input':'i think dogecoin is'}]\nenv = MyRLEnv(model, tokenizer, observation_input=observaton_list, compare_sample=1)\nactor = TextRLActor(env,model,tokenizer,optimizer='adamw',\n                    temperature=0.8,\n                    top_k=100,\n                    top_p=0.85,)\nagent = actor.agent_ppo(update_interval=50, minibatch_size=3, epochs=10,lr=3e-4)\nprint(actor.predict(observaton_list[0]))\n\npfrl.experiments.train_agent_with_evaluation(\n    agent,\n    env,\n    steps=3000,\n    eval_n_steps=None,\n    eval_n_episodes=1,       \n    train_max_episode_len=100,  \n    eval_interval=10,\n    outdir='checkpoint', \n)\nagent.load(\"./checkpoint/best\")\nprint(actor.predict(observaton_list[0]))\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n\n## Example - `bigscience/bloomz-7b1-mt`\n\n\u003cdetails\u003e\u003csummary\u003eCLICK ME\u003c/summary\u003e\n\u003cp\u003e\n\n#### bloomz-7b1-mt Example\n\n```python\nimport pfrl\nfrom textrl import TextRLEnv, TextRLActor, train_agent_with_evaluation\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport logging\nimport sys\n\nlogging.basicConfig(level=logging.INFO, stream=sys.stdout, format='')\n\ncheckpoint = \"bigscience/bloomz-7b1-mt\"\n\ntokenizer = AutoTokenizer.from_pretrained(checkpoint)\nmodel = AutoModelForCausalLM.from_pretrained(checkpoint, torch_dtype=\"auto\", device_map=\"auto\")\n\nmodel = model.cuda()\n\n\nclass MyRLEnv(TextRLEnv):\n    def get_reward(self, input_item, predicted_list, finish):  # predicted will be the list of predicted token\n        reward = [0]\n        if finish:\n            reward = [1]  # calculate reward score base on predicted_list\n        return reward\n\n\nobservaton_list = [{\"input\":\"explain how attention work in seq2seq model\"}]\nenv = TextRLEnv(model, tokenizer, observation_input=observaton_list, max_length=20, compare_sample=2)\nactor = TextRLActor(env, model, tokenizer,\n                    act_deterministically=False,\n                    temperature=1.0,\n                    top_k=0,\n                    top_p=1.0)\nagent = actor.agent_ppo(update_interval=2, minibatch_size=2, epochs=10)\nprint(actor.predict(observaton_list[0]))\n\ntrain_agent_with_evaluation(\n    agent,\n    env,\n    steps=100,\n    eval_n_steps=None,\n    eval_n_episodes=1,\n    eval_interval=2,\n    outdir='bloom—test',\n)\n\nprint(actor.predict(observaton_list[0]))\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n## Example - 176B BLOOM\n\n\u003cdetails\u003e\u003csummary\u003eCLICK ME\u003c/summary\u003e\n\u003cp\u003e\n\n#### bloomz-176B Example\n\nStrongly recommend contribute on public swarm to increase petals capacity\n\nhttps://github.com/bigscience-workshop/petals\n\ninstall `pip install petals -U` first\n\n\n```python\nimport pfrl\nfrom textrl import TextRLEnv, TextRLActor, train_agent_with_evaluation\nfrom transformers import BloomTokenizerFast\nfrom petals import DistributedBloomForCausalLM\nimport logging\nimport sys\n\nlogging.basicConfig(level=logging.INFO, stream=sys.stdout, format='')\n\nMODEL_NAME = \"bigscience/bloom-petals\"\ntokenizer = BloomTokenizerFast.from_pretrained(MODEL_NAME)\nmodel = DistributedBloomForCausalLM.from_pretrained(MODEL_NAME)\nmodel = model.cuda()\n\n\nclass MyRLEnv(TextRLEnv):\n    def get_reward(self, input_item, predicted_list, finish):  # predicted will be the list of predicted token\n        reward = [0]\n        if finish:\n            reward = [1]  # calculate reward score base on predicted_list\n        return reward\n\n\nobservaton_list = [{\"input\":\"explain how attention work in seq2seq model\"}]\nenv = TextRLEnv(model, tokenizer, observation_input=observaton_list, max_length=20, compare_sample=2)\nactor = TextRLActor(env, model, tokenizer,\n                    act_deterministically=False,\n                    temperature=1.0,\n                    top_k=0,\n                    top_p=1.0)\nagent = actor.agent_ppo(update_interval=2, minibatch_size=2, epochs=10)\n\nprint(actor.predict(observaton_list[0]))\n\ntrain_agent_with_evaluation(\n    agent,\n    env,\n    steps=100,\n    eval_n_steps=None,\n    eval_n_episodes=1,\n    eval_interval=2,\n    outdir='bloom—test',\n)\n\nprint(actor.predict(observaton_list[0]))\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n## Example - Controllable generation via RL to let Elon Musk speak ill of DOGE\n\n\u003cdetails\u003e\u003csummary\u003eCLICK ME\u003c/summary\u003e\n\u003cp\u003e\n[Controllable generation via RL to let Elon Musk speak ill of DOGE\n](https://github.com/voidful/TextRL/blob/main/example/2022-12-10-textrl-elon-musk.ipynb)\n\ncolab\nexample: [bigscience/bloom-560m](https://colab.research.google.com/drive/1ThSHtkfzC2dDc6JOdeCTthuDovTCheRf?usp=sharing)\n\ncolab\nexmaple: [huggingtweets/elonmusk](https://colab.research.google.com/drive/149MG6uxu7CjMU1pXnYXfSvJ6HEdwcOFt?usp=sharing)\n\nbefore: `i think dogecoin is a great idea.`    \nafter: `i think dogecoin is a great idea, but I think it is a little overused.`\n\u003c/p\u003e\n\u003c/details\u003e\n\n## Installation\n\n### pip install\n\n```bash\npip install pfrl@git+https://github.com/voidful/pfrl.git\npip install textrl\n```\n\n### Build from source\n\ngit clone and cd into this project.\n\n```bash\npip install -e .\n```\n\n## Usage\n\n### Initialize agent and environment\n\n```python\nimport torch\nfrom textrl import TextRLEnv, TextRLActor, train_agent_with_evaluation\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\ncheckpoint = \"bigscience/bloomz-7b1-mt\"\n\ntokenizer = AutoTokenizer.from_pretrained(checkpoint)\nmodel = AutoModelForCausalLM.from_pretrained(checkpoint, torch_dtype=\"auto\", device_map=\"auto\")\n\nmodel = model.cuda()\n```\n\n### Set up reward function for environment\n\n- predicted(list\\[str]): will be the list of predicted tokens\n- finish(bool): whether the end of sentence has been reached or not\n\n```python\nclass MyRLEnv(TextRLEnv):\n    def get_reward(self, input_item, predicted_list, finish):\n        if finish:\n            reward = [0]  # calculate reward score based on predicted_list\n        return reward\n```\n\n### Prepare for training\n\n- observation\\_list should be a list of all possible input strings for model training\n\n  Example: `observation_list = [{\"input\":'testing sent 1'},{\"input\":'testing sent 2'}]`\n\n```python\nenv = MyRLEnv(model, tokenizer, observation_input=observation_list)\nactor = TextRLActor(env, model, tokenizer)\nagent = actor.agent_ppo(update_interval=10, minibatch_size=2000, epochs=20)\n```\n\n### Train\n\n```python\nn_episodes = 1000\nmax_episode_len = 200  # max sentence length\n\nfor i in range(1, n_episodes + 1):\n    obs = env.reset()\n    R = 0\n    t = 0\n    while True:\n        action = agent.act(obs)\n        obs, reward, done, pred = env.step(action)\n        R += reward\n        t += 1\n        reset = t == max_episode_len\n        agent.observe(obs, reward, done, reset)\n        if done or reset:\n            break\n    if i % 10 == 0:\n        print('episode:', i, 'R:', R)\n    if i % 50 == 0:\n        print('statistics:', agent.get_statistics())\nprint('Finished.')\n```\n\nAnother way to train:\n\n```python\nimport logging\nimport sys\n\nlogging.basicConfig(level=logging.INFO, stream=sys.stdout, format='')\n\ntrain_agent_with_evaluation(\n    agent,\n    env,\n    steps=1000,\n    eval_n_steps=None,\n    eval_n_episodes=1500,\n    train_max_episode_len=50,\n    eval_interval=10000,\n    outdir='somewhere',\n)\n```\n\n### Prediction\n\n```python\nagent.load(\"somewhere/best\")  # loading the best model\nactor.predict(\"input text\")\n```\n\nThis updated usage section provides a comprehensive guide on how to initialize the agent and environment, set up the reward function for the environment, prepare for training, train the model, and make predictions. It also includes an alternative way to train the model using the `train_agent_with_evaluation` function.\n\n## Dump trained model to huggingface's model\n\n```shell\ntextrl-dump --model ./model_path_before_rl --rl ./rl_path --dump ./output_dir\n```\n\n## Key Parameters for RL Training\n\nTo finetune a language model using RL, you need to modify the reward function:\n\n```python\nfrom textrl import TextRLEnv\n\nclass MyRLEnv(TextRLEnv):\n    def get_reward(self, input_item, predicted_list, finish):\n        # input_item is the prompt input for the model, it will be one of your observation\n        # an observation will be a list of sentence of eg: ['inputted sentence','xxx','yyy']\n        # only the first input will feed to the model 'inputted sentence', and \n        # the remaining can be the reference for reward calculation\n\n        # predicted_list is the list of predicted sentences of RL model generated,\n        # it will be used for ranking reward calculation\n\n        # finish is the end of sentences flags, get_reward will be called during generating each word, and \n        # when finish is True, it means the sentence is finished, it will use for sentence level reward calculation.\n\n        # reward should be the list equal to the length of predicted_list\n        return reward\n```\n\nParameters for sampling diverse examples:\n\n```python\nactor = TextRLActor(env, model, tokenizer,\n                    act_deterministically=False,  # select the max probability token for each step or not\n                    temperature=1,                # temperature for sampling\n                    compare_sample=2,             # num of sample to rank\n                    top_k=0,                      # top k sampling\n                    top_p=1.0,)                    # top p sampling\n```\n\nWhen training a reinforcement learning (RL) model, several key parameters need to be tuned to ensure optimal performance. Here is a list of important parameters and their descriptions:\n\n1. **Update Interval**: This determines how often the RL agent updates its policy based on collected experiences. A smaller update interval means the agent learns more frequently from recent experiences, while a larger interval allows more experiences to accumulate before learning. In the example above, the update interval is set to 10.\n\n```python\nupdate_interval=10\n```\n\n2. **Minibatch Size**: The number of experiences sampled from the experience replay buffer to compute the gradient update. A larger minibatch size helps to stabilize learning and reduce variance, but at the cost of increased computational requirements.\n\n```python\nminibatch_size=2000\n```\n\n3. **Epochs**: The number of times the agent iterates through the entire minibatch to update its policy. More epochs can lead to better learning but may increase the risk of overfitting.\n\n```python\nepochs=20\n```\n\n4. **Discount Factor (Gamma)**: This parameter determines how much future rewards are discounted when calculating the expected return. A value closer to 1 makes the agent more farsighted, while a value closer to 0 makes the agent more focused on immediate rewards.\n\n```python\ngamma=0.99\n```\n\n5. **Learning Rate**: The step size used for updating the policy. A larger learning rate allows for faster convergence but may lead to instability in learning, while a smaller learning rate ensures stable learning at the cost of slower convergence.\n\n```python\nlr=1e-4\n```\n\n6. **Epsilon**: A parameter used in the PPO algorithm to clip the policy ratio. This helps to control the magnitude of policy updates, preventing excessively large updates that can destabilize learning.\n\n```python\nepsilon=0.2\n```\n\n7. **Entropy Coefficient**: This parameter encourages exploration by adding a bonus reward for taking less certain actions. A higher entropy coefficient promotes more exploration, while a lower coefficient focuses the agent on exploiting known strategies.\n\n```python\nentropy_coef=0.01\n```\n\n8. **Training Steps**: The total number of steps the agent takes during training. More steps typically lead to better learning but may require more computational time.\n\n```python\nsteps=1000\n```\n\n9. **Evaluation Interval**: The number of training steps between evaluations. Increasing the evaluation interval reduces the computational time spent on evaluation, but it may also reduce the frequency at which you can monitor the agent's progress.\n\n```python\neval_interval=10000\n```\n\n10. **Max Episode Length**: The maximum number of steps allowed in a single episode during training. This can prevent the agent from getting stuck in long, unproductive episodes.\n\n```python\ntrain_max_episode_len=50\n```\n\nThese parameters need to be carefully tuned based on the specific problem and environment to achieve the best performance. It is generally recommended to start with default values and then adjust them based on the observed learning behavior.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvoidful%2FTextRL","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvoidful%2FTextRL","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvoidful%2FTextRL/lists"}