Files
DS-LLM-TEMPLATE-FINETUNING/unsloth_compiled_cache/__pycache__/UnslothGRPOTrainer.cpython-310.pyc
T

813 lines
80 KiB
Plaintext
Raw Normal View History

2025-08-28 17:57:59 +00:00
o
2025-08-28 22:41:56 +00:00
ö×°hü]ã@dZddlmZddlZddlmZddlmZddlmZm Z m
2025-08-28 17:57:59 +00:00
Z
m Z m Z m
Z
mZmZddlmZmZmZmZmZmZmZmZmZmZmZmZm
Z
mZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm Z m(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmZmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmZmVZVmWZWmXZXmYZYmZmZm Z m*Z*m+Z+m,Z,m2Z2m3Z3m8Z8m:Z:mAZAmDZDmEZEmFZFmGZGmLZLmNZNmZmVZVmXZXm1Z1mFZFmNZNmPZPmZmVZVmNZNmZm Z mFZFmMZMmNZNmRZRmSZSmTZTmZmWZWm
Z
mZm&Z&m<Z<mFZFmNZNmZmZmZmFZFmNZNmZmZmNZNmZmZm&Z&m2Z2mFZFmNZNmZddlFZFddlTddlZm[Z[m\Z\dd l]m^Z^ddlZddl_Z`dd
lamEZEddlmZdd lVmbZbmcZdd d
d d
d
dœZeejfd d eedddƒZgddZhGdddejijjƒZk d#ddZlejfd d eedddƒZmddZne[GdddeƒƒZo Gdd „d e&ƒZpGd!d"„d"epƒZqdS)$z9
2025.8.9
2025.8.10
4.55.4
0.21.0
__UNSLOTH_VERSIONING__
é)ÚTensorN)Ú
functional)ÚAnyÚListÚOptionalÚTupleÚUnionÚDictÚSetÚCallable)ˆrÚ
AutoConfigÚ"AutoModelForSequenceClassificationÚ
AutoProcessorÚ
AutoTokenizerÚ
DataLoaderÚDatasetÚFSDPÚ
GRPOConfigÚ GRPOTrainerÚGenerationConfigÚIterableDatasetrÚPathÚ
PeftConfigÚPreTrainedModelÚPreTrainedTokenizerBaseÚProcessorMixinÚ
RepeatSamplerÚ
RewardFuncÚSamplerÚSequenceÚSyncRefModelCallbackÚTrainerÚTrainerCallbackrÚ
VLLMClientÚ_ForwardRedirectionÚapply_chat_templateÚbroadcast_object_listÚcopyÚdatasetsÚ defaultdictÚdequeÚdisable_dropout_in_modelÚentropy_from_logitsÚgatherÚ
gather_objectÚgenerate_model_cardÚget_comet_experiment_urlÚidentityÚinspectÚis_conversationalÚis_datasets_availableÚis_flash_attn_2_availableÚis_liger_kernel_availableÚis_peft_availableÚ
is_peft_modelÚis_rich_availableÚis_vllm_availableÚis_wandb_availableÚmaybe_apply_chat_templateÚnanmaxÚnanminÚnanstdÚnnÚ nullcontextÚosÚpadÚpartialÚprepare_deepspeedÚ prepare_fsdpÚprint_prompt_completions_sampleÚprofiling_contextÚprofiling_decoratorÚreÚ seed_workerÚselective_log_softmaxÚset_seedÚshuffle_sequence_dictÚsplit_pixel_values_by_gridÚsplit_tensor_dictÚtextwrapÚtorchÚ transformersÚunsplit_pixel_values_by_gridÚunwrap_model_for_generationÚwarningsrrrr%r&r'r-r.r3r5r<r?rArBrCrHrJrRrSrUr,rBrJrLrRrSrJrrrBrIrJrNrOrPrRrTrrr!r7rBrJrRrr@rBrJrr@rJrRrr!r-rBrJrR)Ú*)Ú dataclassÚfield)ÚVersion)rA)ÚDataCollatorForSeq2SeqÚDataCollatorForLanguageModelingTF)Úepilogue_fusionÚ max_autotuneÚ
shape_paddingz
trace.enabledztriton.cudagraphs)ÚdynamicÚ fullgraphÚoptionsc
Ctj| d|jd¡ddd}tj| d¡ddd}g}t||ƒD](\}}| tj¡}tj|d| d¡d  d¡}tj
|dd}||} |  | ¡q! t  |¡}| |jd|jdf¡}|S)Néÿÿÿÿér©ÚchunksÚdim©rgÚindex©rgé)
rRÚchunkÚreshapeÚshapeÚzipÚtoÚfloat32r-Ú unsqueezeÚsqueezeÚ logsumexpÚappendÚconcat)
ÚlogitsriÚchunked_logitsÚ
chunked_indexÚall_per_token_logpsÚ chunk_logitsÚ chunk_indexÚselected_logitsÚlogsumexp_valuesÚper_token_logps©r€úR/workspace/DS-LLM-TEMPLATE-FINETUNING/unsloth_compiled_cache/UnslothGRPOTrainer.pyÚchunked_selective_log_softmax"s  
rc"Kó | dd¡}| dd¡} | dd¡}
| dd¡} | dd¡} | d d
¡}
| d d ¡}| d
d ¡}| dd ¡}| d¡}|dkrC||}|dkrK||}|dkrX|t ||¡}| tj¡}|
d
krf||
}tj|d|d d¡}|tj|dd}t  ¡˜|d krÊ|dusJdƒ|dkr“||}|dkr||}|dkr¨|t ||¡}| tj¡}|
d
kr¶||
}tj|d|d d¡}|tj|dd} |dur|dkrØ||}|dkrà||}|dkrí|t ||¡}| tj¡}|
d
krû||
}tj|d|d d¡}|tj|dd}Wdƒn 1swY |d kr3t 
||¡||d
}nd }|durBt 
||¡}n t 
||  ¡¡}t  |d| d|
¡}| durhtj || d| d¡}n|| d¡} || d¡}t 
||¡ }|d kr‰|||}| tj¡}| d¡}|dkr¬|| d¡| d¡j d
d ¡}n.|dkrÀ|| ¡| ¡j d
d}n|dkrÓ|| ¡| d¡| }ntd|ƒt ¡| ¡}|| d¡|} |  ¡}!Wdƒn 1sûwY |||!fS©NÚ loss_typeÚgrpoÚ epsilon_lowçš™™™™™É?Ú epsilon_highÚmax_completion_lengthi ÚdeltaÚ temperatureçð?Úlogit_scale_multiplyçÚlogit_scale_divideÚlogit_softcappingrcrrhrjz.ref_logits should not be None when beta != 0.0rk©Úmax©ÚminÚbnpoÚdr_grpoúUnknown loss type: ©ÚgetrrrRÚtanhrprqr-rsrtÚno_gradÚexpÚdetachÚclampr•ÚsumÚmeanÚsizeÚ
ValueErrorÚinference_mode©"Ú
ref_logitsÚ
new_logitsÚ
old_logitsÚ input_idsÚmaskÚbetaÚ
advantagesÚkwargsr…r‡r‰rrrÚnew_xÚnewÚref_xÚrefÚold_xÚoldÚkl_iÚcoef_1Úcoef_2Úloss_1Úloss_2Úloss_iÚn_mask_per_rewardÚlossÚcompletion_lengthÚmean_kl_per_rewardÚmean_klr€r€rÚgrpo_compute_loss4        
 
 
 å



  

&



ý
r¿c@s(eZdZedddƒZ eddƒZdS)ÚUnslothEfficientGRPONrkc 
s’ˆdurifdd |j} t |¡}
tjd| dtjd| dtjd| dfdd} tj|ddtd}tj|
|
d d
}tj||
d d
}|dur\tj||
d d
}ndg|
}tj||
d d
}tj||
d d
}tj||
d d
}tj||
d d
}| dur‰|  ¡nd }t|||||||ƒD]\}}}}}}}|||||||||ƒq• |
  |
¡ˆ  |
¡ˆ  |
¡ˆ  |
¡| 
|
¡ˆˆˆfS) Nct |ˆ ¡¡}|ddddddf}t ¡@ˆdkr4t |ˆ ¡¡}|ddddddf}nd}|durPt |ˆ ¡¡} | ddddddf} nd} Wdƒn1s\wYt||| ||ˆ|fiˆ¤Ž\}
} } |
|}
|
|
 ¡| | ffS)Nrcr)rRÚmatmulÚtrœr¿)Únew_hidden_statesÚold_hidden_statesÚref_hidden_statesr©Úscalingr§Ú scaled_loss)Ú extra_kwargsÚlm_headr€rÚ compute_lossµs4
öù ø z2UnslothEfficientGRPO.forward.<locals>.compute_lossrk©Údevicec
s`tjjˆddd|||||||ƒ\\}\} \}
} } ˆ |
¡ˆ | ¡ˆ | ¡||dd<dS)rT)ÚargnumsÚhas_aux)rRÚfuncÚgrad_and_valueÚadd_)
Únew_hidden_states_jÚold_hidden_states_jÚref_hidden_states_jÚ input_ids_jÚmask_jÚ advantages_jrÆÚ
grad_inputs_jÚchunk_grad_inputÚ
chunk_lossÚ
unscaled_lossÚchunk_completion_lengthÚ
chunk_mean_kl)Úaccumulated_completion_lengthÚaccumulated_lossÚaccumulated_mean_klrÊr€rÚaccumulate_chunkàs
ýü


z6UnslothEfficientGRPO.forward.<locals>.accumulate_chunkT)rar`rbrrer) rRÚ
empty_likeÚzerosÚcompileÚtorch_compile_optionsrlÚ get_scaleroÚdiv_Úsave_for_backward)ÚctxÚ_new_hidden_statesÚ_old_hidden_statesÚ_ref_hidden_statesrÉÚ
_input_idsÚ_maskÚ _advantagesr«ÚscalerÚn_chunksrÈÚ grad_inputsrâÚgrad_inputs_chunksrÃr€)rÚforward±sb#
û
ÿ ø




ýzUnslothEfficientGRPO.forwardc Cs"|j\}|ddddddddddf S©N)Ú
saved_tensors)Ú grad_outputÚdcompletion_lengthÚdmean_klÚ
grad_inputr€r€rÚbackward2szUnslothEfficientGRPO.backward)NrkN)Ú__name__Ú
__module__Ú __qualname__Ú staticmethodrõr€r€r€r¯s ~
rcc |j\} ‡fddtdˆdƒDƒ}
|dkrˆ}|
tt |
|¡t|
ƒdƒ}t|dƒsJtj  dd¡dkr9t
j nt
j |_
tj  dd ¡d
krJt
j |_
d
tjd <|dd| df} |j ¡j} t
jj|jjj|j
d ct
 ¡.|jj|jd
d ¡|j|||ddj}
Wdƒn1s”wYWdƒn1s£wY |j|||ddj}t |||
| | |||j|jj||¡ \}}}Wdƒn1sÓwY d tjd <|||fS)Ncsg|]
}ˆ|dkr|qSr€©Ú.0ÚÚbszr€rÚ
<listcomp>Góz)grpo_accumulated_loss.<locals>.<listcomp>rkrcÚ_autocast_dtypeÚACCELERATE_MIXED_PRECISIONÚfp16ÚUNSLOTH_FORCE_FLOAT32ÚUNSLOTH_RETURN_HIDDEN_STATES)Ú device_typeÚdtypeF)Úkeep_fp32_wrapper)Úattention_maskÚlogits_to_keep)!rnÚranger•ÚnpÚ searchsortedÚlenÚhasattrrBÚenvironršrRÚfloat16Úbfloat16rÚmodelÚget_output_embeddingsÚweightÚampÚautocastrÌÚtyper¤Ú acceleratorÚ unwrap_modelÚdisable_adapterrwÚapplyr«r¿)Útrainerr©rrÚcompletion_maskr¬r­ÚqlenÚfactorsÚcompletion_input_idsrÉr€rrÚgrpo_accumulated_loss8s`
 
 
 "ýüÿýü õò

r+c"Kr„r™r€r€rÚgrpo_compute_loss_slow„
       
 
 
 å



  

&



