UnslothGKDTrainer.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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.gkd_trainer import (Any, AutoModelForCausalLM, BaseImageProcessor, Callable, DataCollator, DataCollatorForChatML, Dataset, EvalPrediction, F, FeatureExtractionMixin, GKDConfig, GKDTrainer, GenerationConfig, Optional, PeftConfig, PreTrainedModel, PreTrainedModelWrapper, PreTrainedTokenizerBase, ProcessorMixin, SFTTrainer, TrainerCallback, Union, deepcopy, disable_dropout_in_model, empty_cache, generate_model_card, get_comet_experiment_url, is_wandb_available, nn, os, random, textwrap, torch, 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 UnslothGKDConfig(GKDConfig):
  32. """
  33. Configuration class for [`GKDTrainer`].
  34. Args:
  35. temperature (`float`, *optional*, defaults to `0.9`):
  36. Temperature for sampling. The higher the temperature, the more random the completions.
  37. lmbda (`float`, *optional*, defaults to `0.5`):
  38. Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy
  39. student-generated outputs).
  40. beta (`float`, *optional*, defaults to `0.5`):
  41. Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When
  42. beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence.
  43. max_new_tokens (`int`, *optional*, defaults to `128`):
  44. Maximum number of tokens to generate per completion.
  45. teacher_model_name_or_path (`str` or `None`, *optional*, defaults to `None`):
  46. Model name or path of the teacher model. If `None`, the teacher model will be the same as the model
  47. being trained.
  48. teacher_model_init_kwargs (`dict[str, Any]]` or `None`, *optional*, defaults to `None`):
  49. Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model
  50. from a string.
  51. disable_dropout (`bool`, *optional*, defaults to `True`):
  52. Whether to disable dropout in the model.
  53. seq_kd (`bool`, *optional*, defaults to `False`):
  54. Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT
  55. on teacher-generated output).
  56. """
  57. vllm_sampling_params: Optional[Any] = field(
  58. default = None,
  59. metadata = {'help': 'vLLM SamplingParams'},
  60. )
  61. unsloth_num_chunks : Optional[int] = field(
  62. default = -1,
  63. metadata = {'help': 'Chunk size to reduce memory usage. -1 is most efficient.'},
  64. )
  65. def __init__(
  66. self,
  67. output_dir = None,
  68. overwrite_output_dir = None,
  69. do_train = False,
  70. do_eval = False,
  71. do_predict = False,
  72. eval_strategy = 'no',
  73. prediction_loss_only = False,
  74. per_device_train_batch_size = 4,
  75. per_device_eval_batch_size = 4,
  76. per_gpu_train_batch_size = None,
  77. per_gpu_eval_batch_size = None,
  78. gradient_accumulation_steps = 2,
  79. eval_accumulation_steps = 2,
  80. eval_delay = 0,
  81. torch_empty_cache_steps = 250,
  82. learning_rate = 5e-05,
  83. weight_decay = 0.01,
  84. adam_beta1 = 0.9,
  85. adam_beta2 = 0.999,
  86. adam_epsilon = 1e-08,
  87. max_grad_norm = 1.0,
  88. num_train_epochs = 3.0,
  89. max_steps = -1,
  90. lr_scheduler_type = 'linear',
  91. warmup_ratio = 0.1,
  92. warmup_steps = 0,
  93. log_level = 'passive',
  94. log_level_replica = 'warning',
  95. log_on_each_node = True,
  96. logging_dir = None,
  97. logging_strategy = 'steps',
  98. logging_first_step = False,
  99. logging_steps = 1,
  100. logging_nan_inf_filter = False,
  101. save_strategy = 'steps',
  102. save_steps = 500,
  103. save_total_limit = None,
  104. save_safetensors = True,
  105. save_on_each_node = False,
  106. save_only_model = False,
  107. restore_callback_states_from_checkpoint = False,
  108. no_cuda = False,
  109. use_cpu = False,
  110. use_mps_device = False,
  111. seed = 3407,
  112. data_seed = 3407,
  113. jit_mode_eval = False,
  114. use_ipex = False,
  115. bf16 = False,
  116. fp16 = False,
  117. fp16_opt_level = 'O1',
  118. half_precision_backend = 'auto',
  119. bf16_full_eval = False,
  120. fp16_full_eval = False,
  121. tf32 = None,
  122. local_rank = -1,
  123. ddp_backend = None,
  124. tpu_num_cores = None,
  125. tpu_metrics_debug = False,
  126. debug = '',
  127. dataloader_drop_last = False,
  128. eval_steps = None,
  129. dataloader_num_workers = 0,
  130. dataloader_prefetch_factor = None,
  131. past_index = -1,
  132. run_name = None,
  133. disable_tqdm = None,
  134. remove_unused_columns = True,
  135. label_names = None,
  136. load_best_model_at_end = False,
  137. metric_for_best_model = None,
  138. greater_is_better = None,
  139. ignore_data_skip = False,
  140. fsdp = '',
  141. fsdp_min_num_params = 0,
  142. fsdp_config = None,
  143. fsdp_transformer_layer_cls_to_wrap = None,
  144. accelerator_config = None,
  145. deepspeed = None,
  146. label_smoothing_factor = 0.0,
  147. optim = 'adamw_8bit',
  148. optim_args = None,
  149. adafactor = False,
  150. group_by_length = False,
  151. length_column_name = 'length',
  152. report_to = None,
  153. ddp_find_unused_parameters = None,
  154. ddp_bucket_cap_mb = None,
  155. ddp_broadcast_buffers = None,
  156. dataloader_pin_memory = True,
  157. dataloader_persistent_workers = False,
  158. skip_memory_metrics = True,
  159. use_legacy_prediction_loop = False,
  160. push_to_hub = False,
  161. resume_from_checkpoint = None,
  162. hub_model_id = None,
  163. hub_strategy = 'every_save',
  164. hub_token = None,
  165. hub_private_repo = None,
  166. hub_always_push = False,
  167. gradient_checkpointing = False,
  168. gradient_checkpointing_kwargs = None,
  169. include_inputs_for_metrics = False,
  170. eval_do_concat_batches = True,
  171. fp16_backend = 'auto',
  172. evaluation_strategy = None,
  173. push_to_hub_model_id = None,
  174. push_to_hub_organization = None,
  175. push_to_hub_token = None,
  176. mp_parameters = '',
  177. auto_find_batch_size = False,
  178. full_determinism = False,
  179. torchdynamo = None,
  180. ray_scope = 'last',
  181. ddp_timeout = 1800,
  182. torch_compile = False,
  183. torch_compile_backend = None,
  184. torch_compile_mode = None,
  185. dispatch_batches = None,
  186. split_batches = None,
  187. include_tokens_per_second = False,
  188. include_num_input_tokens_seen = False,
  189. neftune_noise_alpha = None,
  190. optim_target_modules = None,
  191. batch_eval_metrics = False,
  192. eval_on_start = False,
  193. use_liger_kernel = False,
  194. eval_use_gather_object = False,
  195. average_tokens_across_devices = False,
  196. model_init_kwargs = None,
  197. use_liger = False,
  198. dataset_text_field = 'text',
  199. dataset_kwargs = None,
  200. dataset_num_proc = None,
  201. max_seq_length = 1024,
  202. packing = False,
  203. eval_packing = None,
  204. dataset_batch_size = None,
  205. num_of_sequences = None,
  206. chars_per_token = None,
  207. temperature = 0.9,
  208. lmbda = 0.5,
  209. beta = 0.5,
  210. max_new_tokens = 128,
  211. teacher_model_name_or_path = None,
  212. teacher_model_init_kwargs = None,
  213. disable_dropout = True,
  214. seq_kd = False,
  215. vllm_sampling_params = None,
  216. unsloth_num_chunks = -1,
  217. **kwargs,
  218. ):
  219. 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!')
  220. 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!')
  221. if output_dir is None and save_strategy == 'steps' and save_steps == 500:
  222. output_dir = 'unsloth_training_checkpoints'
  223. save_strategy = 'no'
  224. if dataset_num_proc is None:
  225. from multiprocessing import cpu_count
  226. dataset_num_proc = cpu_count()
  227. super().__init__(
  228. output_dir = output_dir,
  229. overwrite_output_dir = overwrite_output_dir,
  230. do_train = do_train,
  231. do_eval = do_eval,
  232. do_predict = do_predict,
  233. eval_strategy = eval_strategy,
  234. prediction_loss_only = prediction_loss_only,
  235. per_device_train_batch_size = per_device_train_batch_size,
  236. per_device_eval_batch_size = per_device_eval_batch_size,
  237. per_gpu_train_batch_size = per_gpu_train_batch_size,
  238. per_gpu_eval_batch_size = per_gpu_eval_batch_size,
  239. gradient_accumulation_steps = gradient_accumulation_steps,
  240. eval_accumulation_steps = eval_accumulation_steps,
  241. eval_delay = eval_delay,
  242. torch_empty_cache_steps = torch_empty_cache_steps,
  243. learning_rate = learning_rate,
  244. weight_decay = weight_decay,
  245. adam_beta1 = adam_beta1,
  246. adam_beta2 = adam_beta2,
  247. adam_epsilon = adam_epsilon,
  248. max_grad_norm = max_grad_norm,
  249. num_train_epochs = num_train_epochs,
  250. max_steps = max_steps,
  251. lr_scheduler_type = lr_scheduler_type,
  252. warmup_ratio = warmup_ratio,
  253. warmup_steps = warmup_steps,
  254. log_level = log_level,
  255. log_level_replica = log_level_replica,
  256. log_on_each_node = log_on_each_node,
  257. logging_dir = logging_dir,
  258. logging_strategy = logging_strategy,
  259. logging_first_step = logging_first_step,
  260. logging_steps = logging_steps,
  261. logging_nan_inf_filter = logging_nan_inf_filter,
  262. save_strategy = save_strategy,
  263. save_steps = save_steps,
  264. save_total_limit = save_total_limit,
  265. save_safetensors = save_safetensors,
  266. save_on_each_node = save_on_each_node,
  267. save_only_model = save_only_model,
  268. restore_callback_states_from_checkpoint = restore_callback_states_from_checkpoint,
  269. no_cuda = no_cuda,
  270. use_cpu = use_cpu,
  271. use_mps_device = use_mps_device,
  272. seed = seed,
  273. data_seed = data_seed,
  274. jit_mode_eval = jit_mode_eval,
  275. use_ipex = use_ipex,
  276. bf16 = bf16,
  277. fp16 = fp16,
  278. fp16_opt_level = fp16_opt_level,
  279. half_precision_backend = half_precision_backend,
  280. bf16_full_eval = bf16_full_eval,
  281. fp16_full_eval = fp16_full_eval,
  282. tf32 = tf32,
  283. local_rank = local_rank,
  284. ddp_backend = ddp_backend,
  285. tpu_num_cores = tpu_num_cores,
  286. tpu_metrics_debug = tpu_metrics_debug,
  287. debug = debug,
  288. dataloader_drop_last = dataloader_drop_last,
  289. eval_steps = eval_steps,
  290. dataloader_num_workers = dataloader_num_workers,
  291. dataloader_prefetch_factor = dataloader_prefetch_factor,
  292. past_index = past_index,
  293. run_name = run_name,
  294. disable_tqdm = disable_tqdm,
  295. remove_unused_columns = remove_unused_columns,
  296. label_names = label_names,
  297. load_best_model_at_end = load_best_model_at_end,
  298. metric_for_best_model = metric_for_best_model,
  299. greater_is_better = greater_is_better,
  300. ignore_data_skip = ignore_data_skip,
  301. fsdp = fsdp,
  302. fsdp_min_num_params = fsdp_min_num_params,
  303. fsdp_config = fsdp_config,
  304. fsdp_transformer_layer_cls_to_wrap = fsdp_transformer_layer_cls_to_wrap,
  305. accelerator_config = accelerator_config,
  306. deepspeed = deepspeed,
  307. label_smoothing_factor = label_smoothing_factor,
  308. optim = optim,
  309. optim_args = optim_args,
  310. adafactor = adafactor,
  311. group_by_length = group_by_length,
  312. length_column_name = length_column_name,
  313. report_to = report_to,
  314. ddp_find_unused_parameters = ddp_find_unused_parameters,
  315. ddp_bucket_cap_mb = ddp_bucket_cap_mb,
  316. ddp_broadcast_buffers = ddp_broadcast_buffers,
  317. dataloader_pin_memory = dataloader_pin_memory,
  318. dataloader_persistent_workers = dataloader_persistent_workers,
  319. skip_memory_metrics = skip_memory_metrics,
  320. use_legacy_prediction_loop = use_legacy_prediction_loop,
  321. push_to_hub = push_to_hub,
  322. resume_from_checkpoint = resume_from_checkpoint,
  323. hub_model_id = hub_model_id,
  324. hub_strategy = hub_strategy,
  325. hub_token = hub_token,
  326. hub_private_repo = hub_private_repo,
  327. hub_always_push = hub_always_push,
  328. gradient_checkpointing = gradient_checkpointing,
  329. gradient_checkpointing_kwargs = gradient_checkpointing_kwargs,
  330. include_inputs_for_metrics = include_inputs_for_metrics,
  331. eval_do_concat_batches = eval_do_concat_batches,
  332. fp16_backend = fp16_backend,
  333. evaluation_strategy = evaluation_strategy,
  334. push_to_hub_model_id = push_to_hub_model_id,
  335. push_to_hub_organization = push_to_hub_organization,
  336. push_to_hub_token = push_to_hub_token,
  337. mp_parameters = mp_parameters,
  338. auto_find_batch_size = auto_find_batch_size,
  339. full_determinism = full_determinism,
  340. torchdynamo = torchdynamo,
  341. ray_scope = ray_scope,
  342. ddp_timeout = ddp_timeout,
  343. torch_compile = torch_compile,
  344. torch_compile_backend = torch_compile_backend,
  345. torch_compile_mode = torch_compile_mode,
  346. dispatch_batches = dispatch_batches,
  347. split_batches = split_batches,
  348. include_tokens_per_second = include_tokens_per_second,
  349. include_num_input_tokens_seen = include_num_input_tokens_seen,
  350. neftune_noise_alpha = neftune_noise_alpha,
  351. optim_target_modules = optim_target_modules,
  352. batch_eval_metrics = batch_eval_metrics,
  353. eval_on_start = eval_on_start,
  354. use_liger_kernel = use_liger_kernel,
  355. eval_use_gather_object = eval_use_gather_object,
  356. average_tokens_across_devices = average_tokens_across_devices,
  357. model_init_kwargs = model_init_kwargs,
  358. use_liger = use_liger,
  359. dataset_text_field = dataset_text_field,
  360. dataset_kwargs = dataset_kwargs,
  361. dataset_num_proc = dataset_num_proc,
  362. max_seq_length = max_seq_length,
  363. packing = packing,
  364. eval_packing = eval_packing,
  365. dataset_batch_size = dataset_batch_size,
  366. num_of_sequences = num_of_sequences,
  367. chars_per_token = chars_per_token,
  368. temperature = temperature,
  369. lmbda = lmbda,
  370. beta = beta,
  371. max_new_tokens = max_new_tokens,
  372. teacher_model_name_or_path = teacher_model_name_or_path,
  373. teacher_model_init_kwargs = teacher_model_init_kwargs,
  374. disable_dropout = disable_dropout,
  375. seq_kd = seq_kd,**kwargs)
  376. self.vllm_sampling_params = vllm_sampling_params
  377. self.unsloth_num_chunks = unsloth_num_chunks
  378. pass
  379. class _UnslothGKDTrainer(SFTTrainer):
  380. _tag_names = ["trl", "gkd"]
  381. def __init__(
  382. self,
  383. model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
  384. teacher_model: Union[PreTrainedModel, nn.Module, str] = None,
  385. args: Optional[GKDConfig] = None,
  386. data_collator: Optional[DataCollator] = None, # type: ignore
  387. train_dataset: Optional[Dataset] = None,
  388. eval_dataset: Optional[Union[Dataset, dict[str, Dataset]]] = None,
  389. processing_class: Optional[
  390. Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin]
  391. ] = None,
  392. compute_metrics: Optional[Callable[[EvalPrediction], dict]] = None,
  393. callbacks: Optional[list[TrainerCallback]] = None,
  394. optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
  395. preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
  396. peft_config: Optional["PeftConfig"] = None,
  397. formatting_func: Optional[Callable] = None,
  398. ):
  399. # add remove_unused_columns=False to the dataclass args
  400. args.remove_unused_columns = False
  401. data_collator = DataCollatorForChatML(tokenizer=processing_class, max_length=args.max_seq_length)
  402. super().__init__(
  403. model,
  404. args=args,
  405. data_collator=data_collator,
  406. train_dataset=train_dataset,
  407. eval_dataset=eval_dataset,
  408. processing_class=processing_class,
  409. compute_metrics=compute_metrics,
  410. callbacks=callbacks,
  411. optimizers=optimizers,
  412. preprocess_logits_for_metrics=preprocess_logits_for_metrics,
  413. peft_config=peft_config,
  414. formatting_func=formatting_func,
  415. )
  416. if args.teacher_model_init_kwargs is None:
  417. teacher_model_init_kwargs = {}
  418. elif not isinstance(teacher_model, str):
  419. raise ValueError(
  420. "You passed teacher_model_init_kwargs to the GKDConfig, but your teacher_model is already instantiated."
  421. )
  422. else:
  423. teacher_model_init_kwargs = args.teacher_model_init_kwargs
  424. teacher_model_init_kwargs["torch_dtype"] = (
  425. teacher_model_init_kwargs["torch_dtype"]
  426. if teacher_model_init_kwargs["torch_dtype"] in ["auto", None]
  427. else getattr(torch, teacher_model_init_kwargs["torch_dtype"])
  428. )
  429. if isinstance(teacher_model, str):
  430. if args.use_liger:
  431. teacher_model = AutoLigerKernelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs)
  432. else:
  433. teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs)
  434. # Disable dropout in the model
  435. if args.disable_dropout:
  436. disable_dropout_in_model(self.model)
  437. if self.is_deepspeed_enabled:
  438. self.teacher_model = self._prepare_deepspeed(teacher_model)
  439. else:
  440. self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True)
  441. self.lmbda = args.lmbda
  442. self.beta = args.beta
  443. self.temperature = args.temperature
  444. self.seq_kd = args.seq_kd
  445. self.generation_config = GenerationConfig(
  446. max_new_tokens=args.max_new_tokens,
  447. temperature=args.temperature,
  448. do_sample=True,
  449. top_k=0,
  450. use_cache=False if args.gradient_checkpointing else True,
  451. pad_token_id=self.processing_class.pad_token_id,
  452. )
  453. # Set custom EOS tokens if they are specified by the model's generation
  454. # config. This is important for models with the Llama 3 chat template,
  455. # which use special tokens <|eot_id|> and <|eom_id|> to mark the end of
  456. # turns or messages.
  457. if (
  458. hasattr(self.model.generation_config, "eos_token_id")
  459. and self.model.generation_config.eos_token_id is not None
  460. ):
  461. self.generation_config.eos_token_id = self.model.generation_config.eos_token_id
  462. def _prepare_dataset(self, dataset, *args):
  463. # SFTTrainer._prepare_dataset() applies the chat template and rename the messages column to text. However, we
  464. # need to keep the messages column as it is. We use the following workaround to keep the messages column.
  465. dataset = dataset.add_column("_messages", dataset["messages"])
  466. dataset = super()._prepare_dataset(dataset, *args)
  467. dataset = dataset.rename_column("_messages", "messages")
  468. return dataset
  469. @staticmethod
  470. def generalized_jsd_loss(
  471. student_logits, teacher_logits, labels=None, beta=0.5, temperature=1.0, reduction="batchmean"
  472. ):
  473. """
  474. Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation using F.kl_div. See Eq. (1)
  475. of https://huggingface.co/papers/2306.13649 for the definition.
  476. Args:
  477. student_logits: Tensor of shape (batch_size, sequence_length, vocab_size)
  478. teacher_logits: Tensor of shape (batch_size, sequence_length, vocab_size)
  479. labels: Tensor of shape (batch_size, sequence_length) with -100 for padding tokens to ignore when computing loss
  480. beta: Interpolation coefficient between 0 and 1 (default: 0.5)
  481. temperature: Softmax temperature (default: 1.0)
  482. reduction: Specifies the reduction to apply to the output (default: 'batchmean')
  483. Returns:
  484. loss: Scalar tensor with the generalized JSD loss
  485. """
  486. # Apply temperature scaling
  487. student_logits = student_logits / temperature
  488. teacher_logits = teacher_logits / temperature
  489. # Compute log probabilities for student and probabilities for teacher
  490. student_log_probs = F.log_softmax(student_logits, dim=-1)
  491. teacher_log_probs = F.log_softmax(teacher_logits, dim=-1)
  492. # Compute the log of the mixture distribution
  493. # log(a + b) = log(exp(log(a)) + exp(log(b))) -> for mixture
  494. beta = torch.tensor(beta, dtype=student_log_probs.dtype)
  495. mixture_log_probs = torch.logsumexp(
  496. torch.stack([student_log_probs + torch.log(beta), teacher_log_probs + torch.log(1 - beta)]),
  497. dim=0,
  498. )
  499. # Compute KL divergences using F.kl_div
  500. # PyTorch differs from the standard mathematical definition, so the order of the probability distributions is swapped compared to that defined in the paper.
  501. kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True)
  502. kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True)
  503. # Compute the Generalized Jensen-Shannon Divergence
  504. jsd = beta * kl_teacher + (1 - beta) * kl_student
  505. # Masking
  506. if labels is not None:
  507. mask = labels != -100
  508. jsd = jsd[mask]
  509. # Apply reduction
  510. if reduction == "batchmean":
  511. return jsd.sum() / mask.sum() if labels is not None else jsd.sum() / (jsd.size(0) * jsd.size(1))
  512. elif reduction == "sum":
  513. return jsd.sum()
  514. elif reduction == "mean":
  515. return jsd.mean()
  516. else:
  517. return jsd
  518. def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
  519. # compute student output
  520. outputs_student = model(
  521. input_ids=inputs["input_ids"],
  522. attention_mask=inputs["attention_mask"],
  523. )
  524. # compute teacher output in eval mode
  525. self.teacher_model.eval()
  526. with torch.no_grad():
  527. outputs_teacher = self.teacher_model(
  528. input_ids=inputs["input_ids"],
  529. attention_mask=inputs["attention_mask"],
  530. )
  531. # slice the logits for the generated tokens using the inputs["prompts"] lengths
  532. prompt_lengths = inputs["prompts"].shape[1]
  533. shifted_student_logits = outputs_student.logits[:, prompt_lengths - 1 : -1, :]
  534. shifted_teacher_logits = outputs_teacher.logits[:, prompt_lengths - 1 : -1, :]
  535. shifted_labels = inputs["labels"][:, prompt_lengths:]
  536. # compute loss
  537. loss = self.generalized_jsd_loss(
  538. student_logits=shifted_student_logits,
  539. teacher_logits=shifted_teacher_logits,
  540. labels=shifted_labels,
  541. beta=self.beta,
  542. )
  543. # empty cache
  544. empty_cache()
  545. # Return loss
  546. return (loss, outputs_student) if return_outputs else loss
  547. @staticmethod
  548. def generate_on_policy_outputs(model, inputs, generation_config, pad_token_id=None):
  549. # Generate output with respect to the prompt only
  550. generated_outputs = model.generate(
  551. input_ids=inputs["prompts"],
  552. attention_mask=inputs.get("prompt_attention_mask", None),
  553. generation_config=generation_config,
  554. return_dict_in_generate=True,
  555. )
  556. # Get the generated token IDs
  557. generated_tokens = generated_outputs.sequences
  558. # Calculate new attention mask
  559. new_attention_mask = torch.ones_like(generated_tokens)
  560. new_labels = generated_tokens.clone()
  561. # If there's pad_token_id, set attention mask to 0 for padding tokens
  562. if pad_token_id is not None:
  563. new_labels[new_labels == pad_token_id] = -100
  564. new_attention_mask[generated_tokens == pad_token_id] = 0
  565. return generated_tokens, new_attention_mask, new_labels
  566. def training_step(
  567. self, model: nn.Module, inputs: dict[str, Union[torch.Tensor, Any]], num_items_in_batch: Optional[int] = None
  568. ) -> torch.Tensor:
  569. """
  570. Perform a training step for the Generalized Knowledge Distillation (GKD) model.
  571. This method implements the on-policy learning approach described in the GKD paper.
  572. With probability `self.lmbda`, it generates new responses using the student model,
  573. which are then used for training instead of the original inputs.
  574. """
  575. if self.seq_kd:
  576. with unwrap_model_for_generation(self.teacher_model, self.accelerator) as unwrapped_model:
  577. new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs(
  578. unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id
  579. )
  580. inputs["input_ids"] = new_input_ids
  581. inputs["attention_mask"] = new_attention_mask
  582. inputs["labels"] = new_labels
  583. if random.random() <= self.lmbda:
  584. with unwrap_model_for_generation(model, self.accelerator) as unwrapped_model:
  585. new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs(
  586. unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id
  587. )
  588. inputs["input_ids"] = new_input_ids
  589. inputs["attention_mask"] = new_attention_mask
  590. inputs["labels"] = new_labels
  591. loss = super().training_step(model, inputs, num_items_in_batch)
  592. return loss
  593. def _prepare_deepspeed(self, model: PreTrainedModelWrapper):
  594. # Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473
  595. deepspeed_plugin = self.accelerator.state.deepspeed_plugin
  596. config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config)
  597. if model is not None:
  598. if hasattr(model, "config"):
  599. hidden_size = (
  600. max(model.config.hidden_sizes)
  601. if getattr(model.config, "hidden_sizes", None)
  602. else getattr(model.config, "hidden_size", None)
  603. )
  604. if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3:
  605. # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0`
  606. # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081
  607. config_kwargs.update(
  608. {
  609. "zero_optimization.reduce_bucket_size": hidden_size * hidden_size,
  610. "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size,
  611. "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size,
  612. }
  613. )
  614. # If ZeRO-3 is used, we shard both the active and reference model.
  615. # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0)
  616. if config_kwargs["zero_optimization"]["stage"] != 3:
  617. config_kwargs["zero_optimization"]["stage"] = 0
  618. model, *_ = deepspeed.initialize(model=model, config=config_kwargs)
  619. model.eval()
  620. return model
  621. def create_model_card(
  622. self,
  623. model_name: Optional[str] = None,
  624. dataset_name: Optional[str] = None,
  625. tags: Union[str, list[str], None] = None,
  626. ):
  627. """
  628. Creates a draft of a model card using the information available to the `Trainer`.
  629. Args:
  630. model_name (`str` or `None`, *optional*, defaults to `None`):
  631. Name of the model.
  632. dataset_name (`str` or `None`, *optional*, defaults to `None`):
  633. Name of the dataset used for training.
  634. tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`):
  635. Tags to be associated with the model card.
  636. """
  637. if not self.is_world_process_zero():
  638. return
  639. if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path):
  640. base_model = self.model.config._name_or_path
  641. else:
  642. base_model = None
  643. tags = tags or []
  644. if isinstance(tags, str):
  645. tags = [tags]
  646. if hasattr(self.model.config, "unsloth_version"):
  647. tags.append("unsloth")
  648. citation = textwrap.dedent("""\
  649. @inproceedings{agarwal2024on-policy,
  650. title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}},
  651. author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem},
  652. year = 2024,
  653. booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024},
  654. publisher = {OpenReview.net},
  655. url = {https://openreview.net/forum?id=3zKtaqxLhW},
  656. }""")
  657. model_card = generate_model_card(
  658. base_model=base_model,
  659. model_name=model_name,
  660. hub_model_id=self.hub_model_id,
  661. dataset_name=dataset_name,
  662. tags=tags,
  663. wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None,
  664. comet_url=get_comet_experiment_url(),
  665. trainer_name="GKD",
  666. trainer_citation=citation,
  667. paper_title="On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes",
  668. paper_id="2306.13649",
  669. )
  670. model_card.save(os.path.join(self.args.output_dir, "README.md"))
  671. class UnslothGKDTrainer(_UnslothGKDTrainer):
  672. """
  673. """
  674. def __init__(
  675. self,
  676. model = None,
  677. teacher_model = None,
  678. args = None,
  679. data_collator = None,
  680. train_dataset = None,
  681. eval_dataset = None,
  682. processing_class = None,
  683. compute_metrics = None,
  684. callbacks = None,
  685. preprocess_logits_for_metrics = None,
  686. peft_config = None,
  687. formatting_func = None,
  688. **kwargs
  689. ):
  690. if args is None: args = UnslothGKDConfig()
  691. use_bf16 = getattr(args, 'bf16', False)
  692. use_fp16 = getattr(args, 'fp16', False)
  693. dtype = getattr(model.config, 'torch_dtype', None)
  694. if dtype is None: dtype = model.get_input_embeddings().dtype
  695. from unsloth_zoo.utils import _get_dtype
  696. dtype = _get_dtype(dtype)
  697. float16 = dtype == torch.float16
  698. 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`')
  699. 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`')
  700. if not use_bf16 and not use_fp16:
  701. args.fp16 = float16
  702. args.bf16 = not float16
  703. os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'
  704. if getattr(args, 'eval_dataset', None) is not None and getattr(args, 'eval_strategy', 'no') == 'no':
  705. args.eval_strategy = 'steps'
  706. if getattr(args, 'eval_steps', None) is None: args.eval_steps = 0.1
  707. ga_steps = getattr(args, 'gradient_accumulation_steps', None)
  708. if ga_steps is not None and ga_steps > 1:
  709. from transformers import __version__ as transformers_version
  710. if Version(transformers_version) <= Version('4.45.2'):
  711. print('**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!\n'
  712. '`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`')
  713. if getattr(args, 'eval_strategy', 'no') != 'no':
  714. eval_bsz = getattr(args, 'per_device_eval_batch_size', 8)
  715. 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
  716. if getattr(args, 'eval_accumulation_steps', None) is None and ga_steps is not None: args.eval_accumulation_steps = ga_steps
  717. fp16_full_eval = getattr(args, 'fp16_full_eval', False)
  718. bf16_full_eval = getattr(args, 'bf16_full_eval', False)
  719. if args.fp16 and bf16_full_eval: args.bf16_full_eval = False; args.fp16_full_eval = True
  720. if args.bf16 and fp16_full_eval: args.bf16_full_eval = True; args.fp16_full_eval = False
  721. if not bf16_full_eval and not fp16_full_eval: args.bf16_full_eval = args.bf16; args.fp16_full_eval = args.fp16
  722. if 'max_seq_length' not in locals() and not hasattr(args, 'max_seq_length'):
  723. pass
  724. else:
  725. model_max_seq_length = getattr(model, 'max_seq_length', None)
  726. args_max_seq_length = getattr(args, 'max_seq_length', None)
  727. if args_max_seq_length is None and model_max_seq_length is not None:
  728. max_seq_length = model.max_seq_length
  729. if hasattr(args, 'max_seq_length'): args.max_seq_length = max_seq_length
  730. if model is not None and hasattr(model, 'for_training'):
  731. model.for_training()
  732. if 'tokenizer' in locals() and hasattr(tokenizer, 'padding_side'): tokenizer.padding_side = 'right'
  733. if 'processing_class' in locals():
  734. if hasattr(processing_class, 'padding_side'): processing_class.padding_side = 'right'
  735. if hasattr(processing_class, 'tokenizer') and hasattr(processing_class.tokenizer, 'padding_side'): processing_class.tokenizer.padding_side = 'right'
  736. other_metrics = []
  737. from unsloth_zoo.logging_utils import PatchRLStatistics
  738. PatchRLStatistics('gkd_trainer', other_metrics)
  739. super().__init__(
  740. model = model,
  741. teacher_model = teacher_model,
  742. args = args,
  743. data_collator = data_collator,
  744. train_dataset = train_dataset,
  745. eval_dataset = eval_dataset,
  746. processing_class = processing_class,
  747. compute_metrics = compute_metrics,
  748. callbacks = callbacks,
  749. preprocess_logits_for_metrics = preprocess_logits_for_metrics,
  750. peft_config = peft_config,
  751. formatting_func = formatting_func,**kwargs)
  752. if hasattr(self, 'neftune_hook_handle'):
  753. self.neftune_hook_handle.remove()
  754. if hasattr(self, 'neftune_hook_handle'): del self.neftune_hook_handle
  755. if getattr(args, 'neftune_noise_alpha', None) is not None:
  756. model.get_input_embeddings().neftune_noise_alpha = self.neftune_noise_alpha
  757. pass
  758. pass