MCPcopy Index your code
hub / github.com/CarperAI/trlx

github.com/CarperAI/trlx @v0.7.0 sqlite

repository ↗ · DeepWiki ↗ · release v0.7.0 ↗
765 symbols 3,059 edges 81 files 234 documented · 31%
README

DOI

Transformer Reinforcement Learning X

trlX is a distributed training framework designed from the ground up to focus on fine-tuning large language models with reinforcement learning using either a provided reward function or a reward-labeled dataset.

Training support for 🤗 Hugging Face models is provided by Accelerate-backed trainers, allowing users to fine-tune causal and T5-based language models of up to 20B parameters, such as facebook/opt-6.7b, EleutherAI/gpt-neox-20b, and google/flan-t5-xxl. For models beyond 20B parameters, trlX provides NVIDIA NeMo-backed trainers that leverage efficient parallelism techniques to scale effectively.

The following RL algorithms are currently implemented:

Algorithm Accelerate Trainer NeMo Trainer
Proximal Policy Optimization (PPO)
Implicit Language Q-Learning (ILQL)

📖 Documentation

🧀 CHEESE Collect human annotations for your RL application with our human-in-the-loop data collection library.

Installation

git clone https://github.com/CarperAI/trlx.git
cd trlx
pip install torch==2.0.0 --extra-index-url https://download.pytorch.org/whl/cu116 # for cuda
pip install -e .

Examples

For more usage see examples. You can also try the colab notebooks below: | Description | Link | | ----------- | ----------- | | Simulacra (GPT2, ILQL) | Open In Colab| | Sentiment (GPT2, ILQL) | Open In Colab|

Latest runs of the examples are on our Weights & Biases

How to Train

You can train a model using a reward function or a reward-labeled dataset.

Using a reward function

trainer = trlx.train('gpt2', reward_fn=lambda samples, **kwargs: [sample.count('cats') for sample in samples])

Using a reward-labeled dataset

trainer = trlx.train('EleutherAI/gpt-j-6B', samples=['dolphins', 'geese'], rewards=[1.0, 100.0])

Using a prompt-completion dataset

trainer = trlx.train('gpt2', samples=[['Question: 1 + 2 Answer:', '3'], ['Question: Solve this equation: ∀n>0, s=2, sum(n ** -s). Answer:', '(pi ** 2)/ 6']])

Trainers provide a wrapper over their underlying model

trainer.generate(**tokenizer('Q: Who rules the world? A:', return_tensors='pt'), do_sample=True)

Configure Hyperparameters

from trlx.data.default_configs import default_ppo_config, TrainConfig

config = default_ppo_config()
config.model.model_path = 'EleutherAI/gpt-neox-20b'
config.train.seq_length = 32
config.train.batch_size = 16

trainer = trlx.train(config=config, reward_fn=lambda samples, **kwargs: [float(int(sample)) for sample in samples])

Save the resulting model to a Hugging Face pretrained language model. (Ready to upload to the Hub!)

trainer.save_pretrained('/path/to/output/folder/')

Use 🤗 Accelerate to launch distributed training

accelerate config # choose DeepSpeed option
accelerate launch examples/simulacra.py

Use NeMo-Megatron to launch distributed training

Follow the setup instructions in the NeMo README.

python examples/nemo_ilql_sentiments.py

For more usage see the NeMo README

Use Ray Tune to launch hyperparameter sweep

ray start --head --port=6379
python -m trlx.sweep --config configs/sweeps/ppo_sweep.yml --accelerate_config configs/accelerate/ddp.yaml --num_gpus 4 examples/ppo_sentiments.py

Benchmark your trlX fork against trlX's main branch

python -m trlx.reference octocat/trlx-fork:fix-branch

Logging

trlX uses the standard Python logging library to log training information to the console. The default logger is set to the INFO level, which means that INFO, WARNING, ERROR, and CRITICAL level messages will be printed to standard output.

To change the log level directly, you can use the verbosity setter. For example, to set the log level to WARNING use:

import trlx

trlx.logging.set_verbosity(trlx.logging.WARNING)

This will suppress INFO level messages, but still print WARNING, ERROR, and CRITICAL level messages.

You can also control logging verbosity by setting the TRLX_VERBOSITY environment variable to one of the standard logging level names:

  • CRITICAL (trlx.logging.CRITICAL)
  • ERROR (trlx.logging.ERROR)
  • WARNING (trlx.logging.WARNING)
  • INFO (trlx.logging.INFO)
  • DEBUG (trlx.logging.DEBUG)
export TRLX_VERBOSITY=WARNING

By default, tqdm progress bars are used to display training progress. You can disable them by calling trlx.logging.disable_progress_bar(), otherwise trlx.logging.enable_progress_bar() to enable.

Messages can be formatted with greater detail by setting trlx.logging.enable_explicit_format(). This will inject call-site information into each log which may be helpful for debugging.

[2023-01-01 05:00:00,000] [INFO] [ppo_orchestrator.py:63:make_experience] [RANK 0] Message...

💡 Tip: To reduce the amount of logging output, you might find it helpful to change log levels of third-party libraries used by trlX. For example, try adding transformers.logging.set_verbosity_error() to the top of your trlX scripts to silence verbose messages from the transformers library (see their logging docs for more details).

Contributing

For development check out these guidelines and also read our docs

Acknowledgements

Many thanks to Leandro von Werra for contributing with trl, a library that initially inspired this repo.

Core symbols most depended-on inside this repo

from_pretrained
called by 71
trlx/models/modeling_base.py
update
called by 32
trlx/data/configs.py
load
called by 29
trlx/trainer/__init__.py
state_dict
called by 23
trlx/models/modeling_base.py
decode
called by 18
trlx/trainer/accelerate_base_trainer.py
log
called by 17
trlx/utils/logging.py
parameters
called by 17
trlx/models/modeling_nemo_sft.py
_get_library_root_logger
called by 13
trlx/utils/logging.py

Shape

Method 426
Function 230
Class 109

Languages

Python100%

Modules by API surface

trlx/models/modeling_nemo_ppo.py61 symbols
trlx/models/modeling_nemo_ilql.py48 symbols
tests/test_models.py47 symbols
trlx/models/modeling_ppo.py46 symbols
trlx/utils/logging.py35 symbols
examples/experiments/grounded_program_synthesis/lang.py34 symbols
trlx/models/modeling_nemo_sft.py27 symbols
trlx/models/modeling_ilql.py26 symbols
trlx/pipeline/offline_pipeline.py24 symbols
trlx/utils/modeling.py22 symbols
trlx/trainer/accelerate_base_trainer.py21 symbols
tests/test_minibatch.py21 symbols

Dependencies from manifests, versioned

GitPython3.1.31 · 1×
Jinja23.1.2 · 1×
MarkupSafe2.1.2 · 1×
PyYAML6.0 · 1×
Pygments2.15.1 · 1×
accelerate0.18.0 · 1×
aiohttp3.8.4 · 1×
aiosignal1.3.1 · 1×
appdirs1.4.4 · 1×
async-timeout4.0.2 · 1×
attrs23.1.0 · 1×
cattrs22.2.0 · 1×

For agents

$ claude mcp add trlx \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact