TRL documentation
IW-OPD
IW-OPD
Trong bài báo On the Position Bias of On-Policy Distillation, các tác giả giới thiệu Importance-Weighted On-Policy Distillation (IW-OPD). IW-OPD giải quyết vấn đề thiên vị vị trí trong on-policy distillation bằng cách gán lại trọng số cho các cập nhật token được lấy mẫu dựa trên độ lệch tiền tố giữa teacher và student tích lũy. Các token đầu giữ trọng số lớn hơn, trong khi các token sau có độ trôi cao sẽ bị giảm trọng số.
Để sử dụng IW-OPD, bạn có thể dùng lớp experimental.iw_opd.IWOPDTrainer trong trl.experimental.iw_opd.
IW-OPD hiện là một phần của namespace
trl.experimental. Các API có thể thay đổi mà không cần thông báo trong khi tính năng đang được cải tiến.
Cách sử dụng
from trl.experimental.iw_opd import IWOPDConfig, IWOPDTrainer
training_args = IWOPDConfig(
distillation_objective="iw_opd",
iw_opd_gamma=0.5,
)
trainer = IWOPDTrainer(
model="Qwen/Qwen3-0.6B",
teacher_model="...",
train_dataset=...,
args=training_args,
)
trainer.train()IW-OPD là một mục tiêu on-policy: distillation_objective="iw_opd" yêu cầu lmbda=1.0 (mặc định). iw_opd_gamma là hệ số khuếch đại trọng số quan trọng từ Thuật toán 1 của bài báo.
IWOPDTrainer
lớp trl.experimental.iw_opd.IWOPDTrainer
< source >( model: typing.Union[transformers.modeling_utils.PreTrainedModel, torch.nn.Module, str, NoneType] = Noneteacher_model: typing.Union[transformers.modeling_utils.PreTrainedModel, torch.nn.Module, str] = Noneargs: trl.experimental.iw_opd.iw_opd_config.IWOPDConfig | None = Nonedata_collator: collections.abc.Callable[[list[typing.Any]], dict[str, typing.Any]] | None = Nonetrain_dataset: datasets.arrow_dataset.Dataset | None = Noneeval_dataset: datasets.arrow_dataset.Dataset | dict[str, datasets.arrow_dataset.Dataset] | None = Noneprocessing_class: transformers.tokenization_utils_base.PreTrainedTokenizerBase | transformers.image_processing_utils.BaseImageProcessor | transformers.feature_extraction_utils.FeatureExtractionMixin | transformers.processing_utils.ProcessorMixin | None = Nonecompute_metrics: collections.abc.Callable[[transformers.trainer_utils.EvalPrediction], dict] | None = Nonecallbacks: list[transformers.trainer_callback.TrainerCallback] | None = Noneoptimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None)preprocess_logits_for_metrics: collections.abc.Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = Nonepeft_config: typing.Optional[ForwardRef('PeftConfig')] = None )
Trainer cho Importance-Weighted On-Policy Distillation (IW-OPD).
IW-OPD (Về thiên vị vị trí của Chưng cất On-Policy) gán lại trọng số cho tín hiệu chưng cất token được lấy mẫu bằng sự khác biệt tiền tố tích lũy giữa teacher và student, giảm trọng số cho các token muộn hơn mà sự giám sát của chúng đã trôi ra ngoài phân phối. Chọn nó bằng distillation_objective=“iw_opd”.
Trainer này là một bản chụp đóng băng của
DistillationTrainertrước khi tái cấu trúc, được giữ lại làm nơi chứa IW-OPD (một phương pháp chính sách gradient có sự hướng dẫn của giáo viên, không phù hợp vớiDistillationTrainerổn định, toàn bộ bảng từ vựng). Nó không được bảo trì chủ động và sẽ không theo dõi các cải tiến sau này của trainer đó.
Hỗ trợ:
- Mất JSD tổng quát (KL thuận, KL nghịch, hoặc JSD nội suy qua beta)
- Mục tiêu IW-OPD cho token được lấy mẫu (distillation_objective=“iw_opd”)
- Trộn on-policy / off-policy thông qua lmbda (được đệm qua tích lũy gradient)
- Mô hình giáo viên cục bộ hoặc giáo viên bên ngoài thông qua máy chủ vLLM
- Tạo dữ liệu on-policy của Student bằng vLLM hoặc model.generate()
train
< source >( resume_from_checkpoint: str | bool | None = Nonetrial: optuna.Trial | dict[str, Any] | None = Noneignore_keys_for_eval: list[str] | None = None ) → ~trainer_utils.TrainOutput
Tham số
- resume_from_checkpoint (
strhoặcbool, tùy chọn) — Nếu làstr, đường dẫn cục bộ đến một checkpoint đã lưu bởi một phiênTrainertrước đó. Nếu làboolvà bằngTrue, tải checkpoint cuối cùng trong args.output_dir do một phiênTrainertrước đó lưu lại. Nếu có, quá trình huấn luyện sẽ tiếp tục từ trạng thái model/optimizer/scheduler được tải ở đây. - trial (
optuna.Trialhoặcdict[str, Any], tùy chọn) — Lần chạy thử nghiệm hoặc từ điển siêu tham số cho việc tìm kiếm siêu tham số. - ignore_keys_for_eval (
list[str], tùy chọn) — Một danh sách các khóa trong đầu ra của mô hình của bạn (nếu đó là một từ điển) cần được bỏ qua khi thu thập các dự đoán để đánh giá trong quá trình huấn luyện.
Trả về
~trainer_utils.TrainOutput
Đối tượng chứa số bước toàn cục, tổn thất huấn luyện và các chỉ số.
Điểm vào chính cho quá trình huấn luyện.
Sẽ lưu mô hình, để bạn có thể tải lại bằng from_pretrained().
Chỉ lưu từ tiến trình chính.
push_to_hub
< source >( commit_message: str | None = 'End of training'blocking: bool = Truetoken: str | None = Nonerevision: str | None = Noneprivate: bool | None = None**kwargs )
Tham số
- commit_message (
str, tùy chọn, mặc định là"End of training") — Thông điệp để commit khi đẩy lên. - blocking (
bool, tùy chọn, mặc định làTrue) — Xác định xem hàm có chỉ trả về khigit pushđã hoàn tất hay không. - token (
str, tùy chọn, mặc định làNone) — Token có quyền ghi để ghi đè lên các args gốc của Trainer. - revision (
str, tùy chọn) — Phiên bản git để commit từ. Mặc định là đầu của nhánh “main”. - private (
bool, tuỳ chọn) — Xác định xem có đặt kho thành riêng tư khi tạo hay không. Mặc định làargs.hub_private_repo. Không có tác dụng nếu kho đã tồn tại. - kwargs (
dict[str, Any], tùy chọn) — Các đối số từ khóa bổ sung được truyền đến~Trainer.create_model_card.
Tải self.model và self.processing_class lên 🤗 model hub tại repo self.args.hub_model_id.
IWOPDConfig
lớp trl.experimental.iw_opd.IWOPDConfig
< source >( output_dir: str | None = Noneper_device_train_batch_size: int = 8num_train_epochs: float = 3.0max_steps: int = -1learning_rate: float = 1e-06lr_scheduler_type: transformers.trainer_utils.SchedulerType | str = 'linear'lr_scheduler_kwargs: dict | str | None = Nonewarmup_steps: float = 0optim: transformers.training_args.OptimizerNames | str = 'adamw_torch_fused'optim_args: str | None = Noneweight_decay: float = 0.0adam_beta1: float = 0.9adam_beta2: float = 0.999adam_epsilon: float = 1e-08optim_target_modules: None | str | list[str] = Nonegradient_accumulation_steps: int = 1average_tokens_across_devices: bool = Truemax_grad_norm: float = 1.0label_smoothing_factor: float = 0.0bf16: bool | None = Nonefp16: bool = Falsebf16_full_eval: bool = Falsefp16_full_eval: bool = Falsetf32: bool | None = Noneactivation_checkpointing: bool | None = Noneactivation_checkpointing_kwargs: dict[str, typing.Any] | str | None = Nonegradient_checkpointing: bool | None = Nonegradient_checkpointing_kwargs: dict[str, typing.Any] | str | None = Nonetorch_compile: bool = Falsetorch_compile_backend: str | None = Nonetorch_compile_mode: str | None = Noneuse_liger_kernel: bool = Falseliger_kernel_config: dict[str, bool] | None = Noneuse_cache: bool = Falseneftune_noise_alpha: float | None = Nonetorch_empty_cache_steps: int | None = Noneauto_find_batch_size: bool = Falselogging_strategy: transformers.trainer_utils.IntervalStrategy | str = 'steps'logging_steps: float = 10logging_first_step: bool = Falselog_on_each_node: bool = Truelogging_nan_inf_filter: bool = Trueinclude_num_input_tokens_seen: str | bool = 'no'log_level: str = 'passive'log_level_replica: str = 'warning'disable_tqdm: bool | None = Nonereport_to: None | str | list[str] = 'none'run_name: str | None = Noneproject: str = 'huggingface'trackio_space_id: str | None = Nonetrackio_bucket_id: str | None = Nonetrackio_static_space_id: typing.Union[str, NoneType, typing.Literal[False]] = Noneeval_strategy: transformers.trainer_utils.IntervalStrategy | str = 'no'eval_steps: float | None = Noneeval_delay: float = 0per_device_eval_batch_size: int = 8prediction_loss_only: bool = Falseeval_on_start: bool = Falseeval_do_concat_batches: bool = Trueeval_use_gather_object: bool = Falseeval_accumulation_steps: int | None = Noneinclude_for_metrics: list[str] = <factory>batch_eval_metrics: bool = Falsesave_only_model: bool = Falsesave_strategy: transformers.trainer_utils.SaveStrategy | str = 'steps'save_steps: float = 500save_on_each_node: bool = Falsesave_total_limit: int | None = Noneenable_jit_checkpoint: bool = Falsepush_to_hub: bool = Falsehub_token: str | None = Nonehub_private_repo: bool | None = Nonehub_model_id: str | None = Nonehub_strategy: transformers.trainer_utils.HubStrategy | str = 'every_save'hub_always_push: bool = Falsehub_revision: str | None = Noneload_best_model_at_end: bool = Falsemetric_for_best_model: str | None = Nonegreater_is_better: bool | None = Noneignore_data_skip: bool = Falserestore_callback_states_from_checkpoint: bool = Falsefull_determinism: bool = Falseseed: int = 42data_seed: int | None = Noneuse_cpu: bool = Falseaccelerator_config: dict | str | None = Noneparallelism_config: accelerate.parallelism_config.ParallelismConfig | None = Nonedataloader_drop_last: bool = Falsedataloader_num_workers: int = 0dataloader_pin_memory: bool = Truedataloader_persistent_workers: bool = Falsedataloader_prefetch_factor: int | None = Nonedataloader_multiprocessing_context: str | None = Nonedataloader_in_order: bool = Trueremove_unused_columns: bool = Truelabel_names: list[str] | None = Nonetrain_sampling_strategy: str = 'random'length_column_name: str = 'length'ddp_find_unused_parameters: bool | None = Noneddp_bucket_cap_mb: int | None = Noneddp_broadcast_buffers: bool | None = Noneddp_static_graph: bool | None = Noneddp_backend: str | None = Noneddp_timeout: int = 1800fsdp: str | None = Nonefsdp_config: dict[str, typing.Any] | str | None = Nonedeepspeed: dict | str | None = Nonedebug: str | list[transformers.debug_utils.DebugOption] = ''skip_memory_metrics: bool = Truedo_train: bool = Falsedo_eval: bool = Falsedo_predict: bool = Falseresume_from_checkpoint: str | None = Nonelocal_rank: int = -1model_init_kwargs: dict[str, typing.Any] | str | None = Nonetrust_remote_code: bool = Falsemax_length: int | None = 1024temperature: float = 1.0lmbda: float = 1.0beta: float = 1.0distillation_objective: str = 'iw_opd'iw_opd_gamma: float = 0.5iw_opd_epsilon: float = 1e-08reverse_kl_top_1_mode: str = 'sampled'max_completion_length: int = 512max_prompt_length: int | None = Nonedisable_dropout: bool = Trueteacher_model_name_or_path: str | None = Noneteacher_model_revision: str | None = Noneteacher_model_init_kwargs: dict[str, typing.Any] | str | None = Noneuse_teacher_server: bool = Falseteacher_model_server_url: str | None = Noneloss_top_k: int = 1loss_add_tail: bool = Truenum_generations: int = 1generation_batch_size: int | None = Nonetop_p: float = 0.95top_k: int = 0use_vllm: bool = Falsevllm_mode: str = 'colocate'vllm_server_base_url: str | None = Nonevllm_server_host: str = '0.0.0.0'vllm_server_port: int = 8001vllm_server_timeout: float = 240.0vllm_group_port: int = 51216vllm_gpu_memory_utilization: float = 0.3vllm_tensor_parallel_size: int = 1vllm_max_model_length: int | None = Nonevllm_model_impl: str = 'vllm'vllm_structured_outputs_regex: str | None = Nonevllm_sync_frequency: int = 1vllm_enable_sleep_mode: bool = Falselog_completions: bool = Falselog_completions_steps: int = 100num_completions_to_print: int | None = None )
Các tham số điều khiển mô hình
- model_init_kwargs (
dict[str, Any], tùy chọn) — Các đối số dạng từ khóa choAutoModelForCausalLM.from_pretrained, được sử dụng khi đối sốmodelcủa trainer được cung cấp dưới dạng chuỗi. Giá trịrevisioncũng được sử dụng khi nạp lớp xử lý. - trust_remote_code (
bool, tùy chọn, mặc định làFalse) — Có cho phép tải các model và tokenizer có kèm theo mã Python tùy chỉnh từ Hub hay không. Tham số này được chuyển tiếp đến from_pretrained và from_pretrained, cho cả student lẫn teacher. - max_length (
inthoặcNone, tùy chọn, mặc định là1024) — Độ dài tối đa của toàn bộ chuỗi (prompt + completion) để thực hiện tokenization và cắt ngắn.
Các tham số kiểm soát quá trình chưng cất
- temperature (
float, tùy chọn, mặc định là1.0) — Nhiệt độ cho việc lấy mẫu trong quá trình sinh và cho việc tính toán tổn thất chưng cất. Các giá trị cao hơn tạo ra các phân phối xác suất mềm hơn. - lmbda (
float, tuỳ chọn, mặc định là1.0) — Xác suất sử dụng dữ liệu on-policy (do sinh viên tạo ra) cho mỗi lát tích lũy gradient. Giá trị0.0có nghĩa là hoàn toàn off-policy (chỉ dùng các phần hoàn thành từ tập dữ liệu),1.0có nghĩa là hoàn toàn on-policy. - beta (
float, tùy chọn, mặc định là1.0) — Hệ số nội suy cho tổn thất Divergence Jensen-Shannon tổng quát. Khi0.0, tổn thất là divergence KL thuận. Khi1.0, tổn thất là divergence KL nghịch. Khi0.5, đó là JSD chuẩn. - distillation_objective (
str, tùy chọn, mặc định là"iw_opd") — Mục tiêu cần tối ưu."iw_opd"sử dụng mục tiêu Importance-Weighted On-Policy Distillation cho các token được lấy mẫu."jsd"giữ nguyên mục tiêu JSD/KL tổng quát. - iw_opd_gamma (
float, tùy chọn, mặc định là0.5) — Khuếch đại trọng số quan trọng chodistillation_objective="iw_opd". - iw_opd_epsilon (
float, tuỳ chọn, mặc định là1e-8) — Bộ ổn định được sử dụng khi chuẩn hóa trọng số tiền tố IW-OPD. - reverse_kl_top_1_mode (
str, tùy chọn, mặc định là"sampled") — Quy tắc chọn token top-1 cho reverse-KL khibeta > 0vàloss_top_k == 1."sampled"sử dụng token hoàn thành thực tế trong batch."argmax"sử dụng token có xác suất cao nhất của student. Cài đặt này không ảnh hưởng đến support của forward-KL, vốn luôn sử dụng token top-1 của teacher. Bị bỏ qua khibeta == 0hoặcloss_top_k != 1. - max_completion_length (
int, tùy chọn, mặc định là512) — Số lượng token tối đa được tạo ra cho mỗi completion trong quá trình on-policy generation. - max_prompt_length (
inthoặcNone, tùy chọn) — Số lượng token tối đa cho prompt. Nếu làNone, giá trị này sẽ được tự động tính bằngmax_length - max_completion_length. Các prompt sẽ bị cắt ngắn theo cài đặttruncation_sidecủa tokenizer. - disable_dropout (
bool, tùy chọn, mặc định làTrue) — Có vô hiệu hóa dropout trong mô hình sinh viên trong quá trình huấn luyện hay không.
Các tham số kiểm soát mô hình teacher
- teacher_model_name_or_path (
strhoặcNone, tùy chọn) — Tên hoặc đường dẫn của mô hình teacher. Được sử dụng khi teacher được tải cục bộ. - teacher_model_revision (
strhoặcNone, tùy chọn) — Phiên bản của mô hình teacher (ví dụ: tên nhánh, tag, hoặc commit hash). - teacher_model_init_kwargs (
dict[str, Any]hoặcNone, tùy chọn) — Các đối số dạng từ khóa được truyền vàoAutoModelForCausalLM.from_pretrainedkhi khởi tạo mô hình teacher từ một chuỗi. - use_teacher_server (
bool, tùy chọn, mặc định làFalse) — Liệu có sử dụng máy chủ giáo viên vLLM bên ngoài thay vì mô hình giáo viên cục bộ hay không. - teacher_model_server_url (
strhoặcNone, tùy chọn) — URL gốc của một máy chủ vLLM lưu trữ mô hình teacher (ví dụ:"http://localhost:8000"). Khi được đặt, logprobs của teacher sẽ được lấy từ máy chủ thay vì chạy một bước forward cục bộ khiuse_teacher_server=True. - loss_top_k (
int, tùy chọn, mặc định là1) — Số lượng token hàng đầu được sử dụng khi tính toán tổn thất JSD/KL. Cả phân phối của student và teacher đều bị giới hạn trong K token này và được chuẩn hóa lại trước khi tính độ phân kỳ. Nếu bằng 0, toàn bộ từ vựng sẽ được sử dụng. Đối với teacher cục bộ, quy tắc hỗ trợ chung là top-k của teacher cho KL thuận, top-k của student cho KL nghịch, và phần hợp cho JSD hỗn hợp. Khibeta > 0vàloss_top_k == 1, phần hỗ trợ thuận vẫn sử dụng token top-1 của teacher, trong khi token top-1 nghịch được điều khiển bởireverse_kl_top_1_mode. Khiuse_teacher_server=True, đường dẫn thuần thuận (beta=0) yêu cầu giá trị này phải dương và sử dụng logprobs top-k của teacher cho số hạng thuận. Khibeta > 0, chưng cất dựa trên server yêu cầuloss_top_k == 1và chỉ hỗ trợ token top-1 nghịch"sampled". - loss_add_tail (
bool, tùy chọn, mặc định làTrue) — Liệu có thêm một bucket đuôi đại diện cho phần khối lượng xác suất còn lại nằm ngoài miền hỗ trợ top-k đã chọn khi tính toán loss hay không.
Các tham số kiểm soát việc tạo nội dung theo chính sách
- num_generations (
int, tùy chọn, mặc định là1) — Số lượng câu trả lời cần tạo cho mỗi prompt trong quá trình tạo on-policy. - generation_batch_size (
inthoặcNone, tùy chọn) — Số lượng prompt duy nhất trên mỗi worker cho mỗi bước tối ưu hóa. Nếu làNone, giá trị được tính từ(per_device_train_batch_size * gradient_accumulation_steps) // num_generations. - top_p (
float, tùy chọn, mặc định là0.95) — Tham số lấy mẫu Top-p (nucleus) cho việc tạo nội dung on-policy. - top_k (
int, tùy chọn, mặc định là0) — Tham số lấy mẫu top-k cho việc tạo nội dung on-policy.0tắt bộ lọc top-k.
Các tham số điều khiển vLLM cho việc tạo sinh của student
- use_vllm (
bool, tùy chọn, mặc định làFalse) — Có sử dụng vLLM để tạo các câu trả lời on-policy từ mô hình sinh viên hay không. - vllm_mode (
str, tùy chọn, mặc định là"colocate") — Chế độ cho tích hợp vLLM của student. Hoặc là"server"hoặc là"colocate". - vllm_server_base_url (
strhoặcNone, tùy chọn) — URL gốc cho máy chủ vLLM của student. Nếu được cung cấp,vllm_server_hostvàvllm_server_portsẽ bị bỏ qua. - vllm_server_host (
str, tùy chọn, mặc định là"0.0.0.0") — Host của máy chủ vLLM sinh viên. - vllm_server_port (
int, tùy chọn, mặc định là8001) — Cổng của máy chủ vLLM sinh viên. - vllm_server_timeout (
float, tuỳ chọn, mặc định là240.0) — Thời gian chờ để kết nối với máy chủ vLLM của student. - vllm_group_port (
int, tùy chọn, mặc định là51216) — Cổng cho nhóm cập nhật trọng số vLLM (trình liên lạc NCCL). - vllm_gpu_memory_utilization (
float, không bắt buộc, mặc định là0.3) — Tỷ lệ sử dụng bộ nhớ GPU cho engine vLLM của student được đặt cùng vị trí (colocated). - vllm_tensor_parallel_size (
int, tùy chọn, mặc định là1) — Kích thước song song tensor cho engine vLLM của student được đặt cùng vị trí. - vllm_max_model_length (
inthoặcNone, tùy chọn) — Chiều dài chuỗi tối đa của mô hình cho bộ xử lý vLLM được đặt cùng vị trí. - vllm_model_impl (
str, tuỳ chọn, mặc định là"vllm") — Backend triển khai mô hình cho vLLM. Sử dụng"vllm"hoặc"transformers". - vllm_structured_outputs_regex (
strhoặcNone, tùy chọn) — Mẫu Regex cho structured outputs của vLLM. - vllm_sync_frequency (
int, tùy chọn, mặc định là1) — Tần suất (tính bằng số bước huấn luyện) để đồng bộ trọng số của mô hình học sinh sang engine vLLM. - vllm_enable_sleep_mode (
bool, tùy chọn, mặc định làFalse) — Bật chế độ ngủ của vLLM để chuyển trọng số của student ra ngoài trong bước tối ưu hóa.
Các tham số kiểm soát ghi log
- log_completions (
bool, tùy chọn, mặc định làFalse) — Có nên ghi nhật ký một mẫu các cặp (prompt, completion) mỗilog_completions_stepsbước hay không. Nếurichđược cài đặt, nó sẽ in ra mẫu đó. Nếu ghi nhật kýwandbvà/hoặctrackiođược bật, nó sẽ ghi mẫu đó vàowandbvà/hoặctrackio. - log_completions_steps (
int, tùy chọn, mặc định là100) — Số bước giữa các lần ghi log completions. Chỉ được sử dụng nếulog_completionslàTrue. - num_completions_to_print (
inthoặcNone, tùy chọn) — Số lượng completions cần in ra. Nếu làNone, tất cả các completions sẽ được ghi log.
Lớp cấu hình cho experimental.iw_opd.IWOPDTrainer.
Mở rộng TrainingArguments với các tham số cụ thể cho kỹ thuật chưng cất tri thức. Cấu hình này độc lập với SFTConfig — tất cả các trường cần thiết đều được khai báo tại đây.
Sử dụng HfArgumentParser, chúng ta có thể chuyển lớp này thành các đối số argparse có thể được chỉ định trên dòng lệnh.