From f921d34bf84baf950492f4d291b95d22f311910c Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 5 Feb 2025 05:14:01 -0800 Subject: [PATCH] Create rl.py --- unsloth/models/rl.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 unsloth/models/rl.py diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py new file mode 100644 index 0000000000..efe2d33e01 --- /dev/null +++ b/unsloth/models/rl.py @@ -0,0 +1,39 @@ +# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__all__ = [ + "patch_rl", +] + +from trl.models.utils import unwrap_model_for_generation +from contextlib import contextmanager + + +def patch_rl(FastLanguageModel): + @contextmanager + def unsloth_unwrap_model_for_generation(model, *args, **kwargs): + FastLanguageModel.for_inference(model) + yield unwrap_model_for_generation(model, *args, **kwargs) + FastLanguageModel.for_training (model) + pass + + import trl.trainer + trainers = dir(trl.trainer) + trainers = [x for x in trainers if x.endswith("_trainer")] + unwrap = "unwrap_model_for_generation" + for trainer in trainers: + if hasattr(eval(f"trl.trainer.{trainer}"), unwrap): + exec(f"trl.trainer.{trainer}.{unwrap} = unsloth_{unwrap}") + pass +pass