ý
r,cKs$ddlm}|di|¤Ž}||_|S)Nr)ÚSamplingParamsr€)Úvllmr-Ú _set_kwargs)r­r-Úsampling_paramsr€r€rÚvLLMSamplingParamss r1c¯eZdZUdZedddidZeeed<edddidZ ee
ed <ddd
d
d
d d
d d ddd
d
ddddddddddddddddddd
dd
ddddd
d
d
d
d
d
ddd
d
d
d
d d!d
d
ddddd
d"d
ddddddd
dd
ddd
d"dddddd#d$dd
d
d%dddddd
dd
d
ddd&ddd
dd
dd
dd!dddd"dd
dd'd(d
ddd
d
ddd
d
d
dd
ddd
d)d*d+ddddddddidd
dd
dd,d-dd.d/d0d1dd2dd3ddd4ddd5d
d
d6d)dd
d
dd
ddf¯‡fd7d8„ Z Z S)9ÚUnslothGRPOConfiguâ<
Configuration class for the [`GRPOTrainer`].
This class includes only the parameters that are specific to GRPO training. For a full list of training arguments,
please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
differ from those in [`~transformers.TrainingArguments`].
Using [`~transformers.HfArgumentParser`] we can turn this class into
[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
command line.
Parameters:
> Parameters that control the model and reference model
model_init_kwargs (`str`, `dict[str, Any]` or `None`, *optional*, defaults to `None`):
Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
argument of the [`GRPOTrainer`] is provided as a string.
disable_dropout (`bool`, *optional*, defaults to `False`):
Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents
the model from generating different logprobs for the same input.
> Parameters that control the data preprocessing
remove_unused_columns (`bool`, *optional*, defaults to `False`):
Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that
requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`.
max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
Maximum length of the prompt. If the prompt is longer than this value, it will be truncated left.
num_generations (`int` or `None`, *optional*, defaults to `8`):
Number of generations per prompt to sample. The effective batch size (num_processes * per_device_batch_size
* gradient_accumulation_steps) must be evenly divisible by this value.
max_completion_length (`int` or `None`, *optional*, defaults to `256`):
Maximum length of the generated completion.
ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
improving generation speed. However, disabling this option allows training models that exceed the VRAM
capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
with vLLM generation.
shuffle_dataset (`bool`, *optional*, defaults to `True`):
Whether to shuffle the training dataset.
> Parameters that control generation
generation_batch_size: (`int` or `None`, *optional*, defaults to `None`):
Batch size to use for generation. If `None`, it defaults to the effective training batch size:
`per_device_train_batch_size * num_processes * steps_per_generation`. In other words, there is one
generation batch processed per optimization step. Mutually exclusive with `steps_per_generation`.
steps_per_generation: (`int` or `None`, *optional*, defaults to `None`):
Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. Mutually exclusive
with `generation_batch_size`.
temperature (`float`, defaults to `1.0`):
Temperature for sampling. The higher the temperature, the more random the completions.
top_p (`float`, *optional*, defaults to `1.0`):
Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to
`1.0` to consider all tokens.
top_k (`int` or `None`, *optional*, defaults to `None`):
Number of highest probability vocabulary tokens to keep for top-k-filtering. If `None`, top-k-filtering is
disabled and all tokens are considered.
min_p (`float` or `None`, *optional*, defaults to `None`):
Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range.
repetition_penalty (`float`, *optional*, defaults to `1.0`):
Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far.
Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat
tokens.
use_transformers_paged (`bool`, *optional*, defaults to `False`):
Whether to use the `transformers` paged implementation for generation. If set to `True`, the `transformers`
paged implementation will be used for generation instead of the default padded implementation. This
parameter is only effective when `use_vllm` is set to `False`.
cache_implementation (`str` or `None`, *optional*, defaults to `None`):
Implementation of the cache method for faster generation when `use_vllm` is set to `False`.
generation_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`):
Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if
using vLLM) when sampling completions. This can be used to further customize the generation behavior, such
as setting `supress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation
parameters (like `min_p`, `top_p`, etc.), they will override them.
> Parameters that control generation acceleration powered by vLLM
use_vllm (`bool`, *optional*, defaults to `False`):
Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation
instead of the default model.generate(). Requires `vllm` to be installed.
vllm_mode (`str`, *optional*, defaults to `"server"`):
Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or
`"colocate"`.
- `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM
server is running (start with `trl vllm-serve`).
- `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a
separate server but may cause resource contention with training.
vllm_guided_decoding_regex (`str` or `None`, *optional*, defaults to `None`):
Regex for vLLM guided decoding. If `None` (default), guided decoding is disabled.
> Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)
vllm_server_base_url (`str` or `None`, *optional*, defaults to `None`):
Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and
`vllm_server_port` are ignored.
vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
vllm_server_port (`int`, *optional*, defaults to `8000`):
Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the
timeout, a `ConnectionError` is raised.
> Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)
vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`):
Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to
`"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.
vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to
`"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
launching the vLLM server via the `--vllm_tensor_parallel_size` flag.
vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use
the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model
implementation.
> Parameters that control the training
beta (`float`, *optional*, defaults to `0.0`):
KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and improving
training speed.
num_iterations (`int`, *optional*, defaults to `1`):
Number of iterations per batch (denoted as μ in the algorithm).
epsilon (`float`, *optional*, defaults to `0.2`):
Epsilon value for clipping.
delta: (`float` or `None`, *optional*, defaults to `None`):
Enables the upper clipping bound in two-sided GRPO loss when set to a float. If `None` (default), standard
GRPO clipping is used. Recommended to be greater than `1 + ε` when enabled. This method is introduced in
the [INTELLECT-2 tech report](https://huggingface.co/papers/2505.07291).
epsilon_high (`float` or `None`, *optional*, defaults to `None`):
Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound
specified in argument `epsilon`. Paper [DAPO](https://huggingface.co/papers/2503.14476) recommends `0.28`.
importance_sampling_level (`str`, *optional*, defaults to `"token"`):
Controls whether importance sampling ratios are computed at the `"token"` or `"sequence"` level. `"token"`
keeps the raw per-token log-probability ratios (one weight per token). `"sequence"` averages the
log-probability ratios across valid tokens to produce a single ratio per sequence. The
[GSPO paper](https://huggingface.co/papers/2507.18071) shows that sequence-level sampling often yields more
stable training and better alignment with sequence-level rewards.
reward_weights (`list[float]` or `None`, *optional*, defaults to `None`):
Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are
weighted equally with weight `1.0`.
scale_rewards (`bool`, *optional*, defaults to `True`):
Whether to scale the rewards by dividing them by their standard deviation. If `True` (default), the rewards
are normalized by the standard deviation, ensuring they have unit variance. If `False`, no scaling is
applied. The [Dr. GRPO paper](https://huggingface.co/papers/2503.20783) recommends not scaling the rewards,
as scaling by the standard deviation introduces a question-level difficulty bias.
loss_type (`str`, *optional*, defaults to `"bnpo"`):
Specifies the loss formulation to use. Supported values are:
- `"grpo"`: Aggregates token-level losses by normalizing over sequence length. Not recommended due to
length bias—this approach tends to prefer shorter completions with positive advantages and longer ones
with negative advantages.
- `"bnpo"`: Aggregates token-level losses by normalizing number of active token in the local batch.
Note that normalization is performed over the local batch only, so results may slightly vary depending
on the local batch size, despite a constant effective batch size. When using
`per_device_train_batch_size==1`, the loss is equivalent to the GRPO loss.
- `"dr_grpo"`: Aggregates token-level losses by normalizing with a global constant. This method was
introduced in the [Dr. GRPO paper](https://huggingface.co/papers/2503.20783) to eliminate length bias.
The value of the constant corresponds to `max_completion_length`.
mask_truncated_completions (`bool`, *optional*, defaults to `False`):
When enabled, truncated completions are excluded from the loss calculation, preventing them from being
incorrectly penalized and introducing noise during training. According to the
[DAPO](https://huggingface.co/papers/2503.14476) paper, this is a good practice for training stability.
sync_ref_model (`bool`, *optional*, defaults to `False`):
Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using
the `ref_model_mixup_alpha` parameter. This synchronization originates from the
[TR-DPO](https://huggingface.co/papers/2404.09656) paper.
ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`):
α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix
between the current policy and the previous reference policy during updates. The reference policy is
updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you
must set `sync_ref_model=True`.
ref_model_sync_steps (`int`, *optional*, defaults to `512`):
Ï„ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how
frequently the current policy is synchronized with the reference policy. To use this parameter, you must
set `sync_ref_model=True`.
top_entropy_quantile (`float`, *optional*, defaults to `1.0`):
Ï parameter from [Beyond the 80/20 Rule](https://huggingface.co/papers/2506.01939). Keeps in the policy
loss term only the top-Ï quantile of tokens by entropy of the probability distribution at each sequence
position, improving results. Range: `[0.0-1.0]`. A value of `0.0` masks all but the highest entropy token;
`1.0` keeps all tokens. The paper recommends a value of `0.2`.
If used with `mask_truncated_completions=True`, only tokens from non-truncated completions are considered.
use_liger_loss (`bool`, *optional*, defaults to `False`):
Whether to use the Liger GRPO loss.
> Parameters that control the logging
log_completions (`bool`, *optional*, defaults to `False`):
Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is installed,
it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`.
num_completions_to_print (`int` or `None`, *optional*, defaults to `None`):
Number of completions to print with `rich`. If `None`, all completions are logged.
wandb_log_unique_prompts (`bool`, *optional*, defaults to `False`):
Whether to log unique prompts in wandb. If `True`, only unique prompts are logged. If `False`, all prompts
are logged.
helpzvLLM SamplingParams)ÚdefaultÚmetadataÚvllm_sampling_paramsrcz8Chunk size to reduce memory usage. -1 is most efficient.Úunsloth_num_chunksFÚnordéréúg-Cëâ6
?g{®Gáz„?gÍÌÌÌÌÌì?g+‡ÙÎ÷ï?g:Œ0âŽyE>rglinearçš™™™™™¹?ÚpassiveÚwarningTÚstepsrkéôiO
ÚO1ÚautoÚrÚ
adamw_8bitÚlengthÚ
every_saveÚlastiéééÚcolocater.z0.0.0.0i@gn@g333333Ó?gü©ñÒMbP?rˆÚtokenrg333333ã?c°± sV|dkr td|dƒ|dkrtd|dƒ|dur(|#dkr(|$dkr(d}d }#|¤ ¡d
kr1d
}¤n|¤ ¡d kr9d }¤|¤ ¡d
krQ|£dkrFd }£n%|£d krPtd
ƒd}£n|¤ ¡d krktdƒtdƒtdƒd }¥d} d}œd}¤||„|„|krƒtdt|ƒdt|„ƒƒ|„}|Šdkrtdƒ|Šdkr“tdƒtƒjdÈid|d|d|d|d|d |d!|d"|d#| “d$|
d%| d&| d'|
d(|d)|d*|d+|d,|d-|d.|d/|d0|d1|d2|d3|d4|d5|d6|d7|d8|d9|d:| “d;|!“d<|"“d=|#“d>|$“d?|%“d@|&“dA|'“dB|(“dC|)“dD|*“dE|+“dF|,“dG|-“dH|.“dI|/“dJ|0“dK|1“dL|2“dM|3“dN|4“dO|5“dP|6“dQ|7“dR|8“dS|9“dT|:“dU|;“dV|<“dW|=“dX|>“dY|?“dZ|@“d[|A“d\|B“d]|C“d^|D“d_|E“d`|F“da|G“db|H“dc|I“dd|J“de|K“df|L“dg|M“dh|N“di|O“dj|P“dk|Q“dl|R“dm|S“dn|T“do|U“dp|V“dq|W“dr|X“ds|Y“dt|Z“du|[“dv|\“dw|]“dx|^“dy|_“dz|`“d{|a“d||b“d}|c“d~|d“d|e“d€|f“d|g“d|h“dƒ|i“d„|j“d…|k“d†|l“d‡|m“dˆ|n“d‰|o“dŠ|p“d|q“dŒ|r“d|s“dŽ|t“d|u“d|v“d|w“d|x“d“|y“d”|z“d•|{“d||“d—|}“d˜|~“d™|dš|€“d›|dœ|‚“d|ƒ“dž|„“dŸ|…“d |†“d¡|‡“d¢|ˆ“d£|‰“d¤|Š“d¥|‹“d¦|Œ“d§|d¨|Ž“d©|dª|d«|‘“d¬|’“d­|““d®|”“d¯|•“d°|–“d±|—“d²|˜“d³|™“d´|š“dµ|›“d¶|œ“d·|d¸|ž“d¹|Ÿ“dº| “d»|¡“d¼|¢“d½|£“d¾|¤“d¿|¥“dÀ|¦“dÁ|§“dÂ|¨“dÃ|©“dÄ|ª“dÅ|«“dÆ|¬“dÇ|­“|°¤Ž|®|_|¯|_ dS)ÉNgH¯¼šò×z>z Unsloth: Your learning rate of `zi` is too small and less than 1e-7! Consider increasing it, otherwise gradient updates will be close to 0!rkza` is way too larger > 1! Consider decreasing it to 1e-1, otherwise gradient updates will explode!r?r@Úunsloth_training_checkpointsr8r—ZdapoTzwUnsloth: The Dr GRPO paper recommends setting `scale_rewards` to False! Will override. Set it to `None` to force False.FzFUnsloth: The DAPO paper recommends `mask_truncated_completions = True`z8Unsloth: The DAPO paper recommends `epsilon_high = 0.28`zMUnsloth: The DAPO paper recommends setting `beta = 0.0` to remove the KL termgìQ¸…ëÑ?rrz}Unsloth: We now expect `per_device_train_batch_size` to be a multiple of `num_generations`.
We will change the batch size of z to the `num_generations` of rzUUnsloth: Please set a positive non-zero temperature since your results will be wrong.é
zgUnsloth: Please set a positive non-zero temperature less than 10, since sampling will be quite erratic.Ú
output_dirÚoverwrite_output_dirÚdo_trainÚdo_evalÚ
do_predictÚ
eval_strategyÚprediction_loss_onlyÚper_device_train_batch_sizeÚper_device_eval_batch_sizeÚper_gpu_train_batch_sizeÚper_gpu_eval_batch_sizeÚgradient_accumulation_stepsÚeval_accumulation_stepsÚ
eval_delayÚtorch_empty_cache_stepsÚ
learning_rateÚ weight_decayÚ
adam_beta1Ú
adam_beta2Ú adam_epsilonÚ
max_grad_normÚnum_train_epochsÚ max_stepsÚlr_scheduler_typeÚ warmup_ratioÚ warmup_stepsÚ log_levelÚlog_level_replicaÚlog_on_each_nodeÚ logging_dirÚlogging_strategyÚlogging_first_stepÚ
logging_stepsÚlogging_nan_inf_filterÚ
save_strategyÚ
save_stepsÚsave_total_limitÚsave_safetensorsÚsave_on_each_nodeÚsave_only_modelÚ'restore_callback_states_from_checkpointÚno_cudaÚuse_cpuÚuse_mps_deviceÚseedÚ data_seedÚ
jit_mode_evalÚuse_ipexÚbf16r
Úfp16_opt_levelÚhalf_precision_backendÚbf16_full_evalÚfp16_full_evalÚtf32Ú
local_rankÚ ddp_backendÚ
tpu_num_coresÚtpu_metrics_debugÚdebugÚdataloader_drop_lastÚ
eval_stepsÚdataloader_num_workersÚdataloader_prefetch_factorÚ
past_indexÚrun_nameÚ disable_tqdmÚremove_unused_columnsÚ label_namesÚload_best_model_at_endÚmetric_for_best_modelÚgreater_is_betterÚignore_data_skipÚfsdpÚfsdp_min_num_paramsÚ fsdp_configÚ"fsdp_transformer_layer_cls_to_wrapÚaccelerator_configÚ deepspeedÚlabel_smoothing_factorÚoptimÚ
optim_argsÚ adafactorÚgroup_by_lengthÚlength_column_nameÚ report_toÚddp_find_unused_parametersÚddp_bucket_cap_mbÚddp_broadcast_buffersÚdataloader_pin_memoryÚdataloader_persistent_workersÚskip_memory_metricsÚuse_legacy_prediction_loopÚ push_to_hubÚresume_from_checkpointÚ hub_model_idÚ hub_strategyÚ hub_tokenÚhub_private_repoÚhub_always_pushÚ hub_revisionÚgradient_checkpointingÚgradient_checkpointing_kwargsÚinclude_inputs_for_metricsÚeval_do_concat_batchesÚ fp16_backendÚpush_to_hub_model_idÚpush_to_hub_organizationÚpush_to_hub_tokenÚ
mp_parametersÚauto_find_batch_sizeÚfull_determinismÚ torchdynamoÚ ray_scopeÚ ddp_timeoutÚ
torch_compileÚtorch_compile_backendÚtorch_compile_modeÚinclude_tokens_per_secondÚinclude_num_input_tokens_seenÚneftune_noise_alphaÚoptim_target_modulesÚbatch_eval_metricsÚ
eval_on_startÚuse_liger_kernelÚliger_kernel_configÚeval_use_gather_objectÚaverage_tokens_across_devicesÚmodel_init_kwargsÚdisable_dropoutÚmax_prompt_lengthÚnum_generationsrŠÚds3_gather_for_generationÚshuffle_datasetÚgeneration_batch_sizeÚsteps_per_generationrŒÚtop_pÚtop_kÚmin_pÚgeneration_kwargsÚrepetition_penaltyÚuse_transformers_pagedÚcache_implementationÚuse_vllmÚvllm_server_base_urlÚ vllm_modeÚvllm_model_implÚvllm_guided_decoding_regexÚvllm_server_hostÚvllm_server_portÚvllm_server_timeoutÚvllm_gpu_memory_utilizationÚvllm_tensor_parallel_sizer«Únum_iterationsÚepsilonrr‰Úimportance_sampling_levelÚreward_weightsÚ
scale_rewardsr…Úmask_truncated_completionsÚsync_ref_modelÚref_model_mixup_alphaÚref_model_sync_stepsÚtop_entropy_quantileÚuse_liger_lossÚlog_completionsÚnum_completions_to_printÚwandb_log_unique_promptsr€)
ÚFloatingPointErrorÚ
OverflowErrorÚlowerÚprintÚstrÚ MathErrorÚsuperÚ__init__r6r7)±ÚselfrOrPrQrRrSrTrUrVrWrXrYrZr[r\r]r^r_r`rarbrcrdrerfrgrhrirjrkrlrmrnrorprqrrrsrtrurvrwrxryrzr{r|r}r~rr
r€rrr„r…r†r‡r‰rrrrrrr“r”r•r–r—r™rrr r­r¿r‹r‰r…r6r7r­©Ú __class__r€rÛs´5     ÿþýüûúùø ÷
ö õ ô
óòñðïîíìëêéèçæåäãâá à!ß"Þ#Ý$Ü%Û&Ú'Ù(Ø)×*Ö+Õ,Ô-Ó.Ò/Ñ0Ð1Ï2Î3Í4Ì5Ë6Ê7É8È9Ç:Æ;Å<Ä=Ã>Â?Á@ÀA¿B¾C½D¼E»FºG¹H¸I·JKµL´M³N²O±P°Q¯R®S­T¬U«VªW©X¨Y§Z¦[¥\¤]£^¢_¡` aŸbžcdœefšgh˜ijklmnopqrŽstŒuvŠwxˆyz{|}ƒ~ÿþýüûúùø ÷
ö õ ô
óòñðïîíìëêéèçæåäãâá à!ß"Þ#Ý$Ü%Û&Ú'Ù(Ø)×*Ö+Õ,Ô-Ó.Ò/
zUnslothGRPOConfig.__init__)
rÿÚ__doc__rYr6rrÚ__annotations__r7ÚintrüÚ
__classcell__r€r€rr2sx
LþþÏr2ceZdZdZddgZ        dPdeeefdeee efde
e d e
ee e
fd
e
ee e
eeee e
fffd e
eeefd e
eee efd
e
e edee
ejje
ejjjfde
dffdd
ZddZddZdQde
e defddZdefddZdede defddZe    dRdd „ƒZ dQd!ej!d"ej!d#e"dej!fd$d%„Z#dSd'd(„Z$dQd)e
e efd*d+„Z%dTd,e&j'd-efd.d/„Z(d,e&j'fd0d1„Z)d2d3„Z*ed4eeeej!e+ffdeeeej!e+fffd5d6„ƒZ,efd7d8„ƒZ-d9e eeeej!e+ffdeeeej!e+ffffd:d;„ Z.d<d=„Z/dUd>d?„Z0d@dA„Z1dQdBe
e efdCdD„Z2dQdEeee"fdFe
e"ddffdGdH„
Z3‡fdIdJ„Z4   dVdKe
edLe
edMeee edffdNdO„Z5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tQƒrutRd!d"„| DƒƒrutNd#ƒˆjTˆ_TˆjUˆ_VˆjWdur†ˆjWnˆjUˆ_Wd
ˆ_Xdˆ_Yd|jZd$<t[ƒj\|ˆt]||||| d%ˆj^ˆ_^ˆj^d&kr±dˆ__n t`|ƒrºdˆ__nt |
¡}tt|jd
ƒ}|j|
fi| ¤Žˆ__ˆjarätb|ƒˆj_durätbˆj_ƒˆjHr tcƒsðtd'ƒtdƒˆ_etfˆj^ˆjVˆjWˆj@ˆj^d&kˆjIˆj>d(ˆ_gtht+ƒtht+ƒd)œˆ_id
ˆ_jˆjkˆ_kˆjlˆ_lˆjmˆ_mtnˆjod*tnˆjod*tnˆjod*th‡fd+d,„ƒtnˆjod*d-œˆ_ptqˆjrdd.ˆjrtsƒsTtd/ƒˆjd0kr†ˆjtjur†ˆjvduriˆjv}n
d1ˆjwd2ˆjx}ty|ˆjzd3ˆ_{ˆj{j|t j} d4nƒˆjdkr ˆjtjˆjGd
ks¤td5ˆjGd6ˆjtjd7ƒˆjGdkrÁt j€ fd8d9„t‚ˆjtjˆjGƒDƒ¡\ˆ_ƒ}tˆjtj„ƒt…j†d:<tˆjtj‡ƒt…j†d;<tˆjtjƒt…j†d<<t…j†  d=d>¡t…j†d=<t…j†  d?d@¡t…j†d?<ˆj=durˆj>durˆj=ˆj>}nd}|jˆˆ_‰ˆjŠˆ_dˆ_Œˆjt ¡n<ˆj>d|j%|jŽ|j&ˆj@ˆjAˆjBˆjCˆjDˆjdAœ }ˆjEr>dB|dC<dD|dE<dF|dG<ˆjdurJ| ‘ˆj¡tdKi|¤Žˆ_“dˆ_”ˆj• –ˆj—¡ˆj_dur†ˆj˜rot™ˆj_ˆjtƒˆ__nˆr|t›ˆj_ˆjtƒˆ__n
ˆjtjœˆj_ddHˆ__ˆjr•ˆ žtŸˆj_ˆjtdI¡t-ˆj3ƒD]&\}}t|t:ƒr¿ˆj˜r³t™|ˆjtƒˆj3|<qšˆjtjœ|dddJˆj3|<qšdS)LNÚ vllm_enginerÝFTrKú/rcz-GRPOÚ torch_dtyperBz‰Invalid `torch_dtype` passed to `GRPOConfig`. Expected either 'auto' or a string representing a `torch.dtype` (e.g., 'float32'), but got Ú.rz¡You passed `model_init_kwargs` to the `GRPOConfig`, but your model is already instantiated. This argument can only be used when the `model` argument is a string.Úget_base_modelz>PEFT is required to use `peft_config`. Run `pip install peft`.zWThe `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`Ú image_tokenÚimage_token_idÚvision_start_token_idÚvision_end_token_idÚ
num_labelsrkzNumber of reward weights (z)) must match number of reward functions (úrzRThe number of reward processing classes must match the number of reward functions.rzOLiger Kernels don't currently support masking token positions based on entropy.rLzwLiger Kernels currently only support token-level importance sampling. Please set`importance_sampling_level` to 'token'.css|]}t|tƒVqdS)Ú
isinstancer)rÚdsr€r€rÚ <genexpr>sz/_UnslothGRPOTrainer.__init__.<locals>.<genexpr>z^Iterable datasets are not yet supported in GRPOTrainer. Please use a standard dataset instead.Úestimate_tokens)rrÚ
data_collatorr r
r r
rrzWLiger is required to use `liger_loss` as the GRPO loss. Run `pip install liger-kernel`.)r‡r‰Ú
use_ref_modelr…)ÚtrainÚeval©Úmaxlencs tˆjdS)Nr$)r*r€)rr€rÚ<lambda>qs z._UnslothGRPOTrainer.__init__.<locals>.<lambda>)ÚimageÚpromptÚ
completionÚrewardsr¬)Údevice_specificzkvLLM is not available and `use_vllm` is set to True. Please install vLLM with `pip install vllm` to use it.Úserverzhttp://ú:)Úbase_urlÚconnection_timeoutrËzvllm_tensor_parallel_size (z) must divide world size (z ) evenly.cs*g|]}tt|ˆj|dˆjƒƒqS)rk)Úlistrr©r€rrsÿÿz0_UnslothGRPOTrainer.__init__.<locals>.<listcomp>ÚRANKÚ
LOCAL_RANKÚ
WORLD_SIZEÚ MASTER_ADDRÚ localhostÚ MASTER_PORTÚ12345) Úmax_new_tokensÚ do_sampleÚ pad_token_idÚ bos_token_idÚ eos_token_idrŒr×rHÚmax_batch_tokensiÚ
num_blocksé€Ú
block_size)Úevaluation_mode)Ú ref_modelr")rBÚdevice_placementr€) rÚgetattrrÝrÚconfigÚ
_name_or_pathÚsplitrrRrr Úfrom_pretrainedrSÚ
architecturesr2Ú signaturerõÚ
parametersÚkeysrÚmodel_kwarg_keysr7Ú ImportErrorr³Ú_enable_gradient_checkpointingrrÚ tokenizerrÚ TypeErrorÚ pad_tokenÚ eos_tokenr;r=rrrrr0Úreward_func_namesÚ enumerater
r@ÚModulerurrÚtensorrqÚonesrorrr r…ÚNotImplementedErrorrÓrÚdictÚanyÚvaluesrçr‡r‰Ú_stepÚ_buffered_inputsÚwarnings_issuedrûr1rCr8r+r6r$Ú_forward_redirectionÚLigerFusedLinearGRPOLossÚliger_grpo_lossr)Ú_metricsÚ_total_train_tokensròr*Ú_logsrMr{r:r"Úis_main_processrÞr#Ú vllm_clientÚinit_communicatorÚcudaÚcurrent_deviceÚ
num_processesÚ distributedÚnew_subgroups_by_enumerationrÚtp_groupÚ
process_indexrBrÚlocal_process_indexrÚllmráÚguided_decoding_regexÚ_last_loaded_stepÚwait_for_everyoner<ÚupdaterÚgeneration_configÚmodel_accepts_loss_kwargsrÚadd_model_tagsÚ
_tag_namesÚis_deepspeed_enabledrEÚis_fsdp_enabledrFÚ
prepare_modelríÚ add_callbackr )rrrr r
r r r
rrÚ
model_namerÎÚmodel_idrrFÚ architecturerQrÚ reward_funcÚreward_processing_classr.Ú
max_model_lenrÙ)rris 





ÿÿ

ÿ ÿý 


  ÿÿ
ÿ" ÿÿ
  
 
ÿÿÿþüüÿ
ø 

 
ÿù 



û ÿ  
ÿÿ 
þ
ÿ õ
     ÿúz_UnslothGRPOTrainer.__init__cCs|jdur ddg|_dSdS)Nr(r')Ú_signature_columnsr1r€r€rÚ _set_signature_columns_if_neededÙs
ÿz4_UnslothGRPOTrainer._set_signature_columns_if_neededcC|jdur tdƒ|j}|j}tƒr t|tjƒr |j|dd}n|j|dd}|j |j
j ||j
j |j
j
|j
jdœ}t|tjjjƒsa| ¡|d<|j
j|d<tt|j
j |j
jd|d<|j
j|d <|j t|fi|¤Ž¡S)
Nz+Trainer: training requires a train_dataset.Útraining)Ú description)Ú
batch_sizeÚ
collate_fnÚ num_workersÚ
pin_memoryÚpersistent_workersÚsamplerÚ drop_last)ÚrankÚworker_init_fnÚprefetch_factor)r r r4rr(rÚ_remove_unused_columnsÚ"_get_collator_with_removed_columnsÚ_train_batch_sizerrRÚutilsÚdatarÚ_get_train_samplerrŠrDrKrprr"Úpreparer)r r Údataloader_paramsr€r€rÚget_train_dataloaderës*
 û  
ÿ z(_UnslothGRPOTrainer.get_train_dataloaderÚdatasetÚreturncCs>|dur|j}t||j|jj|j|j|jj|j|jjdS)N)Ú data_sourceÚmini_repeat_countrŠÚ repeat_countÚshuffler{) r rrr{)rr€r€rr™ s  úz&_UnslothGRPOTrainer._get_train_samplercCst||j|jjdS)N)r r{)rrr{)r
r€r€rÚ_get_eval_sampler-s
ýz%_UnslothGRPOTrainer._get_eval_samplercCsNd|j_t|ƒr|j ¡n| ¡|jpi}d|vp|d}|r%| ¡|S)z-Enables gradient checkpointing for the model.FÚ
use_reentrant)rFÚ use_cacher8Ú
base_modelÚgradient_checkpointing_enabler´Úenable_input_require_grads)rrr´r€r€rrP5s 
ÿz2_UnslothGRPOTrainer._enable_gradient_checkpointingc Ct|ƒr|jj}||dœ} |dur|dur|| d<|dur!|| d<|dur)|| d<|dur1|| d<d|jvr<|d| d<|jd i| ¤Žj}
|
ddddddf}
|
dd| dddf}
|
S)
N)rÚimage_grid_thwÚ pixel_valuesÚpixel_attention_maskÚ image_sizesrrkrcr€)r8rrNÚlast_hidden_state) Úunwrapped_modelr©rrÚ model_inputsr­r€r€rÚ_get_last_hidden_stateKs" 

 z*_UnslothGRPOTrainer._get_last_hidden_stateÚ entropiesrªÚ thresholdc
Csd|| ¡ ¡}| ¡dkrtj|tjdS|j |¡}t ||¡}|| ¡}||k} | | ¡@S)
Returns a binary mask identifying tokens whose entropy exceeds a given quantile threshold.
Args:
entropies (`torch.Tensor`):
Tensor of shape (batch_size, seq_len) with per-token entropy values.
mask (`torch.Tensor`):
Binary mask of the same shape as `entropies`, where `1` indicates valid tokens and `0` padding.
threshold (`float`):
Quantile threshold between `0.0` and `1.0` to select high-entropy tokens.
Returns:
`torch.Tensor`:
Boolean mask of shape (batch_size, seq_len), where `True` indicates tokens with entropy >= threshold and
`False` otherwise.
rr)ÚboolÚfloatÚnumelrRÚ
zeros_liker"r-Úquantile)
r"Únon_pad_entropiesÚall_non_pad_entropiesÚentropy_thresholdÚmasked_entropiesÚ entropy_maskr€r€rÚget_high_entropy_maskvs     z)_UnslothGRPOTrainer.get_high_entropy_maskFc Os dS)NTr)
rrBrrRrrrrr rwÚtrl.trainer.utilsr,) rrrÚcompute_entropyrr­rwr,r€r€rÚ"_get_per_token_logps_and_entropies“sz6_UnslothGRPOTrainer._get_per_token_logps_and_entropiesÚextra_prefixescCs,|pg}dg|}|D]}| |d¡}q |S)Nz_checkpoint_wrapped_module.rC)Úreplace)ÚnamerÁÚprefixesÚprefixr€r€rÚ_fix_param_name_to_vllm½s

z+_UnslothGRPOTrainer._fix_param_name_to_vllmÚmodulerÅc
Cs|durtƒ}| ¡D]\}}|r|d|n|}|j|||dq t|tƒrtj|dddH| ¡D]:\}}|rB|d|n|} |j| dgd} | |vrQq5| | ¡|j dkrh|j
j rh|j  
| |j¡q5|j d kro q5WdƒdS1s{wYdSdS)
zdMemory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM.Nr)ÚvisitedF)ÚrecurseÚ writebackz_fsdp_wrapped_module.)r,rK)ÚsetÚnamed_childrenÚ_sync_fsdp1_params_to_vllmrrÚsummon_full_paramsÚnamed_parametersrÆÚaddrßr"rgrhÚupdate_named_paramr˜)
Ú
child_nameÚ child_moduleÚ child_prefixÚ
param_nameÚparamÚ full_namer€r€rÄs0ÿ


ò"ÿÿz._UnslothGRPOTrainer._sync_fsdp1_params_to_vllmcCsd| ¡D]+\}}|jr| t d¡¡}| ¡}|jdkr(|jjr(|j  
||¡q|jdkr/ qdS)Nrjr,rK) ÚitemsÚis_cpurprRÚ full_tensorrßr"rgrh)r€r€rÚ_sync_fsdp2_params_to_vllmás
õz._UnslothGRPOTrainer._sync_fsdp2_params_to_vllmcOsdSr€)rr­r€r€rÚ_move_model_to_vllmðsz'_UnslothGRPOTrainer._move_model_to_vllmÚgeneration_batchcCst|dƒrt|jjjjddƒr|j ¡|jjrdnd}|dkra|j j
|j }|j |dks3|j
durO| |¡}t|ƒ}t|ƒ}t||j j
ƒ}dd|Dƒ|_
|j
|j |j j
}|j d 7_ n| |¡}t|dƒr€t|jjjjddƒr€|j tj d
d ¡¡|S) NrrÚenable_sleep_modeFr"r#rcSsg|]}t|ƒqSr€)rT)rÚbatchr€r€rróz7_UnslothGRPOTrainer._prepare_inputs.<locals>.<listcomp>rkZVLLM_SLEEP_MODE)rrErrÚ
llm_engineZ vllm_configÚ model_configÚwake_uprrˆrr^r_Ú_generate_and_score_completionsrOrNrPÚsleeprBr)ÚmodeÚgenerate_everyÚgeneration_batchesÚinputsr€r€rÚ_prepare_inputsòs&




z#_UnslothGRPOTrainer._prepare_inputsc
s,|jj}tjt|ƒt|jƒ|d}ddˆdDƒ}fdd|Dƒ}|j|d<tt|j|j |j
ƒƒD]Ÿ\} \}
} t || ƒt |
t
jƒr¢tˆdƒr`ddt||ƒDƒ} fd d| Dƒ}
n
d
dt||ƒDƒ}
ˆ|
d d d
dd}tƒ |¡}t ¡|
di|¤Žjdddf|dd| f<Wdƒn1sœwYn!|
d|||dœ|¤Ž}dd|Dƒ}tj|tj|d|dd| f<Wdƒn1sÍwYq3t |¡jdd ¡rt |¡jddjd dddfdd| ¡Dƒ}|ˆ|d<|ˆ|d<t d|d¡t|ƒ}|S)NrËcSsg|]}|dvr|qS))r(r)Úcompletion_idsr€)rÚkeyr€r€rr!óz:_UnslothGRPOTrainer._calculate_rewards.<locals>.<listcomp>rcs i|] ˆfddˆDƒqS)csg|]}|ˆqSr€r€©rÚexample©r€rr"zE_UnslothGRPOTrainer._calculate_rewards.<locals>.<dictcomp>.<listcomp>r€)r)rÚ
<dictcomp>"s z:_UnslothGRPOTrainer._calculate_rewards.<locals>.<dictcomp>Ú
trainer_statecSsg|]
\}}d||iqS)Úmessagesr€©rÚcr€r€rr-rcsg|] }t|ˆƒdqS©Útext)r%©rÚx)r€rr.ócSsg|]\}}||qSr€r€r€r€rr0ÚptTÚrightF©Úreturn_tensorsÚpaddingÚ padding_sideÚadd_special_tokens)ÚpromptsÚ completionsrëcSsg|] }|dur
|ntjqS)rRÚnan)rÚrewardr€r€rr<ó©rrkrj)Úas_tuplecsi|] \}}||ˆqSr€r€)rÚvalue)Ú nan_row_idxr€rCr(r)z=All reward functions returned None for the following kwargs: zI. Please ensure that at least one reward function returns a valid reward.r€)r"rRrrÚstaterVror rUrHrr@rWr3rwrXrqÚisnanÚallr\ÚnonzerorØrVÚwarnr-)rrÚcompletion_ids_listrÌÚrewards_per_funcrMÚ
reward_kwargsrrÚreward_func_nameróÚtextsÚ
reward_inputsÚoutput_reward_funcÚrow_reward_kwargsrþ)r rÚ_calculate_rewardssT
ÿ   
ÿ 
*ÿÿÿì"  
ÿz&_UnslothGRPOTrainer._calculate_rewardsrécIs€ˆjjˆjjr
dnd}dd|Dƒ}t |¡}i}d|dv}|rrdd|Dƒ}dd d|Dƒi}|D]=}t|tƒrq|D]3} t| tƒsEq=|   d
¡}
|   d ¡} t|
t
ƒrp| d krdd
did|
dœg| d
<q=| dkrpd|
dœg| d
<q=q4‡fdd|Dƒ} ˆj dd| dddddœ|¤Ž}
t ƒ 
|
¡}
|
d|
d}}ˆjdurÕ|ddˆj df}|ddˆj df}ˆj j|ddd} ˆj jfddˆdurÕ‡fdd| Dƒ} ˆjr¦ˆjjˆjkr鈠¡ˆjjˆ_ˆjdkr|t| ƒ}|rùt|ƒ}ˆjjrV|ddˆj}|r|ddˆj}nd}tˆdƒ3ˆjj||ˆjˆjˆjˆjˆj dur/dn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ˆj€d] t| ƒ¡ˆj€d^ t|4ƒ¡t|ˆj}ƒD]\}C}Gˆj€d_|G |8dd|Cf ‚¡¡qIˆj€d` |> ‚¡¡|rxˆj€d t|ƒ¡||||)|=daœ}H|1dur‰|1|Hdb<|3dur|3|Hdc<dD|
vr|
dD|HdD<dE|
vr¨|
dE|HdE<dF|
vr³|
dF|HdF<dG|
vr¾|
dG|HdG<|HS)eNr"r#cSsg|]}|dqS©r(r€r€r€rrVzG_UnslothGRPOTrainer._generate_and_score_completions.<locals>.<listcomp>r'rcSsg|]}| d¡qS)r')r€r€rrcsÚimagescSsg|]}|gqSr€r€)rÚimgr€r€rrdóÚcontentÚroleÚuserr!)r!Úsystemcsg|]
}t|ˆjƒdqSr)r<r r1r€rrrrleftFrþr)Úskip_special_tokensÚclean_up_tokenization_spacescs"| ˆ¡r| ˆ¡}| ˆ¡s|S)Ú
startswithÚ removeprefixr÷)rSr€rÚstrip_leading_tokensˆs


ÿzQ_UnslothGRPOTrainer._generate_and_score_completions.<locals>.strip_leading_tokenscsg|]}ˆ|ƒqSr€r€)r)r'r€rrŽsÿr,z
vLLM.generatercr) rrÚnrÚÚ
max_tokensrs)Ú from_processrkrK)Úregex)r(r×r)Úguided_decodingcSóg|]}dqSr€©rr„r€r€rrÜó)ÚgroupcSóg|] }|D]}|qqSr€r€)rÚsublistrõr€r€rrÞcSr-r€r.r€r€rrár/cSr1r€r€)rr2rr€r€rrã)r(Úmulti_modal_dataZgrpo_trainer_lora_model)Ú load_tensors)r0Úuse_tqdmÚ lora_requestcSsg|] }|jD]}|jqqSr€)ÚoutputsÚ token_ids)rr7Úoutputr€r€rr÷rcóg|] }tj|ˆdqS©©rRrX©rÚidsrËr€rr)Ú
padding_valuerjÚpaged_attentionÚ
sdpa_pagedztransformers.generate_batch)Úgather_deepspeed3_params))rwÚ progress_barcSsg|]}|jqSr€)Úgenerated_tokens)rr9r€r€rr rcr:r;r<r=r€rr!)r?rcr:r;r<r=r€rr#ztransformers.generate)rwÚdisable_compilercSs$g|]\}}ddt||ƒDƒqS)cSsg|]
\}}|r| ¡qSr€)Úitem)rÚidÚmr€r€rrErzR_UnslothGRPOTrainer._generate_and_score_completions.<locals>.<listcomp>.<listcomp>)ro)rÚrowÚmask_rowr€r€rrDsÿrª)))r#Ú assistantrC)rrg-Cëâ6
num_tokenszcompletions/mean_lengthzcompletions/min_lengthzcompletions/max_lengthzcompletions/clipped_ratioz"completions/mean_terminated_lengthz!completions/min_terminated_lengthz!completions/max_terminated_lengthúrewards/ú/meanú/stdrÚ
reward_stdÚfrac_reward_zero_stdr(r)r*)Ú
prompt_idsÚ prompt_maskrër'Úold_per_token_logpsÚref_per_token_logpsr€)ƒr"rrˆr'Údeepcopyrr0r[r Ú batch_decoderSr Ú global_steprtr.rgrHrhÚgeneraterÚr×rsrrr&ÚslicerpÚGuidedDecodingParamsrvr-rrRrmÚall_gather_objectrororurrÚ load_loraÚget_rankrCr;ÚcatrÛÚ
model_wrappedrFÚ_attn_implementationr5rUr|rrArrprr
rÚgenerate_batchr©rwr]r=ÚfullÚlongrÚargmaxr\ÚarangeÚexpandrrr rVrWrZrCr#r$r3ÚpoprÚnansumÚviewr¡ÚstdÚiscloser¶Úrepeat_interleaverëÚcloneÚnum_input_tokens_seenr-rFrdr´r•r“rVrUÚnanmeanr?rfÚextendÚtolist)IrýrÚoriginal_promptsr­Ú
has_imagesrr(ÚmessagerrÚ prompts_textÚ
prompt_inputsrRrSÚall_prompts_textÚ
all_imagesÚordered_set_of_promptsÚordered_set_of_imagesrëÚ
process_slicer,r0Ú orig_sizeÚgathered_promptsÚgathered_imagesÚ vllm_inputsr'Ú all_outputsÚlocal_rank_in_groupÚtp_sliceÚprompt_completion_idsÚpaged_prompt_inputsÚ
previous_attnr®Ú
prompt_lengthÚis_eosÚeos_idxÚsequence_indicesr'rÚcompletion_lengthsÚtruncated_completionsrrrTr„rUÚcompletions_textrr)Ú bootstraprr*Úmean_grouped_rewardsÚstd_grouped_rewardsÚ is_std_zeror¬Úall_process_advantagesÚagg_completion_lengthsÚagg_terminated_with_eosÚterm_completion_lengthsÚclipped_completions_ratiorrÚ mean_rewardsÚ std_rewardsrÃr9)rSr'rPs
 




ûú 
ÿ 
ÿ
 
 õÿ þ  ø
  
ü "ÿ 
 
ÿÿþûú

 

ÿÿó ÿÿþûúÿ ÿ÷

"("ÿ


 ÷   ÷  ÷ÿ
Î5"þ þ
$         (û


 
 
 
 z3_UnslothGRPOTrainer._generate_and_score_completionsc Cs<|d|d}}|d|d}}tj||gdd}tj||gdd}| d¡} | |||| | d¡| d¡| d ¡| d
¡¡}
|j|
|jj|||d |jj| d ¡| d
¡d\} } |j dkre| dnd}
| d}|j
j rqdnd}|j dkrŠ|j |d 
|j |
¡ ¡ ¡¡|j |d 
|j |¡ ¡ ¡¡| S)NrRrSr'rkrjrTrU)Ú_inputÚ
lin_weightÚselected_token_idsrÚbiasrTrUrrrcr"r#ÚklÚ
clip_ratio)rRr_rcrrrˆrdrur"r-rF)rRrSr'rrr­Úmetricsr¾r€r€rÚcompute_liger_lossïs@
ø 
ø 
$$z&_UnslothGRPOTrainer.compute_liger_losscsP|rtdƒ|d|d}}|d|d}}tj||gdd} | j\}
} tj||gdd} | d¡}
| }|
}d(‡fd d
„ }||| | |
ƒ}ˆjd kr}t ¡%| ¡||| | |
ƒ}}Wdƒn1shwYWdƒn1swwYnd}|d }| d
d¡}| dd|
df} t |j
ddƒ}|dur¡d}t |j
ddƒ}|dur®d}t |j
ddƒ}|dur»d}|dur|durÑ|ddddddf}|ddddddf}t |||| |ˆj|ˆj j
ˆjˆjˆj jˆj jˆj j|||d\}}}ngtˆj dƒrPtd)idˆd|d|
d|d |d|dˆj jdˆj j
dˆjdˆjdˆj jdˆj jdˆj jd|d |d!|d"| Ž\}}}ntˆ||
|||ˆj jˆj j|||| d# \}}} d$ˆjvr’ˆjjrvd%nd$}ˆj|d& | ¡¡ˆj|d' | ¡¡|Sˆjd& | ¡¡ˆjd' | ¡¡|S)*Nz2The GRPOTrainer does not support returning outputsrRrSr'rkrjFcs2tˆdƒr
ˆ ||||¡Sˆ ||||||¡dS)_get_per_token_logpsr)r)rrrr¿r1r€rr&) sÿz2_UnslothGRPOTrainer.compute_loss.<locals>.<lambda>rrTÚfinal_logit_softcappingrÚ logit_scaleÚlogits_scalingrc) r…r‡r‰r‹rrr…r&rr‡r‰r‹rrr) r&rr'rrrr"r#r©NFr€)rRr_rnr$rErFr,rr…r‡r‰rrr+r7rdÚcontrolÚshould_evaluaterurF)rÚreturn_outputsÚnum_items_in_batchrRrSr'rr(rrÚ_logits_to_keepÚget_logps_funcrrUrrr€r1r 

 ÿ
ÿ    
ðÿþýüûúùø ÷
ö õ ô
óòñð ï ô þz _UnslothGRPOTrainer.compute_lossc% s6|d|d}}|d|d}tj||gdd}tj|ˆgdd}| d¡}|j||||d| d¡| d ¡| d
¡| d ¡d \} }
|jd
krU| |
ˆd|j¡} nd} |jdkrm|d} t | | ¡| | d}
|d}| d¡}|dur~|   ¡n|}| |}|j
dkrŒ|}n$|j
dkr§|ˆ  d¡ˆ  d¡j d
d}| 
d¡}n td|j
dƒt |¡}t  |d|jd|j¡}|jjdurÑtj ||jjd}|| 
d¡}|| 
d¡}t ||¡ }| durî|| }|jdkrú||j|
}|jdkr|ˆ  d¡ˆ  d¡j d
d ¡}n2|jdkr(|ˆ  ¡ˆ  ¡j d
d}n|jdkr=|ˆ  ¡| d¡|j}ntd|jƒ|jjrLdnd}ˆ  ¡j d
dfd d!„}|jdkry||
ƒ}|j|d" |j |¡ ¡ ¡¡||
ƒ}|j|d# |j |¡ ¡ ¡¡|d|jk|