UnslothNashMDTrainer.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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.nash_md_trainer import (Any, BaseImageProcessor, BasePairwiseJudge, Callable, Dataset, EvalPrediction, F, FeatureExtractionMixin, GeometricMixtureWrapper, IterableDataset, NashMDConfig, NashMDTrainer, OnlineDPOTrainer, OptimizerNames, Optional, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, SIMPLE_CHAT_TEMPLATE, TrainerCallback, Union, empty_cache, generate_model_card, get_comet_experiment_url, get_reward, is_conversational, is_wandb_available, jinja2, maybe_apply_chat_template, nn, os, textwrap, torch, truncate_right, unwrap_model_for_generation)
  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. @dataclass
  31. class UnslothNashMDConfig(NashMDConfig):
  32. """
  33. Configuration class for the [`NashMDTrainer`].
  34. Subclass of [`OnlineDPOConfig`] we can use all its arguments and add the following:
  35. Parameters:
  36. mixture_coef (`float` or `list[float]`, *optional*, defaults to `0.5`):
  37. Logit mixture coefficient for the model and reference model. If a list of floats is provided then the
  38. mixture coefficient is selected for each new epoch and the last coefficient is used for the rest of the
  39. epochs.
  40. """
  41. vllm_sampling_params: Optional[Any] = field(
  42. default = None,
  43. metadata = {'help': 'vLLM SamplingParams'},
  44. )
  45. unsloth_num_chunks : Optional[int] = field(
  46. default = -1,
  47. metadata = {'help': 'Chunk size to reduce memory usage. -1 is most efficient.'},
  48. )
  49. def __init__(
  50. self,
  51. output_dir = None,
  52. overwrite_output_dir = None,
  53. do_train = False,
  54. do_eval = False,
  55. do_predict = False,
  56. eval_strategy = 'no',
  57. prediction_loss_only = False,
  58. per_device_train_batch_size = 4,
  59. per_device_eval_batch_size = 4,
  60. per_gpu_train_batch_size = None,
  61. per_gpu_eval_batch_size = None,
  62. gradient_accumulation_steps = 2,
  63. eval_accumulation_steps = 2,
  64. eval_delay = 0,
  65. torch_empty_cache_steps = 250,
  66. learning_rate = 5e-05,
  67. weight_decay = 0.01,
  68. adam_beta1 = 0.9,
  69. adam_beta2 = 0.999,
  70. adam_epsilon = 1e-08,
  71. max_grad_norm = 1.0,
  72. num_train_epochs = 3.0,
  73. max_steps = -1,
  74. lr_scheduler_type = 'linear',
  75. warmup_ratio = 0.1,
  76. warmup_steps = 0,
  77. log_level = 'passive',
  78. log_level_replica = 'warning',
  79. log_on_each_node = True,
  80. logging_dir = None,
  81. logging_strategy = 'steps',
  82. logging_first_step = False,
  83. logging_steps = 1,
  84. logging_nan_inf_filter = False,
  85. save_strategy = 'steps',
  86. save_steps = 500,
  87. save_total_limit = None,
  88. save_safetensors = True,
  89. save_on_each_node = False,
  90. save_only_model = False,
  91. restore_callback_states_from_checkpoint = False,
  92. no_cuda = False,
  93. use_cpu = False,
  94. use_mps_device = False,
  95. seed = 3407,
  96. data_seed = 3407,
  97. jit_mode_eval = False,
  98. use_ipex = False,
  99. bf16 = False,
  100. fp16 = False,
  101. fp16_opt_level = 'O1',
  102. half_precision_backend = 'auto',
  103. bf16_full_eval = False,
  104. fp16_full_eval = False,
  105. tf32 = None,
  106. local_rank = -1,
  107. ddp_backend = None,
  108. tpu_num_cores = None,
  109. tpu_metrics_debug = False,
  110. debug = '',
  111. dataloader_drop_last = False,
  112. eval_steps = None,
  113. dataloader_num_workers = 0,
  114. dataloader_prefetch_factor = None,
  115. past_index = -1,
  116. run_name = None,
  117. disable_tqdm = None,
  118. remove_unused_columns = True,
  119. label_names = None,
  120. load_best_model_at_end = False,
  121. metric_for_best_model = None,
  122. greater_is_better = None,
  123. ignore_data_skip = False,
  124. fsdp = '',
  125. fsdp_min_num_params = 0,
  126. fsdp_config = None,
  127. fsdp_transformer_layer_cls_to_wrap = None,
  128. accelerator_config = None,
  129. deepspeed = None,
  130. label_smoothing_factor = 0.0,
  131. optim = 'adamw_8bit',
  132. optim_args = None,
  133. adafactor = False,
  134. group_by_length = False,
  135. length_column_name = 'length',
  136. report_to = None,
  137. ddp_find_unused_parameters = None,
  138. ddp_bucket_cap_mb = None,
  139. ddp_broadcast_buffers = None,
  140. dataloader_pin_memory = True,
  141. dataloader_persistent_workers = False,
  142. skip_memory_metrics = True,
  143. use_legacy_prediction_loop = False,
  144. push_to_hub = False,
  145. resume_from_checkpoint = None,
  146. hub_model_id = None,
  147. hub_strategy = 'every_save',
  148. hub_token = None,
  149. hub_private_repo = None,
  150. hub_always_push = False,
  151. gradient_checkpointing = False,
  152. gradient_checkpointing_kwargs = None,
  153. include_inputs_for_metrics = False,
  154. eval_do_concat_batches = True,
  155. fp16_backend = 'auto',
  156. evaluation_strategy = None,
  157. push_to_hub_model_id = None,
  158. push_to_hub_organization = None,
  159. push_to_hub_token = None,
  160. mp_parameters = '',
  161. auto_find_batch_size = False,
  162. full_determinism = False,
  163. torchdynamo = None,
  164. ray_scope = 'last',
  165. ddp_timeout = 1800,
  166. torch_compile = False,
  167. torch_compile_backend = None,
  168. torch_compile_mode = None,
  169. dispatch_batches = None,
  170. split_batches = None,
  171. include_tokens_per_second = False,
  172. include_num_input_tokens_seen = False,
  173. neftune_noise_alpha = None,
  174. optim_target_modules = None,
  175. batch_eval_metrics = False,
  176. eval_on_start = False,
  177. use_liger_kernel = False,
  178. eval_use_gather_object = False,
  179. average_tokens_across_devices = False,
  180. reward_model_path = None,
  181. judge = None,
  182. max_new_tokens = 64,
  183. max_length = 512,
  184. temperature = 0.9,
  185. missing_eos_penalty = None,
  186. loss_type = 'sigmoid',
  187. dataset_num_proc = None,
  188. disable_dropout = True,
  189. use_vllm = False,
  190. ds3_gather_for_generation = True,
  191. vllm_sampling_params = None,
  192. unsloth_num_chunks = -1,
  193. **kwargs,
  194. ):
  195. 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!')
  196. 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!')
  197. if output_dir is None and save_strategy == 'steps' and save_steps == 500:
  198. output_dir = 'unsloth_training_checkpoints'
  199. save_strategy = 'no'
  200. if dataset_num_proc is None:
  201. from multiprocessing import cpu_count
  202. dataset_num_proc = cpu_count()
  203. super().__init__(
  204. output_dir = output_dir,
  205. overwrite_output_dir = overwrite_output_dir,
  206. do_train = do_train,
  207. do_eval = do_eval,
  208. do_predict = do_predict,
  209. eval_strategy = eval_strategy,
  210. prediction_loss_only = prediction_loss_only,
  211. per_device_train_batch_size = per_device_train_batch_size,
  212. per_device_eval_batch_size = per_device_eval_batch_size,
  213. per_gpu_train_batch_size = per_gpu_train_batch_size,
  214. per_gpu_eval_batch_size = per_gpu_eval_batch_size,
  215. gradient_accumulation_steps = gradient_accumulation_steps,
  216. eval_accumulation_steps = eval_accumulation_steps,
  217. eval_delay = eval_delay,
  218. torch_empty_cache_steps = torch_empty_cache_steps,
  219. learning_rate = learning_rate,
  220. weight_decay = weight_decay,
  221. adam_beta1 = adam_beta1,
  222. adam_beta2 = adam_beta2,
  223. adam_epsilon = adam_epsilon,
  224. max_grad_norm = max_grad_norm,
  225. num_train_epochs = num_train_epochs,
  226. max_steps = max_steps,
  227. lr_scheduler_type = lr_scheduler_type,
  228. warmup_ratio = warmup_ratio,
  229. warmup_steps = warmup_steps,
  230. log_level = log_level,
  231. log_level_replica = log_level_replica,
  232. log_on_each_node = log_on_each_node,
  233. logging_dir = logging_dir,
  234. logging_strategy = logging_strategy,
  235. logging_first_step = logging_first_step,
  236. logging_steps = logging_steps,
  237. logging_nan_inf_filter = logging_nan_inf_filter,
  238. save_strategy = save_strategy,
  239. save_steps = save_steps,
  240. save_total_limit = save_total_limit,
  241. save_safetensors = save_safetensors,
  242. save_on_each_node = save_on_each_node,
  243. save_only_model = save_only_model,
  244. restore_callback_states_from_checkpoint = restore_callback_states_from_checkpoint,
  245. no_cuda = no_cuda,
  246. use_cpu = use_cpu,
  247. use_mps_device = use_mps_device,
  248. seed = seed,
  249. data_seed = data_seed,
  250. jit_mode_eval = jit_mode_eval,
  251. use_ipex = use_ipex,
  252. bf16 = bf16,
  253. fp16 = fp16,
  254. fp16_opt_level = fp16_opt_level,
  255. half_precision_backend = half_precision_backend,
  256. bf16_full_eval = bf16_full_eval,
  257. fp16_full_eval = fp16_full_eval,
  258. tf32 = tf32,
  259. local_rank = local_rank,
  260. ddp_backend = ddp_backend,
  261. tpu_num_cores = tpu_num_cores,
  262. tpu_metrics_debug = tpu_metrics_debug,
  263. debug = debug,
  264. dataloader_drop_last = dataloader_drop_last,
  265. eval_steps = eval_steps,
  266. dataloader_num_workers = dataloader_num_workers,
  267. dataloader_prefetch_factor = dataloader_prefetch_factor,
  268. past_index = past_index,
  269. run_name = run_name,
  270. disable_tqdm = disable_tqdm,
  271. remove_unused_columns = remove_unused_columns,
  272. label_names = label_names,
  273. load_best_model_at_end = load_best_model_at_end,
  274. metric_for_best_model = metric_for_best_model,
  275. greater_is_better = greater_is_better,
  276. ignore_data_skip = ignore_data_skip,
  277. fsdp = fsdp,
  278. fsdp_min_num_params = fsdp_min_num_params,
  279. fsdp_config = fsdp_config,
  280. fsdp_transformer_layer_cls_to_wrap = fsdp_transformer_layer_cls_to_wrap,
  281. accelerator_config = accelerator_config,
  282. deepspeed = deepspeed,
  283. label_smoothing_factor = label_smoothing_factor,
  284. optim = optim,
  285. optim_args = optim_args,
  286. adafactor = adafactor,
  287. group_by_length = group_by_length,
  288. length_column_name = length_column_name,
  289. report_to = report_to,
  290. ddp_find_unused_parameters = ddp_find_unused_parameters,
  291. ddp_bucket_cap_mb = ddp_bucket_cap_mb,
  292. ddp_broadcast_buffers = ddp_broadcast_buffers,
  293. dataloader_pin_memory = dataloader_pin_memory,
  294. dataloader_persistent_workers = dataloader_persistent_workers,
  295. skip_memory_metrics = skip_memory_metrics,
  296. use_legacy_prediction_loop = use_legacy_prediction_loop,
  297. push_to_hub = push_to_hub,
  298. resume_from_checkpoint = resume_from_checkpoint,
  299. hub_model_id = hub_model_id,
  300. hub_strategy = hub_strategy,
  301. hub_token = hub_token,
  302. hub_private_repo = hub_private_repo,
  303. hub_always_push = hub_always_push,
  304. gradient_checkpointing = gradient_checkpointing,
  305. gradient_checkpointing_kwargs = gradient_checkpointing_kwargs,
  306. include_inputs_for_metrics = include_inputs_for_metrics,
  307. eval_do_concat_batches = eval_do_concat_batches,
  308. fp16_backend = fp16_backend,
  309. evaluation_strategy = evaluation_strategy,
  310. push_to_hub_model_id = push_to_hub_model_id,
  311. push_to_hub_organization = push_to_hub_organization,
  312. push_to_hub_token = push_to_hub_token,
  313. mp_parameters = mp_parameters,
  314. auto_find_batch_size = auto_find_batch_size,
  315. full_determinism = full_determinism,
  316. torchdynamo = torchdynamo,
  317. ray_scope = ray_scope,
  318. ddp_timeout = ddp_timeout,
  319. torch_compile = torch_compile,
  320. torch_compile_backend = torch_compile_backend,
  321. torch_compile_mode = torch_compile_mode,
  322. dispatch_batches = dispatch_batches,
  323. split_batches = split_batches,
  324. include_tokens_per_second = include_tokens_per_second,
  325. include_num_input_tokens_seen = include_num_input_tokens_seen,
  326. neftune_noise_alpha = neftune_noise_alpha,
  327. optim_target_modules = optim_target_modules,
  328. batch_eval_metrics = batch_eval_metrics,
  329. eval_on_start = eval_on_start,
  330. use_liger_kernel = use_liger_kernel,
  331. eval_use_gather_object = eval_use_gather_object,
  332. average_tokens_across_devices = average_tokens_across_devices,
  333. reward_model_path = reward_model_path,
  334. judge = judge,
  335. max_new_tokens = max_new_tokens,
  336. max_length = max_length,
  337. temperature = temperature,
  338. missing_eos_penalty = missing_eos_penalty,
  339. loss_type = loss_type,
  340. dataset_num_proc = dataset_num_proc,
  341. disable_dropout = disable_dropout,
  342. use_vllm = use_vllm,
  343. ds3_gather_for_generation = ds3_gather_for_generation,**kwargs)
  344. self.vllm_sampling_params = vllm_sampling_params
  345. self.unsloth_num_chunks = unsloth_num_chunks
  346. pass
  347. class _UnslothNashMDTrainer(OnlineDPOTrainer):
  348. r""""""
  349. _tag_names = ["trl", "nash-md"]
  350. def __init__(
  351. self,
  352. model: Union[PreTrainedModel, nn.Module] = None,
  353. ref_model: Union[PreTrainedModel, nn.Module] = None,
  354. reward_model: Union[PreTrainedModel, nn.Module, None] = None,
  355. judge: Optional[BasePairwiseJudge] = None,
  356. args: Optional[NashMDConfig] = None,
  357. data_collator: Optional[Callable] = None,
  358. train_dataset: Optional[Union[Dataset, IterableDataset]] = None,
  359. eval_dataset: Optional[Union[Dataset, dict[str, Dataset]]] = None,
  360. processing_class: Optional[
  361. Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin]
  362. ] = None,
  363. peft_config: Optional[dict] = None,
  364. compute_metrics: Optional[Callable[[EvalPrediction], dict]] = None,
  365. callbacks: Optional[list[TrainerCallback]] = None,
  366. optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
  367. preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
  368. ) -> None:
  369. super().__init__(
  370. model=model,
  371. ref_model=ref_model,
  372. reward_model=reward_model,
  373. judge=judge,
  374. args=args,
  375. data_collator=data_collator,
  376. train_dataset=train_dataset,
  377. eval_dataset=eval_dataset,
  378. processing_class=processing_class,
  379. reward_processing_class=processing_class, # for now, NashMDTrainer can't use any reward model
  380. peft_config=peft_config,
  381. compute_metrics=compute_metrics,
  382. callbacks=callbacks,
  383. optimizers=optimizers,
  384. preprocess_logits_for_metrics=preprocess_logits_for_metrics,
  385. )
  386. self._mixture_coef = self.args.mixture_coef
  387. # Overwrite the stats dictionary to include NashMD specific statistics
  388. self.stats = {
  389. # Remove "non_score_reward", "rlhf_reward", "scores_margin"
  390. # Add "mixture_coef"
  391. "loss/kl": [],
  392. "objective/entropy": [],
  393. "loss/score": [],
  394. "rewards/probabilities": [],
  395. "rewards/accuracies": [],
  396. "rewards/margins": [],
  397. "logps/chosen": [],
  398. "logps/rejected": [],
  399. "val/model_contain_eos_token": [],
  400. "val/ref_contain_eos_token": [],
  401. "beta": [],
  402. "mixture_coef": [],
  403. }
  404. if self.reward_model is not None:
  405. self.stats["rewards/chosen"] = []
  406. self.stats["rewards/rejected"] = []
  407. @property
  408. def mixture_coef(self):
  409. if isinstance(self._mixture_coef, list):
  410. epoch = self.state.epoch
  411. return self._mixture_coef[epoch] if epoch < len(self._mixture_coef) else self._mixture_coef[-1]
  412. else:
  413. return self._mixture_coef
  414. def _generate_completions(self, model, prompts):
  415. with unwrap_model_for_generation(model, self.accelerator) as unwrapped_model:
  416. model_output = unwrapped_model.generate(
  417. input_ids=prompts["input_ids"],
  418. attention_mask=prompts["attention_mask"],
  419. generation_config=self.generation_config,
  420. )
  421. ref_model = model if self.ref_model is None else self.ref_model
  422. with torch.no_grad(), unwrap_model_for_generation(ref_model, self.accelerator) as unwrapped_ref_model:
  423. mixture_model = GeometricMixtureWrapper(
  424. model=unwrapped_model,
  425. ref_model=unwrapped_ref_model,
  426. generation_config=self.generation_config,
  427. mixture_coef=self.mixture_coef,
  428. device=self.accelerator.device,
  429. )
  430. mixture_output = mixture_model.generate(
  431. input_ids=prompts["input_ids"],
  432. attention_mask=prompts["attention_mask"],
  433. generation_config=self.generation_config,
  434. )
  435. return model_output, mixture_output
  436. def _process_completions(self, model_output, mixture_output, prompts):
  437. context_length = prompts["input_ids"].shape[1]
  438. # Process model completions
  439. model_completion_ids = model_output[:, context_length:]
  440. model_completion_ids, model_completion_mask = truncate_right(
  441. model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
  442. )
  443. model_data = {
  444. "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1),
  445. "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1),
  446. "raw": prompts["raw"],
  447. }
  448. # Process reference model completions
  449. mixture_completion_ids = mixture_output[:, context_length:]
  450. mixture_completion_ids, mixture_completion_mask = truncate_right(
  451. mixture_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
  452. )
  453. mixture_data = {
  454. "input_ids": torch.cat((prompts["input_ids"], mixture_completion_ids), dim=1),
  455. "attention_mask": torch.cat((prompts["attention_mask"], mixture_completion_mask), dim=1),
  456. "raw": prompts["raw"],
  457. }
  458. return model_data, mixture_data
  459. def _compute_rewards(self, model_data, mixture_data, context_length):
  460. with torch.no_grad():
  461. _, model_scores, _ = get_reward(
  462. self.reward_model, model_data["input_ids"], self.processing_class.pad_token_id, context_length
  463. )
  464. _, mixture_scores, _ = get_reward(
  465. self.reward_model, mixture_data["input_ids"], self.processing_class.pad_token_id, context_length
  466. )
  467. # Apply EOS penalty if needed
  468. if self.args.missing_eos_penalty is not None:
  469. model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
  470. mixture_contain_eos = torch.any(mixture_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
  471. model_scores[~model_contain_eos] -= self.args.missing_eos_penalty
  472. mixture_scores[~mixture_contain_eos] -= self.args.missing_eos_penalty
  473. return model_scores, mixture_scores
  474. def _compute_judge(self, model_data, mixture_data, context_length):
  475. prompts = model_data["raw"]
  476. model_data_completions = self.processing_class.batch_decode(
  477. model_data["input_ids"][:, context_length:], skip_special_tokens=True
  478. )
  479. model_data_completions = [completion.strip() for completion in model_data_completions]
  480. mixture_data_completions = self.processing_class.batch_decode(
  481. mixture_data["input_ids"][:, context_length:], skip_special_tokens=True
  482. )
  483. mixture_data_completions = [completion.strip() for completion in mixture_data_completions]
  484. if is_conversational({"prompt": prompts[0]}):
  485. model_data_completions = [
  486. [{"role": "assistant", "content": completion}] for completion in model_data_completions
  487. ]
  488. environment = jinja2.Environment()
  489. template = environment.from_string(SIMPLE_CHAT_TEMPLATE)
  490. prompts = [template.render(messages=message) for message in prompts]
  491. model_data_completions = [template.render(messages=completion) for completion in model_data_completions]
  492. mixture_data_completions = [
  493. [{"role": "assistant", "content": completion}] for completion in mixture_data_completions
  494. ]
  495. mixture_data_completions = [
  496. template.render(messages=completion) for completion in mixture_data_completions
  497. ]
  498. probability = self.judge.judge(
  499. prompts,
  500. list(zip(model_data_completions, mixture_data_completions)),
  501. return_scores=True,
  502. )
  503. return torch.tensor(probability, device=model_data["input_ids"].device)
  504. def _compute_logprobs(self, model, model_data, context_length):
  505. def compute_logprobs_for_data(m, data):
  506. output = m(data["input_ids"], attention_mask=data["attention_mask"])
  507. logits = output.logits[:, context_length - 1 : -1]
  508. token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:])
  509. return token_logprobs
  510. # Compute logprobs for model completions under the model
  511. model_logprobs_model_data = compute_logprobs_for_data(model, model_data)
  512. # Compute logprobs of model completions under the reference model
  513. with torch.no_grad():
  514. if self.ref_model is None:
  515. with model.disable_adapter():
  516. ref_logprobs_model_data = compute_logprobs_for_data(model, model_data)
  517. else:
  518. ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data)
  519. # Mask padding tokens
  520. model_padding_mask = model_data["attention_mask"][:, context_length:] == 0
  521. model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
  522. ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
  523. return (model_logprobs_model_data, ref_logprobs_model_data)
  524. def _compute_losses(
  525. self,
  526. model_logprobs_model_data,
  527. ref_logprobs_model_data,
  528. probability,
  529. ):
  530. # reinforce score where 0.5 is a control variate
  531. score = (probability - 0.5) * model_logprobs_model_data.sum(1)
  532. # kl divergence via reinforce
  533. with torch.no_grad():
  534. log_ratio = model_logprobs_model_data - ref_logprobs_model_data
  535. kl_div_log = log_ratio.sum(1)
  536. kl_div_loss = (log_ratio * model_logprobs_model_data).sum(1)
  537. # final loss
  538. loss = self.beta * kl_div_loss - score
  539. return loss.mean(), score, kl_div_log
  540. def _log_statistics(
  541. self,
  542. model_data,
  543. mixture_data,
  544. model_logprobs_model_data,
  545. ref_logprobs_model_data,
  546. probability,
  547. score,
  548. kl_div,
  549. context_length,
  550. model_scores=None,
  551. mixture_scores=None,
  552. ):
  553. # Helper function to gather and compute mean
  554. def gather_mean(tensor):
  555. return self.accelerator.gather_for_metrics(tensor).mean().item()
  556. # Log score
  557. self.stats["loss/score"].append(gather_mean(score))
  558. # Log KL divergence
  559. self.stats["loss/kl"].append(gather_mean(kl_div))
  560. # Log logprobs
  561. model_logprobs_model_data_sum = model_logprobs_model_data.sum(1)
  562. ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1)
  563. self.stats["logps/chosen"].append(gather_mean(model_logprobs_model_data_sum))
  564. self.stats["logps/rejected"].append(gather_mean(ref_logprobs_model_data_sum))
  565. # Log rewards
  566. if self.reward_model is not None:
  567. self.stats["rewards/chosen"].append(gather_mean(model_scores))
  568. self.stats["rewards/rejected"].append(gather_mean(mixture_scores))
  569. # Log probabilities
  570. self.stats["rewards/probabilities"].append(gather_mean(probability))
  571. # Calculate entropy for model data
  572. entropy_model_data = -model_logprobs_model_data.sum(1)
  573. self.stats["objective/entropy"].append(gather_mean(entropy_model_data))
  574. # Calculate margins
  575. margin = model_logprobs_model_data_sum - ref_logprobs_model_data_sum
  576. self.stats["rewards/margins"].append(gather_mean(margin))
  577. # Calculate accuracy
  578. accuracy = (margin > 0).float()
  579. self.stats["rewards/accuracies"].append(gather_mean(accuracy))
  580. # Log EOS token statistics
  581. model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
  582. mixture_eos = (mixture_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
  583. self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float()))
  584. self.stats["val/ref_contain_eos_token"].append(gather_mean(mixture_eos.float()))
  585. # Log beta and mixture coef
  586. self.stats["beta"].append(self.beta)
  587. self.stats["mixture_coef"].append(self.mixture_coef)
  588. def training_step(
  589. self, model: nn.Module, inputs: dict[str, Union[torch.Tensor, Any]], num_items_in_batch: Optional[int] = None
  590. ) -> torch.Tensor:
  591. model.train()
  592. # Apply chat template and tokenize the input
  593. batch_size = len(next(iter(inputs.values())))
  594. prompts = inputs["prompt"]
  595. inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)]
  596. inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs]
  597. inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs]
  598. inputs = self.data_collator(inputs)
  599. # need the prompt_ only
  600. inputs = self._prepare_inputs(inputs)
  601. context_length = inputs["prompt_input_ids"].shape[1]
  602. prompts = {
  603. "input_ids": inputs["prompt_input_ids"],
  604. "attention_mask": inputs["prompt_attention_mask"],
  605. "raw": prompts,
  606. }
  607. del inputs
  608. # Sample completions from both the model and the reference model
  609. model_output, mixture_output = self._generate_completions(model, prompts)
  610. # Process model completions
  611. model_data, mixture_data = self._process_completions(model_output, mixture_output, prompts)
  612. # Compute rewards
  613. if self.reward_model is not None:
  614. model_scores, mixture_scores = self._compute_rewards(model_data, mixture_data, context_length)
  615. # probability of the model data vs the mixture data
  616. probability = F.sigmoid(model_scores - mixture_scores)
  617. else:
  618. model_scores, mixture_scores = None, None
  619. probability = self._compute_judge(model_data, mixture_data, context_length)
  620. # Compute logprobs
  621. model_logprobs_model_data, ref_logprobs_model_data = self._compute_logprobs(model, model_data, context_length)
  622. # Compute loss
  623. loss, score, kl_div = self._compute_losses(model_logprobs_model_data, ref_logprobs_model_data, probability)
  624. # Log everything
  625. self._log_statistics(
  626. model_data,
  627. mixture_data,
  628. model_logprobs_model_data.detach(),
  629. ref_logprobs_model_data,
  630. probability,
  631. score.detach(),
  632. kl_div.detach(),
  633. context_length,
  634. model_scores,
  635. mixture_scores,
  636. )
  637. if (
  638. self.args.torch_empty_cache_steps is not None
  639. and self.state.global_step % self.args.torch_empty_cache_steps == 0
  640. ):
  641. empty_cache()
  642. kwargs = {}
  643. # For LOMO optimizers you need to explicitly use the learning rate
  644. if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]:
  645. kwargs["learning_rate"] = self._get_learning_rate()
  646. if self.args.n_gpu > 1:
  647. loss = loss.mean() # mean() to average on multi-gpu parallel training
  648. if self.use_apex:
  649. with amp.scale_loss(loss, self.optimizer) as scaled_loss:
  650. scaled_loss.backward()
  651. else:
  652. self.accelerator.backward(loss, **kwargs)
  653. return loss.detach() / self.args.gradient_accumulation_steps
  654. def create_model_card(
  655. self,
  656. model_name: Optional[str] = None,
  657. dataset_name: Optional[str] = None,
  658. tags: Union[str, list[str], None] = None,
  659. ):
  660. """
  661. Creates a draft of a model card using the information available to the `Trainer`.
  662. Args:
  663. model_name (`str` or `None`, *optional*, defaults to `None`):
  664. Name of the model.
  665. dataset_name (`str` or `None`, *optional*, defaults to `None`):
  666. Name of the dataset used for training.
  667. tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`):
  668. Tags to be associated with the model card.
  669. """
  670. if not self.is_world_process_zero():
  671. return
  672. if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path):
  673. base_model = self.model.config._name_or_path
  674. else:
  675. base_model = None
  676. tags = tags or []
  677. if isinstance(tags, str):
  678. tags = [tags]
  679. if hasattr(self.model.config, "unsloth_version"):
  680. tags.append("unsloth")
  681. citation = textwrap.dedent("""\
  682. @inproceedings{munos2024nash,
  683. title = {{Nash Learning from Human Feedback}},
  684. author = {R{\'{e}}mi Munos and Michal Valko and Daniele Calandriello and Mohammad Gheshlaghi Azar and Mark Rowland and Zhaohan Daniel Guo and Yunhao Tang and Matthieu Geist and Thomas Mesnard and C{\\^{o}}me Fiegel and Andrea Michi and Marco Selvi and Sertan Girgin and Nikola Momchev and Olivier Bachem and Daniel J. Mankowitz and Doina Precup and Bilal Piot},
  685. year = 2024,
  686. booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024},
  687. publisher = {OpenReview.net},
  688. url = {https://openreview.net/forum?id=Y5AmNYiyCQ}
  689. }""")
  690. model_card = generate_model_card(
  691. base_model=base_model,
  692. model_name=model_name,
  693. hub_model_id=self.hub_model_id,
  694. dataset_name=dataset_name,
  695. tags=tags,
  696. wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None,
  697. comet_url=get_comet_experiment_url(),
  698. trainer_name="Nash-MD",
  699. trainer_citation=citation,
  700. paper_title="Nash Learning from Human Feedback",
  701. paper_id="2312.00886",
  702. )
  703. model_card.save(os.path.join(self.args.output_dir, "README.md"))
  704. class UnslothNashMDTrainer(_UnslothNashMDTrainer):
  705. """
  706. Initialize NashMDTrainer as a subclass of [`OnlineDPOConfig`].
  707. Args:
  708. model (`transformers.PreTrainedModel`):
  709. The model to train, preferably an `AutoModelForCausalLM`.
  710. ref_model (`PreTrainedModelWrapper`):
  711. Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no
  712. reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized.
  713. reward_model (`transformers.PreTrainedModel`):
  714. The reward model to score completions with, preferably an `AutoModelForSequenceClassification`.
  715. judge (`BasePairwiseJudge`):
  716. The judge to use for pairwise comparison of model completions.
  717. args (`NashMDConfig`):
  718. The NashMD config arguments to use for training.
  719. data_collator (`transformers.DataCollator`):
  720. The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used
  721. which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
  722. train_dataset (`datasets.Dataset`):
  723. The dataset to use for training.
  724. eval_dataset (`datasets.Dataset`):
  725. The dataset to use for evaluation.
  726. processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*):
  727. Processing class used to process the data. If provided, will be used to automatically process the inputs
  728. for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
  729. reuse the fine-tuned model.
  730. peft_config (`dict`):
  731. The peft config to use for training.
  732. compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
  733. The function to use to compute the metrics. Must take a `EvalPrediction` and return
  734. a dictionary string to metric values.
  735. callbacks (`list[transformers.TrainerCallback]`):
  736. The callbacks to use for training.
  737. optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
  738. The optimizer and scheduler to use for training.
  739. preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
  740. The function to use to preprocess the logits before computing the metrics.
  741. """
  742. def __init__(
  743. self,
  744. model = None,
  745. ref_model = None,
  746. reward_model = None,
  747. judge = None,
  748. args = None,
  749. data_collator = None,
  750. train_dataset = None,
  751. eval_dataset = None,
  752. processing_class = None,
  753. peft_config = None,
  754. compute_metrics = None,
  755. callbacks = None,
  756. preprocess_logits_for_metrics = None,
  757. **kwargs
  758. ):
  759. if args is None: args = UnslothNashMDConfig()
  760. use_bf16 = getattr(args, 'bf16', False)
  761. use_fp16 = getattr(args, 'fp16', False)
  762. dtype = getattr(model.config, 'torch_dtype', None)
  763. if dtype is None: dtype = model.get_input_embeddings().dtype
  764. from unsloth_zoo.utils import _get_dtype
  765. dtype = _get_dtype(dtype)
  766. float16 = dtype == torch.float16
  767. 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`')
  768. 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`')
  769. if not use_bf16 and not use_fp16:
  770. args.fp16 = float16
  771. args.bf16 = not float16
  772. os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'
  773. if getattr(args, 'eval_dataset', None) is not None and getattr(args, 'eval_strategy', 'no') == 'no':
  774. args.eval_strategy = 'steps'
  775. if getattr(args, 'eval_steps', None) is None: args.eval_steps = 0.1
  776. ga_steps = getattr(args, 'gradient_accumulation_steps', None)
  777. if ga_steps is not None and ga_steps > 1:
  778. from transformers import __version__ as transformers_version
  779. if Version(transformers_version) <= Version('4.45.2'):
  780. print('**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!\n'
  781. '`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`')
  782. if getattr(args, 'eval_strategy', 'no') != 'no':
  783. eval_bsz = getattr(args, 'per_device_eval_batch_size', 8)
  784. 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
  785. if getattr(args, 'eval_accumulation_steps', None) is None and ga_steps is not None: args.eval_accumulation_steps = ga_steps
  786. fp16_full_eval = getattr(args, 'fp16_full_eval', False)
  787. bf16_full_eval = getattr(args, 'bf16_full_eval', False)
  788. if args.fp16 and bf16_full_eval: args.bf16_full_eval = False; args.fp16_full_eval = True
  789. if args.bf16 and fp16_full_eval: args.bf16_full_eval = True; args.fp16_full_eval = False
  790. if not bf16_full_eval and not fp16_full_eval: args.bf16_full_eval = args.bf16; args.fp16_full_eval = args.fp16
  791. if 'max_seq_length' not in locals() and not hasattr(args, 'max_seq_length'):
  792. pass
  793. else:
  794. model_max_seq_length = getattr(model, 'max_seq_length', None)
  795. args_max_seq_length = getattr(args, 'max_seq_length', None)
  796. if args_max_seq_length is None and model_max_seq_length is not None:
  797. max_seq_length = model.max_seq_length
  798. if hasattr(args, 'max_seq_length'): args.max_seq_length = max_seq_length
  799. if model is not None and hasattr(model, 'for_training'):
  800. model.for_training()
  801. if 'tokenizer' in locals() and hasattr(tokenizer, 'padding_side'): tokenizer.padding_side = 'right'
  802. if 'processing_class' in locals():
  803. if hasattr(processing_class, 'padding_side'): processing_class.padding_side = 'right'
  804. if hasattr(processing_class, 'tokenizer') and hasattr(processing_class.tokenizer, 'padding_side'): processing_class.tokenizer.padding_side = 'right'
  805. other_metrics = []
  806. from unsloth_zoo.logging_utils import PatchRLStatistics
  807. PatchRLStatistics('nash_md_trainer', other_metrics)
  808. super().__init__(
  809. model = model,
  810. ref_model = ref_model,
  811. reward_model = reward_model,
  812. judge = judge,
  813. args = args,
  814. data_collator = data_collator,
  815. train_dataset = train_dataset,
  816. eval_dataset = eval_dataset,
  817. processing_class = processing_class,
  818. peft_config = peft_config,
  819. compute_metrics = compute_metrics,
  820. callbacks = callbacks,
  821. preprocess_logits_for_metrics = preprocess_logits_for_metrics,**kwargs)
  822. if hasattr(self, 'neftune_hook_handle'):
  823. self.neftune_hook_handle.remove()
  824. if hasattr(self, 'neftune_hook_handle'): del self.neftune_hook_handle
  825. if getattr(args, 'neftune_noise_alpha', None) is not None:
  826. model.get_input_embeddings().neftune_noise_alpha = self.neftune_noise_alpha
  827. pass
  828. pass