UnslothGRPOTrainer.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. from torch import Tensor
  2. import torch
  3. import torch.nn as nn
  4. from torch.nn import functional as F
  5. from trl.trainer.grpo_trainer import (Any, AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, Dataset, GRPOConfig, GRPOTrainer, GenerationConfig, IterableDataset, LLM, Optional, PeftConfig, PreTrainedModel, PreTrainedTokenizerBase, RepeatRandomSampler, RewardFunc, Sampler, SamplingParams, SyncRefModelCallback, Trainer, TrainerCallback, Union, apply_chat_template, broadcast_object_list, create_reference_model, defaultdict, gather, gather_object, generate_model_card, get_comet_experiment_url, is_conversational, is_deepspeed_zero3_enabled, is_peft_model, is_wandb_available, maybe_apply_chat_template, nn, os, pad, patch, prepare_deepspeed, set_seed, textwrap, torch, transformers, unwrap_model_for_generation, version, warnings, os, torch, transformers, Any, LLM, Union, apply_chat_template, broadcast_object_list, gather, gather_object, is_conversational, maybe_apply_chat_template, nn, os, pad, torch, unwrap_model_for_generation, GRPOTrainer, Trainer, gather, os, torch)
  6. import os
  7. from typing import *
  8. from dataclasses import dataclass, field
  9. from packaging.version import Version
  10. import torch
  11. import numpy as np
  12. from contextlib import nullcontext
  13. from torch.nn import functional as F
  14. torch_compile_options = {
  15. "epilogue_fusion" : True,
  16. "max_autotune" : False,
  17. "shape_padding" : True,
  18. "trace.enabled" : False,
  19. "triton.cudagraphs" : False,
  20. }
  21. @torch.compile(dynamic = True, fullgraph = True, options = torch_compile_options,)
  22. def selective_log_softmax(logits, index):
  23. logits = logits.to(torch.float32)
  24. selected_logits = torch.gather(logits, dim = -1, index = index.unsqueeze(-1)).squeeze(-1)
  25. # loop to reduce peak mem consumption
  26. # logsumexp_values = torch.stack([torch.logsumexp(lg, dim=-1) for lg in logits])
  27. logsumexp_values = torch.logsumexp(logits, dim = -1)
  28. per_token_logps = selected_logits - logsumexp_values # log_softmax(x_i) = x_i - logsumexp(x)
  29. return per_token_logps
  30. def grpo_compute_loss(old_logits, new_logits, input_ids, mask, beta, advantages):
  31. # All Unsloth Zoo code licensed under LGPLv3
  32. old_logits = old_logits.to(torch.float32)
  33. new_logits = new_logits.to(torch.float32)
  34. input_ids = input_ids.unsqueeze(-1)
  35. # x_i - logsumexp(x_i)
  36. old_x = torch.gather(old_logits, dim = -1, index = input_ids).squeeze(-1)
  37. new_x = torch.gather(new_logits, dim = -1, index = input_ids).squeeze(-1)
  38. old = old_x - torch.logsumexp(old_logits, dim = -1)
  39. new = new_x - torch.logsumexp(new_logits, dim = -1)
  40. # Reverse KL
  41. kl_i = torch.exp(old - new) - (old - new) - 1.0
  42. # Full correct reverse KL divergence?? Missing term maybe?
  43. # kl_i = torch.exp(new) * kl_i
  44. # Below is forward KL (normal KL)
  45. # kl_i = torch.exp(old) * (old - new)
  46. # Must detach - otherwise gradients are not propagated correctly!
  47. # exp(x - x) == 1
  48. loss_i = torch.exp(new - new.detach()) * advantages.unsqueeze(1)
  49. loss_i = -(loss_i - beta * kl_i)
  50. mask = mask.to(torch.float32)
  51. n_mask_per_reward = mask.sum(1)
  52. # See https://github.com/huggingface/trl/pull/2881
  53. # loss_per_reward = (loss_i * mask).sum(1) / n_mask_per_reward
  54. # loss = loss_per_reward.mean()
  55. loss = (loss_i * mask).sum() / mask.sum()
  56. # Get metrics as well which are folded
  57. with torch.inference_mode():
  58. completion_length = n_mask_per_reward.mean()
  59. mean_kl_per_reward = (kl_i * mask).sum(1) / n_mask_per_reward
  60. mean_kl = mean_kl_per_reward.mean()
  61. pass
  62. return loss, completion_length, mean_kl
  63. class UnslothEfficientGRPO(torch.autograd.Function):
  64. # All Unsloth Zoo code licensed under LGPLv3
  65. @staticmethod
  66. def forward(ctx, _new_hidden_states, _old_hidden_states, lm_head, _input_ids, _mask, _advantages, beta, scaler = None, n_chunks = 1):
  67. def compute_loss(new_hidden_states, old_hidden_states, input_ids, mask, advantages, scaling):
  68. new_logits = torch.matmul(new_hidden_states, lm_head.t())
  69. new_logits = new_logits[:, :-1, :] # exclude the last logit: it corresponds to the next token pred
  70. old_logits = torch.matmul(old_hidden_states, lm_head.t())
  71. old_logits = old_logits[:, :-1, :] # exclude the last logit: it corresponds to the next token pred
  72. loss, completion_length, mean_kl = grpo_compute_loss(
  73. old_logits, new_logits, input_ids, mask, beta, advantages,
  74. )
  75. # Scale loss if needed for mixed precision training
  76. scaled_loss = loss * scaling
  77. # Must add .loss.detach otherwise autograd uses 2x VRAM
  78. return scaled_loss, (loss.detach(), completion_length, mean_kl,)
  79. pass
  80. device =_new_hidden_states.device
  81. grad_inputs = torch.empty_like(_new_hidden_states)
  82. accumulated_loss = torch.zeros(1, device = device)
  83. accumulated_completion_length = torch.zeros(1, device = device)
  84. accumulated_mean_kl = torch.zeros(1, device = device)
  85. def accumulate_chunk(new_hidden_states_j, old_hidden_states_j, input_ids_j, mask_j, advantages_j, scaling):
  86. (chunk_grad_input,), (chunk_loss, (unscaled_loss, chunk_completion_length, chunk_mean_kl,)) = torch.func.grad_and_value(
  87. compute_loss,
  88. argnums = (0,),
  89. has_aux = True,
  90. )(new_hidden_states_j, old_hidden_states_j, input_ids_j, mask_j, advantages_j, scaling)
  91. accumulated_loss .add_(unscaled_loss)
  92. accumulated_completion_length.add_(chunk_completion_length)
  93. accumulated_mean_kl .add_(chunk_mean_kl)
  94. return chunk_grad_input
  95. pass
  96. accumulate_chunk = torch.compile(
  97. accumulate_chunk,
  98. fullgraph = True,
  99. options = torch_compile_options,
  100. )
  101. grad_inputs_chunks = torch.chunk(grad_inputs, chunks = n_chunks, dim = 0)
  102. new_hidden_states = torch.chunk(_new_hidden_states, chunks = n_chunks, dim = 0)
  103. old_hidden_states = torch.chunk(_old_hidden_states, chunks = n_chunks, dim = 0)
  104. input_ids = torch.chunk(_input_ids, chunks = n_chunks, dim = 0)
  105. mask = torch.chunk(_mask, chunks = n_chunks, dim = 0)
  106. advantages = torch.chunk(_advantages, chunks = n_chunks, dim = 0)
  107. # Get mixed precision scaling if seen
  108. scaling = scaler.get_scale() if scaler is not None else 1.0
  109. # Force torch.compile to use dynamic shapes for seqlen dim
  110. mark_dynamic = lambda x: torch._dynamo.mark_dynamic(x, 1)
  111. for (grad_inputs_j, new_hidden_states_j, old_hidden_states_j, input_ids_j, mask_j, advantages_j,) in \
  112. zip(grad_inputs_chunks, new_hidden_states, old_hidden_states, input_ids, mask, advantages):
  113. mark_dynamic(new_hidden_states_j)
  114. mark_dynamic(old_hidden_states_j)
  115. mark_dynamic(input_ids_j)
  116. mark_dynamic(mask_j)
  117. grad_inputs_j.copy_(
  118. accumulate_chunk(new_hidden_states_j, old_hidden_states_j, input_ids_j, mask_j, advantages_j, scaling)
  119. )
  120. pass
  121. grad_inputs .div_(n_chunks)
  122. accumulated_loss .div_(n_chunks)
  123. accumulated_completion_length.div_(n_chunks)
  124. accumulated_mean_kl .div_(n_chunks)
  125. ctx.save_for_backward(grad_inputs)
  126. return (
  127. accumulated_loss,
  128. accumulated_completion_length,
  129. accumulated_mean_kl,
  130. )
  131. pass
  132. @staticmethod
  133. def backward(ctx, grad_output, dcompletion_length, dmean_kl):
  134. (grad_input,) = ctx.saved_tensors
  135. return (grad_input, None, None, None, None, None, None, None, None,)
  136. pass
  137. def grpo_accumulated_loss(
  138. trainer,
  139. input_ids,
  140. logits_to_keep,
  141. completion_mask,
  142. advantages,
  143. n_chunks = -1,
  144. ):
  145. # All Unsloth Zoo code licensed under LGPLv3
  146. bsz, qlen = input_ids.shape
  147. # Find closest multiple
  148. factors = [i for i in range(1, bsz + 1) if bsz % i == 0]
  149. if n_chunks == -1: n_chunks = bsz
  150. n_chunks = factors[min(np.searchsorted(factors, n_chunks), len(factors)-1)]
  151. mixed_dtype = torch.float16 if os.environ.get('ACCELERATE_MIXED_PRECISION', 'fp16') == 'fp16' else torch.bfloat16
  152. os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"
  153. completion_input_ids = input_ids[:, -logits_to_keep:]
  154. lm_head = trainer.model.get_output_embeddings().weight
  155. with torch.amp.autocast(device_type = "cuda", dtype = mixed_dtype):
  156. with torch.inference_mode(), trainer.accelerator.unwrap_model(trainer.model, keep_fp32_wrapper = False).disable_adapter():
  157. old_hidden_states = trainer.model(input_ids = input_ids, logits_to_keep = logits_to_keep + 1).logits
  158. pass
  159. new_hidden_states = trainer.model(input_ids = input_ids, logits_to_keep = logits_to_keep + 1).logits
  160. loss, completion_length, mean_kl = UnslothEfficientGRPO.apply(
  161. new_hidden_states, old_hidden_states, lm_head,
  162. completion_input_ids, completion_mask, advantages, trainer.beta,
  163. trainer.accelerator.scaler,
  164. n_chunks,
  165. )
  166. return loss, completion_length, mean_kl
  167. # Old non efficient code path
  168. new_logits = torch.matmul(new_hidden_states, lm_head.t())
  169. new_logits = new_logits[:, :-1, :] # exclude the last logit: it corresponds to the next token pred
  170. old_logits = torch.matmul(old_hidden_states, lm_head.t())
  171. old_logits = old_logits[:, :-1, :] # exclude the last logit: it corresponds to the next token pred
  172. loss, completion_length, mean_kl = grpo_compute_loss(
  173. old_logits, new_logits, completion_input_ids, completion_mask, trainer.beta, advantages,
  174. )
  175. return loss, completion_length, mean_kl
  176. pass
  177. def vLLMSamplingParams(**kwargs):
  178. from vllm import SamplingParams
  179. sampling_params = SamplingParams(**kwargs)
  180. sampling_params._set_kwargs = kwargs
  181. return sampling_params
  182. @dataclass
  183. class UnslothGRPOConfig(GRPOConfig):
  184. """
  185. Configuration class for the [`GRPOTrainer`].
  186. Only the parameters specific to GRPO training are listed here. For details on other parameters, refer to the
  187. [`~transformers.TrainingArguments`] documentation.
  188. Using [`~transformers.HfArgumentParser`] we can turn this class into
  189. [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
  190. command line.
  191. Parameters:
  192. > Parameters that control the model and reference model
  193. model_init_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`):
  194. Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
  195. argument of the [`GRPOTrainer`] is provided as a string.
  196. > Parameters that control the data preprocessing
  197. remove_unused_columns (`bool`, *optional*, defaults to `False`):
  198. Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that
  199. requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`.
  200. max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
  201. Maximum length of the prompt. If the prompt is longer than this value, it will be truncated left.
  202. num_generations (`int` or `None`, *optional*, defaults to `8`):
  203. Number of generations per prompt to sample. The global batch size (num_processes * per_device_batch_size)
  204. must be divisible by this value.
  205. temperature (`float`, *optional*, defaults to `0.9`):
  206. Temperature for sampling. The higher the temperature, the more random the completions.
  207. max_completion_length (`int` or `None`, *optional*, defaults to `256`):
  208. Maximum length of the generated completion.
  209. ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
  210. This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
  211. improving generation speed. However, disabling this option allows training models that exceed the VRAM
  212. capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
  213. with vLLM generation.
  214. > Parameters that control generation acceleration powered by vLLM
  215. use_vllm (`bool`, *optional*, defaults to `False`):
  216. Whether to use vLLM for generating completions. If set to `True`, ensure that a GPU is kept unused for
  217. training, as vLLM will require one for generation. vLLM must be installed (`pip install vllm`).
  218. vllm_device (`str`, *optional*, defaults to `"auto"`):
  219. Device where vLLM generation will run, e.g. `"cuda:1"`. If set to `"auto"` (default), the system will
  220. automatically select the next available GPU after the last one used for training. This assumes that
  221. training has not already occupied all available GPUs. If only one device is available, the device will be
  222. shared between both training and vLLM.
  223. vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.9`):
  224. Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV cache on the
  225. device dedicated to generation powered by vLLM. Higher values will increase the KV cache size and thus
  226. improve the model's throughput. However, if the value is too high, it may cause out-of-memory (OOM) errors
  227. during initialization.
  228. vllm_dtype (`str`, *optional*, defaults to `"auto"`):
  229. Data type to use for vLLM generation. If set to `"auto"`, the data type will be automatically determined
  230. based on the model configuration. Find the supported values in the vLLM documentation.
  231. vllm_max_model_len (`int` or `None`, *optional*, defaults to `None`):
  232. If set, the `max_model_len` to use for vLLM. This could be useful when running with reduced
  233. `vllm_gpu_memory_utilization`, leading to a reduced KV cache size. If not set, vLLM will use the model
  234. context size, which might be much larger than the KV cache, leading to inefficiencies.
  235. > Parameters that control the training
  236. learning_rate (`float`, *optional*, defaults to `1e-6`):
  237. Initial learning rate for [`AdamW`] optimizer. The default value replaces that of
  238. [`~transformers.TrainingArguments`].
  239. beta (`float`, *optional*, defaults to `0.04`):
  240. KL coefficient.
  241. reward_weights (`list[float]` or `None`, *optional*, defaults to `None`):
  242. Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are
  243. weighted equally with weight `1.0`.
  244. sync_ref_model (`bool`, *optional*, defaults to `False`):
  245. Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using
  246. the `ref_model_mixup_alpha` parameter. This synchronization originites from the
  247. [TR-DPO](https://huggingface.co/papers/2404.09656) paper.
  248. ref_model_mixup_alpha (`float`, *optional*, defaults to `0.9`):
  249. α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix
  250. between the current policy and the previous reference policy during updates. The reference policy is
  251. updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you
  252. must set `sync_ref_model=True`.
  253. ref_model_sync_steps (`int`, *optional*, defaults to `64`):
  254. τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how
  255. frequently the current policy is synchronized with the reference policy. To use this parameter, you must
  256. set `sync_ref_model=True`.
  257. > Parameters that control the logging
  258. log_completions (`bool`, *optional*, defaults to `False`):
  259. Whether to log the completions during training.
  260. """
  261. vllm_sampling_params: Optional[Any] = field(
  262. default = None,
  263. metadata = {'help': 'vLLM SamplingParams'},
  264. )
  265. unsloth_num_chunks : Optional[int] = field(
  266. default = -1,
  267. metadata = {'help': 'Chunk size to reduce memory usage. -1 is most efficient.'},
  268. )
  269. def __init__(
  270. self,
  271. output_dir = None,
  272. overwrite_output_dir = None,
  273. do_train = False,
  274. do_eval = False,
  275. do_predict = False,
  276. eval_strategy = 'no',
  277. prediction_loss_only = False,
  278. per_device_train_batch_size = 4,
  279. per_device_eval_batch_size = 4,
  280. per_gpu_train_batch_size = None,
  281. per_gpu_eval_batch_size = None,
  282. gradient_accumulation_steps = 2,
  283. eval_accumulation_steps = 2,
  284. eval_delay = 0,
  285. torch_empty_cache_steps = 250,
  286. learning_rate = 5e-05,
  287. weight_decay = 0.01,
  288. adam_beta1 = 0.9,
  289. adam_beta2 = 0.999,
  290. adam_epsilon = 1e-08,
  291. max_grad_norm = 1.0,
  292. num_train_epochs = 3.0,
  293. max_steps = -1,
  294. lr_scheduler_type = 'linear',
  295. warmup_ratio = 0.1,
  296. warmup_steps = 0,
  297. log_level = 'passive',
  298. log_level_replica = 'warning',
  299. log_on_each_node = True,
  300. logging_dir = None,
  301. logging_strategy = 'steps',
  302. logging_first_step = False,
  303. logging_steps = 1,
  304. logging_nan_inf_filter = False,
  305. save_strategy = 'steps',
  306. save_steps = 500,
  307. save_total_limit = None,
  308. save_safetensors = True,
  309. save_on_each_node = False,
  310. save_only_model = False,
  311. restore_callback_states_from_checkpoint = False,
  312. no_cuda = False,
  313. use_cpu = False,
  314. use_mps_device = False,
  315. seed = 3407,
  316. data_seed = 3407,
  317. jit_mode_eval = False,
  318. use_ipex = False,
  319. bf16 = False,
  320. fp16 = False,
  321. fp16_opt_level = 'O1',
  322. half_precision_backend = 'auto',
  323. bf16_full_eval = False,
  324. fp16_full_eval = False,
  325. tf32 = None,
  326. local_rank = -1,
  327. ddp_backend = None,
  328. tpu_num_cores = None,
  329. tpu_metrics_debug = False,
  330. debug = '',
  331. dataloader_drop_last = False,
  332. eval_steps = None,
  333. dataloader_num_workers = 0,
  334. dataloader_prefetch_factor = None,
  335. past_index = -1,
  336. run_name = None,
  337. disable_tqdm = None,
  338. remove_unused_columns = False,
  339. label_names = None,
  340. load_best_model_at_end = False,
  341. metric_for_best_model = None,
  342. greater_is_better = None,
  343. ignore_data_skip = False,
  344. fsdp = '',
  345. fsdp_min_num_params = 0,
  346. fsdp_config = None,
  347. fsdp_transformer_layer_cls_to_wrap = None,
  348. accelerator_config = None,
  349. deepspeed = None,
  350. label_smoothing_factor = 0.0,
  351. optim = 'adamw_8bit',
  352. optim_args = None,
  353. adafactor = False,
  354. group_by_length = False,
  355. length_column_name = 'length',
  356. report_to = None,
  357. ddp_find_unused_parameters = None,
  358. ddp_bucket_cap_mb = None,
  359. ddp_broadcast_buffers = None,
  360. dataloader_pin_memory = True,
  361. dataloader_persistent_workers = False,
  362. skip_memory_metrics = True,
  363. use_legacy_prediction_loop = False,
  364. push_to_hub = False,
  365. resume_from_checkpoint = None,
  366. hub_model_id = None,
  367. hub_strategy = 'every_save',
  368. hub_token = None,
  369. hub_private_repo = None,
  370. hub_always_push = False,
  371. gradient_checkpointing = False,
  372. gradient_checkpointing_kwargs = None,
  373. include_inputs_for_metrics = False,
  374. eval_do_concat_batches = True,
  375. fp16_backend = 'auto',
  376. evaluation_strategy = None,
  377. push_to_hub_model_id = None,
  378. push_to_hub_organization = None,
  379. push_to_hub_token = None,
  380. mp_parameters = '',
  381. auto_find_batch_size = False,
  382. full_determinism = False,
  383. torchdynamo = None,
  384. ray_scope = 'last',
  385. ddp_timeout = 1800,
  386. torch_compile = False,
  387. torch_compile_backend = None,
  388. torch_compile_mode = None,
  389. dispatch_batches = None,
  390. split_batches = None,
  391. include_tokens_per_second = False,
  392. include_num_input_tokens_seen = False,
  393. neftune_noise_alpha = None,
  394. optim_target_modules = None,
  395. batch_eval_metrics = False,
  396. eval_on_start = False,
  397. use_liger_kernel = False,
  398. eval_use_gather_object = False,
  399. average_tokens_across_devices = False,
  400. model_init_kwargs = None,
  401. max_prompt_length = 512,
  402. num_generations = 8,
  403. temperature = 0.9,
  404. max_completion_length = 256,
  405. ds3_gather_for_generation = True,
  406. use_vllm = False,
  407. vllm_device = 'auto',
  408. vllm_gpu_memory_utilization = 0.9,
  409. vllm_dtype = 'auto',
  410. vllm_max_model_len = None,
  411. beta = 0.04,
  412. reward_weights = None,
  413. sync_ref_model = False,
  414. ref_model_mixup_alpha = 0.9,
  415. ref_model_sync_steps = 64,
  416. log_completions = False,
  417. vllm_sampling_params = None,
  418. unsloth_num_chunks = -1,
  419. **kwargs,
  420. ):
  421. if learning_rate < 1e-7: raise FloatingPointError(f'Unsloth: Your learning rate of `{learning_rate}` is too small and less than 1e-7! Consider increasing it, otherwise gradient updates will be close to 0!')
  422. if learning_rate > 1: raise OverflowError(f'Unsloth: Your learning rate of `{learning_rate}` is way too larger > 1! Consider decreasing it to 1e-1, otherwise gradient updates will explode!')
  423. if output_dir is None and save_strategy == 'steps' and save_steps == 500:
  424. output_dir = 'unsloth_training_checkpoints'
  425. save_strategy = 'no'
  426. div = per_device_train_batch_size // num_generations
  427. if div * num_generations != per_device_train_batch_size:
  428. print('Unsloth: We now expect `per_device_train_batch_size` to be a multiple of `num_generations`.\nWe will change the batch size of ' + str(per_device_train_batch_size) + ' to the `num_generations` of ' + str(num_generations))
  429. per_device_train_batch_size = num_generations
  430. super().__init__(
  431. output_dir = output_dir,
  432. overwrite_output_dir = overwrite_output_dir,
  433. do_train = do_train,
  434. do_eval = do_eval,
  435. do_predict = do_predict,
  436. eval_strategy = eval_strategy,
  437. prediction_loss_only = prediction_loss_only,
  438. per_device_train_batch_size = per_device_train_batch_size,
  439. per_device_eval_batch_size = per_device_eval_batch_size,
  440. per_gpu_train_batch_size = per_gpu_train_batch_size,
  441. per_gpu_eval_batch_size = per_gpu_eval_batch_size,
  442. gradient_accumulation_steps = gradient_accumulation_steps,
  443. eval_accumulation_steps = eval_accumulation_steps,
  444. eval_delay = eval_delay,
  445. torch_empty_cache_steps = torch_empty_cache_steps,
  446. learning_rate = learning_rate,
  447. weight_decay = weight_decay,
  448. adam_beta1 = adam_beta1,
  449. adam_beta2 = adam_beta2,
  450. adam_epsilon = adam_epsilon,
  451. max_grad_norm = max_grad_norm,
  452. num_train_epochs = num_train_epochs,
  453. max_steps = max_steps,
  454. lr_scheduler_type = lr_scheduler_type,
  455. warmup_ratio = warmup_ratio,
  456. warmup_steps = warmup_steps,
  457. log_level = log_level,
  458. log_level_replica = log_level_replica,
  459. log_on_each_node = log_on_each_node,
  460. logging_dir = logging_dir,
  461. logging_strategy = logging_strategy,
  462. logging_first_step = logging_first_step,
  463. logging_steps = logging_steps,
  464. logging_nan_inf_filter = logging_nan_inf_filter,
  465. save_strategy = save_strategy,
  466. save_steps = save_steps,
  467. save_total_limit = save_total_limit,
  468. save_safetensors = save_safetensors,
  469. save_on_each_node = save_on_each_node,
  470. save_only_model = save_only_model,
  471. restore_callback_states_from_checkpoint = restore_callback_states_from_checkpoint,
  472. no_cuda = no_cuda,
  473. use_cpu = use_cpu,
  474. use_mps_device = use_mps_device,
  475. seed = seed,
  476. data_seed = data_seed,
  477. jit_mode_eval = jit_mode_eval,
  478. use_ipex = use_ipex,
  479. bf16 = bf16,
  480. fp16 = fp16,
  481. fp16_opt_level = fp16_opt_level,
  482. half_precision_backend = half_precision_backend,
  483. bf16_full_eval = bf16_full_eval,
  484. fp16_full_eval = fp16_full_eval,
  485. tf32 = tf32,
  486. local_rank = local_rank,
  487. ddp_backend = ddp_backend,
  488. tpu_num_cores = tpu_num_cores,
  489. tpu_metrics_debug = tpu_metrics_debug,
  490. debug = debug,
  491. dataloader_drop_last = dataloader_drop_last,
  492. eval_steps = eval_steps,
  493. dataloader_num_workers = dataloader_num_workers,
  494. dataloader_prefetch_factor = dataloader_prefetch_factor,
  495. past_index = past_index,
  496. run_name = run_name,
  497. disable_tqdm = disable_tqdm,
  498. remove_unused_columns = remove_unused_columns,
  499. label_names = label_names,
  500. load_best_model_at_end = load_best_model_at_end,
  501. metric_for_best_model = metric_for_best_model,
  502. greater_is_better = greater_is_better,
  503. ignore_data_skip = ignore_data_skip,
  504. fsdp = fsdp,
  505. fsdp_min_num_params = fsdp_min_num_params,
  506. fsdp_config = fsdp_config,
  507. fsdp_transformer_layer_cls_to_wrap = fsdp_transformer_layer_cls_to_wrap,
  508. accelerator_config = accelerator_config,
  509. deepspeed = deepspeed,
  510. label_smoothing_factor = label_smoothing_factor,
  511. optim = optim,
  512. optim_args = optim_args,
  513. adafactor = adafactor,
  514. group_by_length = group_by_length,
  515. length_column_name = length_column_name,
  516. report_to = report_to,
  517. ddp_find_unused_parameters = ddp_find_unused_parameters,
  518. ddp_bucket_cap_mb = ddp_bucket_cap_mb,
  519. ddp_broadcast_buffers = ddp_broadcast_buffers,
  520. dataloader_pin_memory = dataloader_pin_memory,
  521. dataloader_persistent_workers = dataloader_persistent_workers,
  522. skip_memory_metrics = skip_memory_metrics,
  523. use_legacy_prediction_loop = use_legacy_prediction_loop,
  524. push_to_hub = push_to_hub,
  525. resume_from_checkpoint = resume_from_checkpoint,
  526. hub_model_id = hub_model_id,
  527. hub_strategy = hub_strategy,
  528. hub_token = hub_token,
  529. hub_private_repo = hub_private_repo,
  530. hub_always_push = hub_always_push,
  531. gradient_checkpointing = gradient_checkpointing,
  532. gradient_checkpointing_kwargs = gradient_checkpointing_kwargs,
  533. include_inputs_for_metrics = include_inputs_for_metrics,
  534. eval_do_concat_batches = eval_do_concat_batches,
  535. fp16_backend = fp16_backend,
  536. evaluation_strategy = evaluation_strategy,
  537. push_to_hub_model_id = push_to_hub_model_id,
  538. push_to_hub_organization = push_to_hub_organization,
  539. push_to_hub_token = push_to_hub_token,
  540. mp_parameters = mp_parameters,
  541. auto_find_batch_size = auto_find_batch_size,
  542. full_determinism = full_determinism,
  543. torchdynamo = torchdynamo,
  544. ray_scope = ray_scope,
  545. ddp_timeout = ddp_timeout,
  546. torch_compile = torch_compile,
  547. torch_compile_backend = torch_compile_backend,
  548. torch_compile_mode = torch_compile_mode,
  549. dispatch_batches = dispatch_batches,
  550. split_batches = split_batches,
  551. include_tokens_per_second = include_tokens_per_second,
  552. include_num_input_tokens_seen = include_num_input_tokens_seen,
  553. neftune_noise_alpha = neftune_noise_alpha,
  554. optim_target_modules = optim_target_modules,
  555. batch_eval_metrics = batch_eval_metrics,
  556. eval_on_start = eval_on_start,
  557. use_liger_kernel = use_liger_kernel,
  558. eval_use_gather_object = eval_use_gather_object,
  559. average_tokens_across_devices = average_tokens_across_devices,
  560. model_init_kwargs = model_init_kwargs,
  561. max_prompt_length = max_prompt_length,
  562. num_generations = num_generations,
  563. temperature = temperature,
  564. max_completion_length = max_completion_length,
  565. ds3_gather_for_generation = ds3_gather_for_generation,
  566. use_vllm = use_vllm,
  567. vllm_device = vllm_device,
  568. vllm_gpu_memory_utilization = vllm_gpu_memory_utilization,
  569. vllm_dtype = vllm_dtype,
  570. vllm_max_model_len = vllm_max_model_len,
  571. beta = beta,
  572. reward_weights = reward_weights,
  573. sync_ref_model = sync_ref_model,
  574. ref_model_mixup_alpha = ref_model_mixup_alpha,
  575. ref_model_sync_steps = ref_model_sync_steps,
  576. log_completions = log_completions,**kwargs)
  577. self.vllm_sampling_params = vllm_sampling_params
  578. self.unsloth_num_chunks = unsloth_num_chunks
  579. pass
  580. class _UnslothGRPOTrainer(Trainer):
  581. """"""
  582. _tag_names = ["trl", "grpo"]
  583. def __init__(
  584. self,
  585. model: Union[str, PreTrainedModel],
  586. reward_funcs: Union[RewardFunc, list[RewardFunc]],
  587. args: GRPOConfig = None,
  588. train_dataset: Optional[Union[Dataset, IterableDataset]] = None,
  589. eval_dataset: Optional[Union[Dataset, IterableDataset, dict[str, Union[Dataset, IterableDataset]]]] = None,
  590. processing_class: Optional[PreTrainedTokenizerBase] = None,
  591. reward_processing_classes: Optional[Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]] = None,
  592. callbacks: Optional[list[TrainerCallback]] = None,
  593. optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None),
  594. peft_config: Optional["PeftConfig"] = None,
  595. ):
  596. if hasattr(model, 'vllm_engine') and hasattr(args, 'use_vllm') and (getattr(args, 'use_vllm', False) == False): args.use_vllm = True
  597. # Args
  598. if args is None:
  599. model_name = model if isinstance(model, str) else model.config._name_or_path
  600. model_name = model_name.split("/")[-1]
  601. args = GRPOConfig(f"{model_name}-GRPO")
  602. # Models
  603. # Trained model
  604. model_init_kwargs = args.model_init_kwargs or {}
  605. if isinstance(model, str):
  606. model_id = model
  607. torch_dtype = model_init_kwargs.get("torch_dtype")
  608. if isinstance(torch_dtype, torch.dtype) or torch_dtype == "auto" or torch_dtype is None:
  609. pass # torch_dtype is already a torch.dtype or "auto" or None
  610. elif isinstance(torch_dtype, str): # it's a str, but not "auto"
  611. torch_dtype = getattr(torch, torch_dtype)
  612. model_init_kwargs["torch_dtype"] = torch_dtype
  613. else:
  614. raise ValueError(
  615. "Invalid `torch_dtype` passed to `GRPOConfig`. Expected either 'auto' or a string representing "
  616. f"a `torch.dtype` (e.g., 'float32'), but got {torch_dtype}."
  617. )
  618. # Disable caching if gradient checkpointing is enabled (not supported)
  619. model_init_kwargs["use_cache"] = (
  620. False if args.gradient_checkpointing else model_init_kwargs.get("use_cache")
  621. )
  622. model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
  623. else:
  624. model_id = model.config._name_or_path
  625. if args.model_init_kwargs is not None:
  626. raise ValueError(
  627. "You passed `model_init_kwargs` to the `GRPOConfig`, but your model is already instantiated. "
  628. "This argument can only be used when the `model` argument is a string."
  629. )
  630. if False:
  631. model = model
  632. # Reference model
  633. if is_deepspeed_zero3_enabled():
  634. self.ref_model = AutoModelForCausalLM.from_pretrained(model_id, **model_init_kwargs)
  635. elif not is_peft_model(model):
  636. # If PEFT configuration is not provided, create a reference model based on the initial model.
  637. self.ref_model = create_reference_model(model)
  638. else:
  639. # If PEFT is used, the reference model is not needed since the adapter can be disabled
  640. # to revert to the initial model.
  641. self.ref_model = None
  642. # Processing class
  643. if processing_class is None:
  644. processing_class = AutoTokenizer.from_pretrained(model.config._name_or_path, padding_side="left")
  645. # Reward functions
  646. if not isinstance(reward_funcs, list):
  647. reward_funcs = [reward_funcs]
  648. for i, reward_func in enumerate(reward_funcs):
  649. if isinstance(reward_func, str):
  650. reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained(
  651. reward_func, num_labels=1, **model_init_kwargs
  652. )
  653. self.reward_funcs = reward_funcs
  654. # Reward weights
  655. if args.reward_weights is not None:
  656. if len(args.reward_weights) != len(reward_funcs):
  657. raise ValueError(
  658. f"Number of reward weights ({len(args.reward_weights)}) must match number of reward "
  659. f"functions ({len(reward_funcs)})"
  660. )
  661. self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32)
  662. else:
  663. self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32)
  664. # Reward processing class
  665. if reward_processing_classes is None:
  666. reward_processing_classes = [None] * len(reward_funcs)
  667. elif not isinstance(reward_processing_classes, list):
  668. reward_processing_classes = [reward_processing_classes]
  669. else:
  670. if len(reward_processing_classes) != len(reward_funcs):
  671. raise ValueError("The number of reward processing classes must match the number of reward functions.")
  672. for i, (reward_processing_class, reward_func) in enumerate(zip(reward_processing_classes, reward_funcs)):
  673. if isinstance(reward_func, PreTrainedModel):
  674. if reward_processing_class is None:
  675. reward_processing_class = AutoTokenizer.from_pretrained(reward_func.config._name_or_path)
  676. if reward_processing_class.pad_token_id is None:
  677. reward_processing_class.pad_token = reward_processing_class.eos_token
  678. # The reward model computes the reward for the latest non-padded token in the input sequence.
  679. # So it's important to set the pad token ID to the padding token ID of the processing class.
  680. reward_func.config.pad_token_id = reward_processing_class.pad_token_id
  681. reward_processing_classes[i] = reward_processing_class
  682. self.reward_processing_classes = reward_processing_classes
  683. # Data collator
  684. def data_collator(features): # No data collation is needed in GRPO
  685. return features
  686. # Training arguments
  687. self.max_prompt_length = args.max_prompt_length
  688. self.max_completion_length = args.max_completion_length # = |o_i| in the GRPO paper
  689. self.num_generations = args.num_generations # = G in the GRPO paper
  690. self.use_vllm = args.use_vllm
  691. self.beta = args.beta
  692. # The trainer estimates the number of FLOPs (floating-point operations) using the number of elements in the
  693. # input tensor associated with the key "input_ids". However, in GRPO, the sampled data does not include the
  694. # "input_ids" key. Instead, the available keys is "prompt". As a result, the trainer issues the warning:
  695. # "Could not estimate the number of tokens of the input, floating-point operations will not be computed." To
  696. # suppress this warning, we set the "estimate_tokens" key in the model's "warnings_issued" dictionary to True.
  697. # This acts as a flag to indicate that the warning has already been issued.
  698. model.warnings_issued["estimate_tokens"] = True
  699. # Initialize the metrics
  700. self._metrics = defaultdict(list)
  701. self.log_completions = args.log_completions
  702. super().__init__(
  703. model=model,
  704. args=args,
  705. data_collator=data_collator,
  706. train_dataset=train_dataset,
  707. eval_dataset=eval_dataset,
  708. processing_class=processing_class,
  709. callbacks=callbacks,
  710. optimizers=optimizers,
  711. )
  712. # Check if the per_device_train/eval_batch_size * num processes can be divided by the number of generations
  713. num_processes = self.accelerator.num_processes
  714. global_batch_size = args.per_device_train_batch_size * num_processes
  715. possible_values = [n_gen for n_gen in range(2, global_batch_size + 1) if (global_batch_size) % n_gen == 0]
  716. if self.num_generations not in possible_values:
  717. raise ValueError(
  718. f"The global train batch size ({num_processes} x {args.per_device_train_batch_size}) must be evenly "
  719. f"divisible by the number of generations per prompt ({self.num_generations}). Given the current train "
  720. f"batch size, the valid values for the number of generations are: {possible_values}."
  721. )
  722. if self.args.eval_strategy != "no":
  723. global_batch_size = args.per_device_eval_batch_size * num_processes
  724. possible_values = [n_gen for n_gen in range(2, global_batch_size + 1) if (global_batch_size) % n_gen == 0]
  725. if self.num_generations not in possible_values:
  726. raise ValueError(
  727. f"The global eval batch size ({num_processes} x {args.per_device_eval_batch_size}) must be evenly "
  728. f"divisible by the number of generations per prompt ({self.num_generations}). Given the current "
  729. f"eval batch size, the valid values for the number of generations are: {possible_values}."
  730. )
  731. # Ensure each process receives a unique seed to prevent duplicate completions when generating with
  732. # transformers if num_generations exceeds per_device_train_batch_size. We could skip it if we use vLLM, but
  733. # it's safer to set it in all cases.
  734. set_seed(args.seed, device_specific=True)
  735. if self.use_vllm:
  736. self.llm = model.vllm_engine; self._last_loaded_step = 0; self.sampling_params = SamplingParams(
  737. temperature=args.temperature,
  738. max_tokens=self.max_completion_length,**getattr(getattr(args, 'vllm_sampling_params', vLLMSamplingParams()), '_set_kwargs', {}),)
  739. else:
  740. self.generation_config = GenerationConfig(
  741. max_new_tokens=self.max_completion_length,
  742. do_sample=True,
  743. temperature=args.temperature,
  744. pad_token_id=processing_class.pad_token_id,
  745. )
  746. # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
  747. # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
  748. # self.model_accepts_loss_kwargs to False to enable scaling.
  749. self.model_accepts_loss_kwargs = False
  750. # Add tags to the model
  751. self.model.add_model_tags(self._tag_names)
  752. if self.ref_model is not None:
  753. if self.is_deepspeed_enabled:
  754. self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
  755. else:
  756. self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
  757. if args.sync_ref_model:
  758. self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator))
  759. for i, reward_func in enumerate(self.reward_funcs):
  760. if isinstance(reward_func, PreTrainedModel):
  761. self.reward_funcs[i] = self.accelerator.prepare_model(reward_func, evaluation_mode=True)
  762. def _set_signature_columns_if_needed(self):
  763. # If `self.args.remove_unused_columns` is True, non-signature columns are removed.
  764. # By default, this method sets `self._signature_columns` to the model's expected inputs.
  765. # In GRPOTrainer, we preprocess data, so using the model's signature columns doesn't work.
  766. # Instead, we set them to the columns expected by the `training_step` method, hence the override.
  767. if self._signature_columns is None:
  768. self._signature_columns = ["prompt"]
  769. def _get_train_sampler(self) -> Sampler:
  770. # Returns a sampler that ensures each prompt is repeated across multiple processes. This guarantees that
  771. # identical prompts are distributed to different GPUs, allowing rewards to be computed and normalized correctly
  772. # within each prompt group. Using the same seed across processes ensures consistent prompt assignment,
  773. # preventing discrepancies in group formation.
  774. return RepeatRandomSampler(self.train_dataset, self.num_generations, seed=self.args.seed)
  775. def _get_eval_sampler(self, eval_dataset) -> Sampler:
  776. # Returns a sampler that ensures each prompt is repeated across multiple processes. This guarantees that
  777. # identical prompts are distributed to different GPUs, allowing rewards to be computed and normalized correctly
  778. # within each prompt group. Using the same seed across processes ensures consistent prompt assignment,
  779. # preventing discrepancies in group formation.
  780. return RepeatRandomSampler(eval_dataset, self.num_generations, seed=self.args.seed)
  781. # Get the per-token log probabilities for the completions for the model and the reference model
  782. def _get_per_token_logps(self, model, input_ids, attention_mask, logits_to_keep):
  783. return None # Unsloth efficient GRPO
  784. if not hasattr(self, '_autocast_dtype'):
  785. self._autocast_dtype = torch.float16 if os.environ.get('ACCELERATE_MIXED_PRECISION', 'fp16') == 'fp16' else torch.bfloat16
  786. with torch.amp.autocast(device_type = 'cuda', dtype = self._autocast_dtype):
  787. # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
  788. logits = model(input_ids=input_ids, attention_mask=attention_mask, logits_to_keep=logits_to_keep + 1).logits
  789. logits = logits[:, :-1, :] # (B, L-1, V), exclude the last logit: it corresponds to the next token pred
  790. input_ids = input_ids[:, -logits_to_keep:]
  791. # For transformers<=4.48, logits_to_keep argument isn't supported, so here we drop logits ourselves.
  792. # See https://github.com/huggingface/trl/issues/2770
  793. logits = logits[:, -logits_to_keep:]
  794. return logits
  795. # return selective_log_softmax(logits, input_ids) # compute logprobs for the input tokens
  796. pass
  797. def _move_model_to_vllm(self, *args, **kwargs): return None
  798. def _prepare_inputs(self, inputs: dict[str, Union[torch.Tensor, Any]]) -> dict[str, Union[torch.Tensor, Any]]:
  799. device = self.accelerator.device
  800. prompts = [x["prompt"] for x in inputs]
  801. prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs]
  802. prompt_inputs = self.processing_class(
  803. prompts_text, return_tensors="pt", padding=True, padding_side="left", add_special_tokens=False
  804. )
  805. prompt_inputs = super()._prepare_inputs(prompt_inputs)
  806. prompt_ids, prompt_mask = prompt_inputs["input_ids"], prompt_inputs["attention_mask"]
  807. if self.max_prompt_length is not None:
  808. prompt_ids = prompt_ids[:, -self.max_prompt_length :]
  809. prompt_mask = prompt_mask[:, -self.max_prompt_length :]
  810. # Generate completions using either vLLM or regular generation
  811. if self.args.use_vllm:
  812. # First, have main process load weights if needed
  813. if self.state.global_step != self._last_loaded_step:
  814. self._move_model_to_vllm()
  815. self._last_loaded_step = self.state.global_step
  816. # Generate completions using vLLM: gather all prompts and use them in a single call in the main process
  817. all_prompts_text = gather_object(prompts_text)
  818. if self.accelerator.is_main_process:
  819. outputs = self.llm.generate(all_prompts_text, sampling_params=self.sampling_params, use_tqdm=False, lora_request = self.model.load_lora('grpo_trainer_lora_model', load_tensors = True))
  820. completion_ids = [out.token_ids for completions in outputs for out in completions.outputs]
  821. else:
  822. completion_ids = [None] * len(all_prompts_text)
  823. # Broadcast the completions from the main process to all processes, ensuring each process receives its
  824. # corresponding slice.
  825. completion_ids = broadcast_object_list(completion_ids, from_process=0)
  826. process_slice = slice(
  827. self.accelerator.process_index * len(prompts),
  828. (self.accelerator.process_index + 1) * len(prompts),
  829. )
  830. completion_ids = completion_ids[process_slice]
  831. # Pad the completions, and concatenate them with the prompts
  832. completion_ids = [torch.tensor(ids, device=device) for ids in completion_ids]
  833. completion_ids = pad(completion_ids, padding_value=self.processing_class.pad_token_id)
  834. prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1)
  835. else:
  836. # Regular generation path
  837. with unwrap_model_for_generation(self.model, self.accelerator) as unwrapped_model:
  838. prompt_completion_ids = unwrapped_model.generate(
  839. prompt_ids, attention_mask=prompt_mask, generation_config=self.generation_config
  840. )
  841. # Compute prompt length and extract completion ids
  842. prompt_length = prompt_ids.size(1)
  843. prompt_ids = prompt_completion_ids[:, :prompt_length]
  844. completion_ids = prompt_completion_ids[:, prompt_length:]
  845. # Mask everything after the first EOS token
  846. is_eos = completion_ids == self.processing_class.eos_token_id
  847. eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
  848. eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
  849. sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
  850. completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int()
  851. # Concatenate prompt_mask with completion_mask for logit computation
  852. attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B*G, P+C)
  853. logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
  854. with torch.inference_mode(), torch.amp.autocast(device_type = 'cuda', dtype = torch.float16 if os.environ.get('ACCELERATE_MIXED_PRECISION', 'fp16') == 'fp16' else torch.bfloat16) if not torch.is_autocast_enabled('cuda') else nullcontext():
  855. if self.ref_model is not None:
  856. ref_per_token_logps = self._get_per_token_logps(
  857. self.ref_model, prompt_completion_ids, attention_mask, logits_to_keep
  858. )
  859. else:
  860. with self.accelerator.unwrap_model(self.model, keep_fp32_wrapper = False).disable_adapter():
  861. ref_per_token_logps = self._get_per_token_logps(
  862. self.model, prompt_completion_ids, attention_mask, logits_to_keep
  863. )
  864. # Decode the generated completions
  865. completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
  866. if is_conversational(inputs[0]):
  867. completions = []
  868. for prompt, completion in zip(prompts, completions_text):
  869. bootstrap = prompt.pop()["content"] if prompt[-1]["role"] == "assistant" else ""
  870. completions.append([{"role": "assistant", "content": bootstrap + completion}])
  871. else:
  872. completions = completions_text
  873. rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device)
  874. for i, (reward_func, reward_processing_class) in enumerate(
  875. zip(self.reward_funcs, self.reward_processing_classes)
  876. ):
  877. if isinstance(reward_func, nn.Module): # Module instead of PretrainedModel for compat with compiled models
  878. if is_conversational(inputs[0]):
  879. messages = [{"messages": p + c} for p, c in zip(prompts, completions)]
  880. texts = [apply_chat_template(x, reward_processing_class)["text"] for x in messages]
  881. else:
  882. texts = [p + c for p, c in zip(prompts, completions)]
  883. reward_inputs = reward_processing_class(
  884. texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False
  885. )
  886. reward_inputs = super()._prepare_inputs(reward_inputs)
  887. with torch.inference_mode(), torch.amp.autocast(device_type = 'cuda', dtype = torch.float16 if os.environ.get('ACCELERATE_MIXED_PRECISION', 'fp16') == 'fp16' else torch.bfloat16) if not torch.is_autocast_enabled('cuda') else nullcontext():
  888. rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,)
  889. else:
  890. # Repeat all input columns (but "prompt" and "completion") to match the number of generations
  891. keys = [key for key in inputs[0] if key not in ["prompt", "completion"]]
  892. reward_kwargs = {key: [example[key] for example in inputs] for key in keys}
  893. output_reward_func = reward_func(prompts=prompts, completions=completions, **reward_kwargs)
  894. rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device)
  895. # Gather the reward per function: this part is crucial, because the rewards are normalized per group and the
  896. # completions may be distributed across processes
  897. rewards_per_func = gather(rewards_per_func)
  898. # Apply weights to each reward function's output and sum
  899. rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).sum(dim=1)
  900. # Compute grouped-wise rewards
  901. mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1)
  902. std_grouped_rewards = rewards.view(-1, self.num_generations).std(dim=1)
  903. # Normalize the rewards to compute the advantages
  904. mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
  905. std_grouped_rewards = std_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
  906. advantages = (rewards - mean_grouped_rewards) / (std_grouped_rewards + 1e-4)
  907. # Slice to keep only the local part of the data
  908. process_slice = slice(
  909. self.accelerator.process_index * len(prompts),
  910. (self.accelerator.process_index + 1) * len(prompts),
  911. )
  912. advantages = advantages[process_slice]
  913. # Log the metrics
  914. reward_per_func = rewards_per_func.mean(0)
  915. for i, reward_func in enumerate(self.reward_funcs):
  916. if isinstance(reward_func, nn.Module): # Module instead of PretrainedModel for compat with compiled models
  917. reward_func_name = reward_func.config._name_or_path.split("/")[-1]
  918. else:
  919. reward_func_name = reward_func.__name__
  920. self._metrics[f"rewards/{reward_func_name}"].append(reward_per_func[i].item())
  921. self._metrics["reward"].append(rewards.mean().item())
  922. self._metrics["reward_std"].append(std_grouped_rewards.mean().item())
  923. if (
  924. self.log_completions
  925. and self.state.global_step % self.args.logging_steps == 0
  926. and "wandb" in self.args.report_to
  927. ):
  928. import pandas as pd
  929. # For logging
  930. table = {
  931. "step": [str(self.state.global_step)] * len(rewards),
  932. "prompt": gather_object(prompts_text),
  933. "completion": gather_object(completions_text),
  934. "reward": rewards.tolist(),
  935. }
  936. df = pd.DataFrame(table)
  937. if wandb.run is not None and self.accelerator.is_main_process:
  938. wandb.log({"completions": wandb.Table(dataframe=df)})
  939. return {
  940. "prompt_ids": prompt_ids,
  941. "prompt_mask": prompt_mask,
  942. "completion_ids": completion_ids,
  943. "completion_mask": completion_mask,
  944. "ref_per_token_logps": ref_per_token_logps,
  945. "advantages": advantages,
  946. }
  947. def compute_loss(self, model, inputs, return_outputs = False, num_items_in_batch = None):
  948. if return_outputs:
  949. raise ValueError("The GRPOTrainer does not support returning outputs")
  950. # Compute the per-token log probabilities for the model
  951. prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
  952. completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
  953. input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
  954. bsz, qlen = input_ids.shape
  955. # attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
  956. attention_mask = None
  957. logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
  958. _input_ids = input_ids
  959. _logits_to_keep = logits_to_keep
  960. per_token_logps = self._get_per_token_logps(model, input_ids, attention_mask, logits_to_keep)
  961. # Compute the KL divergence between the model and the reference model
  962. ref_per_token_logps = inputs["ref_per_token_logps"]
  963. # per_token_kl = torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
  964. # x - x.detach() allows for preserving gradients from x
  965. advantages = inputs["advantages"]
  966. # per_token_loss = torch.exp(per_token_logps - per_token_logps.detach()) * advantages.unsqueeze(1)
  967. # per_token_loss = -(per_token_loss - self.beta * per_token_kl)
  968. # loss = ((per_token_loss * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()
  969. input_ids = input_ids[:, -logits_to_keep:]
  970. if False:#per_token_logps is not None:
  971. loss, completion_length, mean_kl = grpo_compute_loss(
  972. ref_per_token_logps, per_token_logps, input_ids, completion_mask, self.beta, advantages,
  973. )
  974. else:
  975. loss, completion_length, mean_kl = grpo_accumulated_loss(
  976. self, _input_ids, logits_to_keep, completion_mask, advantages,
  977. n_chunks = self.args.unsloth_num_chunks,
  978. )
  979. # Log the metrics
  980. # completion_length = self.accelerator.gather_for_metrics(completion_mask.sum(1)).float().mean().item()
  981. self._metrics["completion_length"].append(completion_length.item())
  982. # mean_kl = ((per_token_kl * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()
  983. # self._metrics["kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item())
  984. self._metrics["kl"].append(mean_kl.item())
  985. return loss
  986. def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: Optional[list[str]] = None):
  987. inputs = self._prepare_inputs(inputs)
  988. with torch.no_grad():
  989. with self.compute_loss_context_manager():
  990. loss = self.compute_loss(model, inputs)
  991. loss = loss.mean().detach()
  992. return loss, None, None
  993. def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None:
  994. metrics = {key: sum(val) / len(val) for key, val in self._metrics.items()} # average the metrics
  995. # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
  996. # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
  997. if next(iter(logs.keys())).startswith("eval_"):
  998. metrics = {f"eval_{key}": val for key, val in metrics.items()}
  999. logs = {**logs, **metrics}
  1000. if version.parse(transformers.__version__) >= version.parse("4.47.0.dev0"):
  1001. super().log(logs, start_time)
  1002. else: # transformers<=4.46
  1003. super().log(logs)
  1004. self._metrics.clear()
  1005. def create_model_card(
  1006. self,
  1007. model_name: Optional[str] = None,
  1008. dataset_name: Optional[str] = None,
  1009. tags: Union[str, list[str], None] = None,
  1010. ):
  1011. """
  1012. Creates a draft of a model card using the information available to the `Trainer`.
  1013. Args:
  1014. model_name (`str` or `None`, *optional*, defaults to `None`):
  1015. Name of the model.
  1016. dataset_name (`str` or `None`, *optional*, defaults to `None`):
  1017. Name of the dataset used for training.
  1018. tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`):
  1019. Tags to be associated with the model card.
  1020. """
  1021. if not self.is_world_process_zero():
  1022. return
  1023. if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path):
  1024. base_model = self.model.config._name_or_path
  1025. else:
  1026. base_model = None
  1027. tags = tags or []
  1028. if isinstance(tags, str):
  1029. tags = [tags]
  1030. if hasattr(self.model.config, "unsloth_version"):
  1031. tags.append("unsloth")
  1032. citation = textwrap.dedent(
  1033. """\
  1034. @article{zhihong2024deepseekmath,
  1035. title = {{DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models}},
  1036. author = {Zhihong Shao and Peiyi Wang and Qihao Zhu and Runxin Xu and Junxiao Song and Mingchuan Zhang and Y. K. Li and Y. Wu and Daya Guo},
  1037. year = 2024,
  1038. eprint = {arXiv:2402.03300},
  1039. }
  1040. """
  1041. )
  1042. model_card = generate_model_card(
  1043. base_model=base_model,
  1044. model_name=model_name,
  1045. hub_model_id=self.hub_model_id,
  1046. dataset_name=dataset_name,
  1047. tags=tags,
  1048. wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None,
  1049. comet_url=get_comet_experiment_url(),
  1050. trainer_name="GRPO",
  1051. trainer_citation=citation,
  1052. paper_title="DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models",
  1053. paper_id="2402.03300",
  1054. )
  1055. model_card.save(os.path.join(self.args.output_dir, "README.md"))
  1056. class UnslothGRPOTrainer(_UnslothGRPOTrainer):
  1057. """
  1058. Trainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the
  1059. paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300).
  1060. Example:
  1061. ```python
  1062. from datasets import load_dataset
  1063. from trl import GRPOTrainer
  1064. dataset = load_dataset("trl-lib/tldr", split="train")
  1065. def reward_func(completions, **kwargs):
  1066. # Dummy reward function that rewards completions with more unique letters.
  1067. return [float(len(set(completion))) for completion in completions]
  1068. trainer = GRPOTrainer(
  1069. model="Qwen/Qwen2-0.5B-Instruct",
  1070. reward_funcs=reward_func,
  1071. train_dataset=dataset,
  1072. )
  1073. trainer.train()
  1074. ```
  1075. Args:
  1076. model (`Union[str, PreTrainedModel]`):
  1077. Model to be trained. Can be either:
  1078. - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or
  1079. a path to a *directory* containing model weights saved using
  1080. [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is
  1081. loaded using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keywork arguments
  1082. in `args.model_init_kwargs`.
  1083. - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
  1084. reward_funcs (`Union[RewardFunc, list[RewardFunc]]`):
  1085. Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
  1086. functions with the prompts and completions and sum the rewards. Can be either:
  1087. - A single reward function, such as:
  1088. - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
  1089. path to a *directory* containing model weights saved using
  1090. [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
  1091. using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
  1092. keyword arguments in `args.model_init_kwargs`.
  1093. - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
  1094. - A custom reward function: The function is provided with the prompts and the generated completions,
  1095. plus any additional columns in the dataset. It should return a list of rewards. For more details, see
  1096. [Using a custom reward function](#using-a-custom-reward-function).
  1097. - A list of reward functions, where each item can independently be any of the above types. Mixing different
  1098. types within the list (e.g., a string model ID and a custom reward function) is allowed.
  1099. args ([`GRPOConfig`], *optional*, defaults to `None`):
  1100. Configuration for this trainer. If `None`, a default configuration is used.
  1101. train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
  1102. Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
  1103. ignored. The format of the samples can be either:
  1104. - [Standard](dataset_formats#standard): Each sample contains plain text.
  1105. - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
  1106. and content).
  1107. eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Union[Dataset, IterableDataset]]`):
  1108. Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
  1109. processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*, defaults to `None`):
  1110. Processing class used to process the data. The padding side must be set to "left". If `None`, the
  1111. processing class is loaded from the model's name with [`~transformers.AutoTokenizer.from_pretrained`].
  1112. reward_processing_classes (`Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]`, *optional*, defaults to `None`):
  1113. Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
  1114. - A single processing class: Used when `reward_funcs` contains only one reward function.
  1115. - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
  1116. If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
  1117. `None`, the tokenizer for the model is automatically loaded using [`~transformers.AutoTokenizer.from_pretrained`].
  1118. For elements in `reward_funcs` that are custom reward functions (not [`~transformers.PreTrainedModel`]),
  1119. the corresponding entries in `reward_processing_classes` are ignored.
  1120. callbacks (list of [`~transformers.TrainerCallback`], *optional*, defaults to `None`):
  1121. List of callbacks to customize the training loop. Will add those to the list of default callbacks
  1122. detailed in [here](https://huggingface.co/docs/transformers/main_classes/callback).
  1123. If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
  1124. method.
  1125. optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
  1126. A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your
  1127. model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`.
  1128. peft_config ([`~peft.PeftConfig`], *optional*, defaults to `None`):
  1129. PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
  1130. """
  1131. def __init__(
  1132. self,
  1133. model,
  1134. reward_funcs,
  1135. args = None,
  1136. train_dataset = None,
  1137. eval_dataset = None,
  1138. processing_class = None,
  1139. reward_processing_classes = None,
  1140. callbacks = None,
  1141. peft_config = None,
  1142. **kwargs
  1143. ):
  1144. if args is None: args = UnslothGRPOConfig()
  1145. use_bf16 = getattr(args, 'bf16', False)
  1146. use_fp16 = getattr(args, 'fp16', False)
  1147. dtype = getattr(model.config, 'torch_dtype', None)
  1148. if dtype is None: dtype = model.get_input_embeddings().dtype
  1149. from unsloth_zoo.utils import _get_dtype
  1150. dtype = _get_dtype(dtype)
  1151. float16 = dtype == torch.float16
  1152. if float16 and use_bf16: raise TypeError('Unsloth: Model is in float16 precision but you want to use bfloat16 precision. Set fp16 to `True` and bf16 to `False`')
  1153. if not float16 and use_fp16: raise TypeError('Unsloth: Model is in bfloat16 precision but you want to use float16 precision. Set fp16 to `False` and bf16 to `True`')
  1154. if not use_bf16 and not use_fp16:
  1155. args.fp16 = float16
  1156. args.bf16 = not float16
  1157. os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'
  1158. if getattr(args, 'eval_dataset', None) is not None and getattr(args, 'eval_strategy', 'no') == 'no':
  1159. args.eval_strategy = 'steps'
  1160. if getattr(args, 'eval_steps', None) is None: args.eval_steps = 0.1
  1161. ga_steps = getattr(args, 'gradient_accumulation_steps', None)
  1162. if ga_steps is not None and ga_steps > 1:
  1163. from transformers import __version__ as transformers_version
  1164. if Version(transformers_version) <= Version('4.45.2'):
  1165. print('**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!\n'
  1166. '`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`')
  1167. if getattr(args, 'eval_strategy', 'no') != 'no':
  1168. eval_bsz = getattr(args, 'per_device_eval_batch_size', 8)
  1169. if eval_bsz == 8 and args.per_device_train_batch_size < eval_bsz: args.per_device_eval_batch_size = args.per_device_train_batch_size
  1170. if getattr(args, 'eval_accumulation_steps', None) is None and ga_steps is not None: args.eval_accumulation_steps = ga_steps
  1171. fp16_full_eval = getattr(args, 'fp16_full_eval', False)
  1172. bf16_full_eval = getattr(args, 'bf16_full_eval', False)
  1173. if args.fp16 and bf16_full_eval: args.bf16_full_eval = False; args.fp16_full_eval = True
  1174. if args.bf16 and fp16_full_eval: args.bf16_full_eval = True; args.fp16_full_eval = False
  1175. if not bf16_full_eval and not fp16_full_eval: args.bf16_full_eval = args.bf16; args.fp16_full_eval = args.fp16
  1176. if 'max_seq_length' not in locals() and not hasattr(args, 'max_seq_length'):
  1177. pass
  1178. else:
  1179. model_max_seq_length = getattr(model, 'max_seq_length', None)
  1180. args_max_seq_length = getattr(args, 'max_seq_length', None)
  1181. if args_max_seq_length is None and model_max_seq_length is not None:
  1182. max_seq_length = model.max_seq_length
  1183. if hasattr(args, 'max_seq_length'): args.max_seq_length = max_seq_length
  1184. if model is not None and hasattr(model, 'for_training'):
  1185. model.for_training()
  1186. if 'tokenizer' in locals() and hasattr(tokenizer, 'padding_side'): tokenizer.padding_side = 'right'
  1187. if 'processing_class' in locals():
  1188. if hasattr(processing_class, 'padding_side'): processing_class.padding_side = 'right'
  1189. if hasattr(processing_class, 'tokenizer') and hasattr(processing_class.tokenizer, 'padding_side'): processing_class.tokenizer.padding_side = 'right'
  1190. other_metrics = []
  1191. if not isinstance(reward_funcs, list): _reward_funcs = [reward_funcs]
  1192. else: _reward_funcs = reward_funcs
  1193. for reward_func in _reward_funcs:
  1194. try:
  1195. reward_func_name = reward_func.__name__
  1196. other_metrics.append(f'rewards/{reward_func_name}')
  1197. except: pass
  1198. from unsloth_zoo.logging_utils import PatchRLStatistics
  1199. PatchRLStatistics('grpo_trainer', other_metrics)
  1200. super().__init__(
  1201. model = model,
  1202. reward_funcs = reward_funcs,
  1203. args = args,
  1204. train_dataset = train_dataset,
  1205. eval_dataset = eval_dataset,
  1206. processing_class = processing_class,
  1207. reward_processing_classes = reward_processing_classes,
  1208. callbacks = callbacks,
  1209. peft_config = peft_config,**kwargs)
  1210. if hasattr(self, 'neftune_hook_handle'):
  1211. self.neftune_hook_handle.remove()
  1212. if hasattr(self, 'neftune_hook_handle'): del self.neftune_hook_handle
  1213. if getattr(args, 'neftune_noise_alpha', None) is not None:
  1214. model.get_input_embeddings().neftune_noise_alpha = self.neftune_noise_alpha
  1215. pass
  1216. pass