Create rl.py

This commit is contained in:
Daniel Han 2025-02-05 05:14:01 -08:00
commit f921d34bf8

39
unsloth/models/rl.py Normal file
View file

@ -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